#web-development
2 messages ยท Page 87 of 1
so
would it be
according to the docs both do that same thing
dict.key['example of a key']
dict.key = dict['key']
So the error you are getting is that dict_to_be_passed is not assigned
so can you show the render_template function you use to call this?
which route is giving the error
@app.route("/UpdateKnowledgeArticles")
@login_required
def knowledge_articles():
return render_template("knowledge_articles.xhtml", dict=urls_311)```
So in your template the value you would reference is dict not dict_to_be_passed
because in the render_template function you are passing the variable dict so that is the one you would be able to reference in the template
It is and you shouldn't use it
return render_template("knowledge_articles.xhtml", my_dict=urls_311)
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Knowledge Articles</title>
</head>
<body>
{% extends "staff_parent_template.xhtml" %}
{% block content %}
<h1> Welcome to the Knowledge Articles page </h1>
<p> these are the new articles for today </p>
<h3>DICTIONARY: {{ my_dict }} </h3>
<h3>DICTIONARY FIELD: {{ my_dict['field_name'] }}</h3>
{% endblock %}
</body>
</html>
Make sense?
That means that you are passing a list instead of a dictionary
yeah
so it would be something in your processing of urls_311
yeah indeed urls is a list
urls_311 = []
but the functino
def parseXML(xml_string):
# parse xml
prefix = "{http://www.sitemaps.org/schemas/sitemap/0.9}"
dt = datetime.now(timezone.utc)
root = ET.fromstring(xml_string)
for url in root.iter(f"{prefix}url"):
for loc, time in zip(url.iter(f"{prefix}loc"), url.iter(f"{prefix}lastmod")):
obj_time = dateparser.parse(time.text)
if obj_time >= (dt - timedelta(days=3)):
# print(loc.text, "---", time.text)
urls_311.append({"url": loc.text, "last update": obj_time})
#print(urls_311)
return urls_311```
so it's a list of dicts O.o
urls_311.append({"url": loc.text, "last update": obj_time})
#print(urls_311)
return urls_311```
or tuple or something?
what is .xhtml format?
Give me one second
k
I need to create an example
hey everyone! anybody available to help with a flask-sqlalchemy problem?
So @swift sky I don't know if you're using the dict correctly
oh
Dictionaries are data structures that store a key value pair
yes
keys should be unique
oh
Luckily you already have a unique key
why woulnt they be unique
urls_311[loc.text] = {
"last update": obj_time
}
yeah each url is unique
That statement makes it so that each url is created into a dictionary entry
the value for the entry is another dictionary that holds attributes about the url
well
'url0': {'last_update': 'some_time'}
yeah i understand
so you would get entries that look like that
what do you mean?
the value for the entry is another dictionary that holds attributes about the url
@errant spear this
like wouldn't you want to just do url & time
You could absolutely do that
that would 100% work the key is the url and the value is obj_time
I just thought you wanted it split up because that is the way you had it before
hmm
If I were you I would do it as urls_311[url] = obj_time
If I were you I would do it as
urls_311[url] = obj_time
@errant spear where are you doing this
def parseXML(xml_string):
# parse xml
prefix = "{http://www.sitemaps.org/schemas/sitemap/0.9}"
dt = datetime.now(timezone.utc)
root = ET.fromstring(xml_string)
for url in root.iter(f"{prefix}url"):
for loc, time in zip(url.iter(f"{prefix}loc"), url.iter(f"{prefix}lastmod")):
obj_time = dateparser.parse(time.text)
if obj_time >= (dt - timedelta(days=3)):
# print(loc.text, "---", time.text)
# THIS IS THE LINE BEING CHANGED
urls_311[loc.text] = obj_time
#print(urls_311)
return urls_311
Like that
what should I do with urls_311 = [] at the top of the page
urls_311 = {} creates an empty dict
No
It will be a dictionary with many key-value pairs with the keys being urls and the values being last updated times
hmm
so i tried it
jinja2.exceptions.UndefinedError: 'dict object' has no attribute 'key'
hmm one sec
this is prob why
<h3>DICTIONARY FIELD: {{ dict_to_be_passed.key['url'] }}</h3>
yes
Not quite
it would be the url
and the way to access it in jinja2 is
{% for url in my_dict %}
{{ url }}
{{ my_dict[url] }}
{% endfor %}
make sense?
I have a lot of questions
Ok shoot
uhhhh
when you use my_dict
i guess that would be equivalent to dict_to_be_passed
<h3>DICTIONARY FIELD: {{ dict_to_be_passed.key['loc'] }}</h3>```
yes
also, do i need both h3 headers
or whatever is on the left side of the equals in render_template
No you can do it in one
Unless you want a line separation between them
naw
i changed it to this
DICTIONARY FIELD: {{ dict_to_be_passed.key['loc'] }}</h3>```
and so now I will try to make it like so
wait
so i don't need this anymore?DICTIONARY FIELD: {{ dict_to_be_passed.key['loc'] }}</h3>
cuz im looping through the dict
{{ dict_to_be_passed.key['loc'] }} would throw an error
first because the syntax is wrong
the syntax is either
{{ dict_to_be_passed.loc }} or
{{ dict_to_be_passed['loc'] }}
secondly it would throw an error because that would search the dictionary for a place where key = 'loc'
the keys are the urls
so and the values are the locs
so to get the loc for each url you would need {{ dict_to_be_passed[url] }}
because that would access the value at that key
does that make sense?
yes
this is what i have now
but it looks like I could get rid of the last line
<h3>DICTIONARY: {{ dict_to_be_passed }}
{% for url in dict_to_be_passed %}
{{ url }}
{{ dict_to_be_passed[url] }}
{% endfor %}
DICTIONARY FIELD: {{ dict_to_be_passed['loc'] }}</h3>```
DICTIONARY FIELD: {{ dict_to_be_passed['loc'] }}</h3> this line will still throw an error
my bad
i just didnt update it
i dont need that line though
since you are looping throught he dict already?
right
so im going to delete it then
{{ dict_to_be_passed }} will print the whole dict
{% for url in dict_to_be_passed %}
{{ url }}
{{ dict_to_be_passed[url] }}
{% endfor %}
``` will loop and print the url and location for all the entries
what's the difference
however....
hmmm and what does your render_template statement look like?
@login_required
def knowledge_articles():
return render_template("knowledge_articles.xhtml", dict_to_be_passed=urls_311)```
it may be how my parser script is running
That's my guess
meaning, the ordedr of things being run, and the imports
since its returning an empty dict
thank you for your help
Instead of wrapping try:except around all my code, is there another way to log errors that may occur? I have over 12 files, and at least 3000 lines of code
Flask btw
anyone have an idea why elasticsearch isn't finding the indecies on heroku?
It works locally, and that is what is confusing me haha
how do i conntect css to html , im using flask
and i have
base.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="mystyle.css">
<title>{% block title%}{% endblock %}</title>
</head>
<body>
{% block content %}
{% endblock %}
</body>
</html>
body {
background-color: cadetblue;
text-align: center;
}
both in same fodler
you have to create a static directory in the same level as your templates directory
then after you put your css in the static directory
then depending on how you set up your html files, you use the code
<link rel="stylesheet" href="{{ url_for('static', filename='mystyle.css') }}">
you can also use the static directory for imgs and stuff that you use to style your site with
i have base.html and just extend it in other tempaltes , do i just put it in base.html?
yes you can just put it in your base
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="{{ url_for('static', filename='mystyle.css') }}">
<title>{% block title%}{% endblock %}</title>
</head>
<body>
{% block content %}
{% endblock %}
</body>
</html>
what does it mean?
it should be like this
\app
\static
.css
\templates
.html
doesnt matter really
^
just add it to your path to le file
still 404
that is because the file path you are giving is not where your .css is
cuz you didnt do the css/ bit
css/mystyle.css?
yus
anyone have elasticsearch in a heroku flask app working?
I keep getting a peculiar error
is it normal that flask doesnt debug when css updates?
body {
background-color: rgb(57, 36, 173);
text-align: center;
font-size: medium;
}
form {
background-color: chartreuse;
font-size: large;
}
o.0
after refreshing
and suddently i dont get the get css notification in termianl
only get i get
what browser is that?
opera gx
do the dev tools open, if you hit F12?
nothing happens with f12 , lemme run the page on chrome
might also work with ctrl+shift+i
right, go to "Network" and see if the checkbox for "Disable Cache" is enabled.
its disabled
enable it, and keep it enabled.
whenever you have the dev-tools open, the browser now won't cache your css files etc.
and forces them to re-download
so i need to refresh with dev tools open?
preferably
yup , only works with dev tools open
I recommend getting used to dev-tools anyway. They're very helpful for debugging and adjusting CSS
usually browsers have a way to "reload without cache". In most browsers it's something like Ctrl+F5 or Shift+F5
its my first day working on web dev soo advices are very welcome
ctrl+f5 in opera will reload without cahge
yes, if you go to "Element" tab in dev tool, you can go through your html hierarchy, inspect each element, and see the CSS rules that apply and change them in the browser directly.
thats cool , but later they wont save even tho its my local host right?
no, those changes are only temporarily, until you reload the page
alright , thank u :3
Should this 2018 web development tutorial I found be fine to learn the basics or has there been any major updates within that time I should keep in mind so I don't learn outdated things
it should be fine, just becareful of outdated packages or version differences
YOOOOOOOOO
I finally fixed the stupid issue I have been having for the past week
lets go
in django, whats the difference between DEFAULT_FILE_STORAGE and STATICFILES_STORAGE?
@bright spindle https://tartarus.org/james/diary/2013/07/18/fun-with-django-storage-backends
DEFAULT_FILE_STORAGE is used when you want to store file-like things attached to your models, using field types like FileField and ImageField; STATICFILES_STORAGE is where the static files pulled together from apps and your project by the collectstatic command end up.
is there instances where you would actually need different ones
STATICFILES is for developer-provided files such as Html, Css, and Js
also for some reason STATIC_URL has become completely useless, while AWS_S3_CUSTOM_DOMAIN seems to take over the work
They usually come from your apps
but i dont know if its useless or if its nessesary somewhere
i put my static files on the cdn
DEFAULT_FILES_STORAGE is where.. I think.. django stores uploaded files. User uploaded files, from Filefield and similar
to put less strain on the servers (or will it cause more strain, if it has to call the data, then inject the info and then return the data?)
Then you should point your static url at the cdn
static url is usually used in templates like {{ STATIC_URL }}img/logo.png
There's also STATICFILES_STORAGE
i just do
{% static 'foo/style.css' %}
right, that's correct
but it seems STATIC_URL really doesnt do anything
What that does is finds the appropriate link to the static file via STATICFILES_STORAGE
thanks for the help bast and sambyte! I also do wonder if im just making things slower by using a CDN for serving STATIC_FILES
i just noticed... the source said its a smart idea to do so, but what makes it faster to load, django still has to receive the data, inject the data and then return the site
While it won't reduce connection latency directly, it will reduce sending load on your server
they still need to get the html from django, but it does mean that everything else comes from elsewhere, which is usually an improvement
the improvement is that it allows static files e.g. css and png to be served trough a cdn
that is a huge bonus
that makes me wonder... if the html actually gets served from cdn or from file storage, ill try that tomorrow 
hi im noob im trying to create a template in django but I think I have an error with routing? Thankful for your insights
File "C:\Python38\lib\importlib_init_.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in call_with_frames_removed
File "C:\dev\Projects\CookingBlog\CookingBlog\CookingBlog\urls.py", line 18, in <module>
from . import views
ImportError: cannot import name 'views' from 'CookingBlog' (C:\dev\Projects\CookingBlog\CookingBlog\CookingBlog_init.py)
I'm following this https://djangocentral.com/configuring-django-templates/ but was stuck on this for the past hour
wats oganaj
hi im noob im trying to create a template in django but I think I have an error with routing? Thankful for your insights
@meager coyote You are trying to import "views" from the current directory (CookingBlog), but theres no "views" file in that directory
Here's the scope which you're trying to import views from
@meager coyote read Oganj backwards
how would i go about importing it from the blog directory?
@meager coyote from blog import views
@meager coyote read Oganj backwards
@noble star jnago?
It was supposed to be django, but my spelling is lacking
Is there a way with Flask to make it so a page is only accessible to people inside the network? I have Flask operating as a webhook listener but I would also like to have a page with buttons I can use to trigger the same events that the webhooks do
Safest bet would be to not have those buttons on the same app thatโs facing the web even if you think you lock it down.
Make that button app to trigger your hooks be local only. Donโt risk it.
It just occurred to me that since I'm not checking the authenticity of the webhook messages that's totally possible. Thanks!
@versed python regarding this tutorial you had given me earlier: https://dev.to/ignisda/setting-up-user-authentication-with-nuxtjs-and-django-rest-framework-part-1-5gji
As I said, most tutorials stop at how to signup the user and don't tell how to actually use that information in other APIs. Your tutorial also misses on this part.
What I wanted to know was how to use this token to validate requests once the signup and login is complete. And this is what I needed to do for that:
# For function based views, add the following decorators
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def func_view(request):
#then use the following to get the user id of the user who made the request
user_id = request.user.id
And
# For class based view, use the APIView class
class ClassView(APIView):
#then add the following permission class
permission_classes = (IsAuthenticated,)
def get(self, request):
#then use the previous syntax to access the user information
user_id = request.user.id
Unless I know this part, creating a login or signup doesn't serve much purpose as I still wouldn't know how to authenticate the requests.
@merry geode alright that's a fair point, and I missed it. It will add it to the tutorial as soon as I can. Thanks for the input!
Hello all ๐๏ธ - I would like constructive feedback on the UX + code layout in my Django app - https://github.com/huangsam/chowist/ - feel free to provide it in the DMs or as a GitHub issue / feature request
Hello all ๐๏ธ - I would like constructive feedback on the UX + code layout in my Django app
@deft flower looks nice, but a little bit dry. Would be good to add some images. Maybe Cards (as I see you are using bootstrap) to display the restaurants list (https://getbootstrap.com/docs/4.5/components/card/).
Looking for a method/technology: I have an app that trains ML models and generates forms for users. All models are saved in a S3 bucket. After a user fills out a form and wants to predict something the app downloads the models from the bucket and uses it for the prediction. As the user can simply reuse the form I think that redownloading the model is unefficient. Is there a better way? Download the model to a temporary folder? Use cache?
in django templates, how do you handle things like page title, which has to be in the title tag and 2 meta tags, allowing child templates to change the title in one place and having it use the title in 3 places
sending the title as a context var seems quite silly
in django templates, how do you handle things like page title, which has to be in the title tag and 2 meta tags, allowing child templates to change the title in one place and having it use the title in 3 places
@dapper tusk{%with foo="bar" %}<title>{{ foo }}</title>{% endwith %}or something to that effect?
https://docs.djangoproject.com/en/3.1/ref/templates/builtins/#with
how would I override a with in a child tag
can I do
with foo={%block bar%}"bar"{%endblock %}
I think it'd be rather
{% block block_to_override %}
{% with title="foo" %}
<title>{{ title }}</title>
<meta...>{{ title }}
{% endwith %}
{% endblock %}
Don't think you can just pass a variable from a child template to a parent, if that is what you'd want to do...
But I mostly use Django for APIs and ORM lol
Don't think you can just pass a variable from a child template to a parent, if that is what you'd want to do...
well, this is literally what I want to do, so I guess I will just send the title from the view
Probably the most logical.
well, this is literally what I want to do, so I guess I will just send the title from the view
@dapper tusk you can also create a {% block title %}MySite - {%%} as a prefix and then in the child templates, you put {% block login %} Login {%%} or something, then you will controle from de template itself.
elaborate please
This in the base template
and then in the child templates
just make sure to put before the {% block content %}{%%} as usually it represents the <body> of the page
but yea, you can do either way, depends on your approach
are you on windows?
yes
The last time I was on Windows, and had the same problem. Could not find any solution.
I switched to Linux
Actually I got solution
really?
yes
what was it?
@fallen peak the problem with that is I need the same title in multiple places
@rough tulip I see, i did not know windows even bothers reading shebangs
well that's something new for me, thanks
@fallen peak the problem with that is I need the same title in multiple places
@dapper tusk it's the same title to all pages?
one title per page, but on multiple places in that single page
{% with rtitle=title|default:"redacted" rdescription=description|default:"redacted" %}
<title> {{ rtitle }}</title>
<meta property="og:type" content="website">
<meta property="og:url" content="{{request.path}}">
<meta property="og:title" content="{{rtitle}}">
<meta property="og:description" content="{{rdescription}}">
<meta name="title" content="{{rtitle}}">
<meta name="description" content="{{rdescription}}">
{%endwith%}
How to integrate TSX(TypeScript React) with Django?
generally, you make an API in django and talk to that from react
you create separate backend and frontend projects @somber aurora
look into django rest framework
How to do that?
@somber aurora better yet, useariadne. DRF is getting dated.
(And REST as a whole)
Well, it still works
and there's definitely jobs that require it
But if I started a new project, I would definitely go GraphQL
^
{% with rtitle=title|default:"redacted" rdescription=description|default:"redacted" %}
<title> {{ rtitle }}</title>
<meta property="og:type" content="website">
<meta property="og:url" content="{{request.path}}">
<meta property="og:title" content="{{rtitle}}">
<meta property="og:description" content="{{rdescription}}">
<meta name="title" content="{{rtitle}}">
<meta name="description" content="{{rdescription}}">
{%endwith%}
@dapper tusk Well, since theres a lot of dynamic meta tags, i think you'll be better of passing the variables as context on the return render_template() and grabbing them with the {{}} jinja syntax
How can website change data without redirecting and wont letting others edit them
like mee6
its probably a server-client relationship
uh?
its probably preset
the part you see is just a front end
there goes many processes in the background
one by one,
as one finishes, the front end changes
if im not wrong
@cyan violet look into Ajax, that's where you would want to start
Ajax is API-calls based, isnt it?
but dynamic websites are no childs play, and if you want to make a good looking one, you'd have to learn a frontend framework
@vague ibex yeah it's present in most browsers nowadays
be it front end framework or pure html css, both are usuable
all actually
Could i use ajax to send forms without refreshing
it went out of use and was replaced by modern frontend frameworks now
@cyan violet yeah
That could work
you can try websockets too
to check if user has perms i would need to get sessions tho
but you should probably switch to an actual frontend framework instead of Ajax
uh
Ajax works pretty fine with javascript
do you need a front-end framework?
ig DOM manipulation with javascript works pretty fine
if you dont want to waste your precious time learning react/vue
or you can look into intercoolerjs if you don't want to learn an entire framework
my experience with ajax has been not good, hence i am recommending alternatives.
it it works out for you, then cool
never used them so idk
once u learn using websockets, its way too easier and powerful
today's servers use websockets
for communicating
be it PHP, node or flask, websockets are super common
@cyan violet yeah you can
@cyan violet everything can be hacked, assuming there is a good hacker behind the computer
but it's generally safe
i mean i dont want that my javascript would just send a request to a url with guild id that people could easily copy
i think you should implement it first, and worry about security later
one step at a time dude
then ask in #cybersecurity if you want to have security side cleared up
that it just redirects you to a url where it changes it
@cyan violet ajax doesn't work that way, you must have done something wrong
i dont use ajax
i just do document.location.href
lmao
and add values like
/config/guild_id/nex_config
that's very inefficient and unmaintainable code imo
web sockets are better right
Well i think you can make chat apps with them too
most chat apps would use something more robust than ajax
something like an actual frontend framework
i mean web sockets
well maybe, idk
@cyan violet websockets are used for client-server communications.
SocketIO is a multi-client chatting platform
You can use it in your projects tho.
What is the main thing are you trying to do?
a single bot at a time?
yeah
so, basically you're retrieving data from your own database or from any other external database through APIs?
mongodb
Its simple. Just connect the server with the database properly. Check if everything is okay and then further, make the functions to interact with the front end accordingly
Web dashboard
@cyan violet is it like a result for a searched input?
what
what kind of dashboard is it? when does it appear ?
Like mee6 simple
like this?
I cant really get what kind of dashboard you're referring to.
alright
You can just use websockets then
Socketio seems easier tho
socketio is a chat room -like thing
you need a dashboard if im not wrong
so where's the chatroom coming from?
nowhere
'o.o
I can't really get what you're talking about.
You want a dashboard so from where is the chatroom coming]
i just need frontend to send Something WHere it checks userid from sessions and it can send a guild_id with it too
so use websockets
simple javascript or event listeners works too
whenever someone clicks, you can pass on the details to ur backend
the backend will process and do whatever is required and then send back the result
you can research more on websockets
you can also cache the results for a particular user so that you dont need to do it again and again
Whats a good flask web socket
I'd refer this to you.
no worries ๐ ^_^
I've linked my Django Project to my react
How to render my more tsx pages in my views?
is there someone here who uses Selenium for testing or automating with python?!
i did once, what do you need? @hybrid gale
also goto #unit-testing, you'll find better help there
I wrote some code to automate googling stuff just for fun (as always ), and I want someone who writes python code better than me to look at it!!
@versed python, this is the code https://www.youtube.com/watch?v=E-Nx8zwjSUU&list=PLu9cO88jTb8Awy5jYmg5Dc_WuedVKgDVs
I've used the selenium framework or library as you prefer to call it, in this case to automate some googling. Which wasn't the purpose of this video, and that is to collect some new Pythonic concepts and code writing along the way.
Hello, I'm working on a flask app and deployed it to Heroku. The container is up but as you can see uwsgi fails. It seems it cannot bind port 80. Any idea how can I fix that?
IIRC, heroku gives you a port you are supported to bind to in a PORT env var
yeah
yeah, I do not use heroku sadly, but that sounds right haha
like 5050 or something
I added this line, but doesn't seem to fix the problem
are you using docker?
@acoustic oyster heroku-cli to be more accurate
you may not want a default, you probably want it to raise an exception if "PORT" is not defined
so I would set 5000 to none, or omit it
Ok but where do I specify that? In the dockerfile?
I mean just on that line, you want to os.environ.get("PORT"), if the port is somehow wrong, you do not want it to raise a "failed to bind" error from port 5000. It seems that heroku sets the "PORT" environment variable for you.
Ok
The biggest thing I could think for that error is improperly configured permissions
@hybrid gale i thought you were a beginner, turns out you are better than me lol.
I do not use heroku, but here is what I have in docker for a django/nginx container
again, i suggest you goto #unit-testing, they will help you
I do not use heroku, but here is what I have in docker for a django/nginx container
@acoustic oyster
Ok I'll try, I'll check that more thank you
@acoustic oyster what does the -d flag to useradd do?
if only I knew, LOL
this is from another project, I actually did not write this. But thought it may help
it sets the dir where the user will be created
shhhh, haha
I need this
jk, patryk plz help, like you helped me
@acoustic oyster what does the
-dflag touseradddo?
@versed python sets the home directory to the passed value (/django)
Also, I never used Heroku, so I won't be much help
I want to build an e-commerce website using flask
Can anyone tell me what flask extensions are great to do that?
I have a question, is it far more costly to use ModalViewSets inside Django rest framework than simple function methods ?
Can anyone tell me what flask extensions are great to do that?
@nimble epoch You can always look at saleor. It's BSD-licensed (based on Django, rather than flask). Probably better than writing your own from scratch.
https://github.com/mirumee/saleor
@lethal orbit the problem is i want to write it from scratch
More comfortable with my own program
Then you need to decide on the features, and look for packages that fill those needs.
- DB. Either use a DB library or an ORM (SQLAlchemy).
- User management. See what the standard is (I never did user management in Flask, so I can't help there)...
- Etc.
Decided how you want to handle communications. API, or just templates?
If API, REST or GraphQL?
Flask-RESTful seems like a good bet for REST. Ariadne is great for GraphQL, but I only worked with it in Django, not Flask.
I do know they have support.
Expect to do a lot of research and spend a lot of hours lol
I have a question, is it far more costly to use ModalViewSets inside Django rest framework than simple function methods ?
@native tide In general, there is probably a performance hit using a built in ViewSet, but I would not consider it anywhere near impactful enough to make the decision as to which one to use
Hi guys sorry to interrupt, which channel would you recommend I go to for my project idea help/feedback?
@buoyant escarp Whats your idea?
well it's like using a qr code to send the user to leave feedback on a website/webapp for a product they just purchased
was wondering if it's possible using Django framework for it
I've used Flask but never Django
@lethal orbit thanks a lot man i really needed that
And of course you mean user management like django admin??
Or itโs authentication system?
Authentication system.
was wondering if it's possible using Django framework for it
@buoyant escarp That should definitely be doable. I think Django is a great fit, tbh.
I use a Python back-end to generate bar-codes for a store with physical goods.
This channel is a good place. You can also always DM me if you have some questions. I will be busy tonight though ๐
do you guys use elasticsearch with django ? Is it worth replacing django built in python search modules rather using elasticsearch?
built in Python search modules??
How much hosting costs sites like tinypng has to pay if they have 100K daily visitors?
Yo! I have a string that I am getting from a REST API, but a lot of the text is being displayed as HTMl placeholder codes, like ' instead of just an ' character. Does anyone know of a python module that handles replacements of these values with their actual meaning?
Yo! I have a string that I am getting from a REST API, but a lot of the text is being displayed as HTMl placeholder codes, like
'instead of just an'character. Does anyone know of a python module that handles replacements of these values with their actual meaning?
@muted groveurllib.unquote
@vestal hound I appreciate the suggestion, but that does not handle the specific ' placeholder type
that only handles url placeholders like %20 and such
I need HTML placeholders, not URL placeholders
For reference, I found the solution, it is html.unescape(string)
Does anyone know how to work with the offset parameter in flask? Im trying to get 400 search results to paginate in my jinja template, but unfortunately the propublica api https://projects.propublica.org/api-docs/congress-api/ doesn't include a limit parameter or a next page function. So basically I'm trying to loop through the offset, make the GET api call and then decrease the offset by 20. During each loop I'd have to save the results returned by the api call, but how do I store this data so I can pass it to my jinja template? This is how my code looks
@app.route('/search/member/<member_id>')
def get_member_info(member_id):
"""Retrieve individual government official data on link click"""
offset = 400
while offset >= 0:
res = requests.get(
f"{MEMBER_VOTE_POSITION_API}{member_id}/votes.json", headers={'X-API-Key': key}, params=offset)
offset -= 20
data = res.json()
Can someone please help me figure this out?
hey guys! im bored atm and wanting to learn more html, css, and js etc. can someone give me a website idea n ill start it up and try to design it, please TAG me to get my attention thanks alot
@rotund token https://www.internetingishard.com/
Friendly web development tutorials for complete beginners
something like a website idea
@rotund token website for your pet, a portfolio, or make a discord bot and make a website for it
hmmmm ok
@zealous cloud you need to pass the variable in this case member_id to the template, to do that you can use this code:
return render_template('template.html', member_id=member_id)
After this you can call the variable from inside your template by doing something like this {{ member_id }}
If you need to save results on each loop then better create a dictionary or list at the beginning of the function and append the result of each loop to that list or dictionary (depending on how you want go save things)
@wind escarp Sorry I definitely should've posted the entire code block for the route. I've done this and got it to work, the api unfortunately only returns 20 results per call. Im trying to figure out a way to get 400 results via the offset method. I dont know how to save that data however, this is what Im struggling with. Here's my full code
@app.route('/search/member/<member_id>')
def get_member_info(member_id):
"""Retrieve individual government official data on link click"""
res_object = {}
offset = 400
while offset >= 0:
res = requests.get(
f"{MEMBER_VOTE_POSITION_API}{member_id}/votes.json?limit=100&offset={offset}", headers={'X-API-Key': key})
data = res.json()
res_object.update(data)
offset -= 20
# return data
members_data = data['results'][0]['votes']
return render_template('search/officials_voting.html', members_data=members_data)
Yea thats what im working on at the moment, but how would I save this data and continue to update it? Dictionaries dont have an append method, so is there a way to continually add the results of an api call to a dictionary?
Are you sure you are adding data to res_object?
No i just printed it. Im definitely not
That's where you should add that and then you can retrieve it
Although I can suggest using sqlalchemy
Flask-SQLAlchemy is easy to use
This project is making use of flask-sqlalchemy. The issue with this feature is that this is government voting information that changes daily, so every time you visit the page to view voting records you should see the latest info, This is why im not saving this data, I would need to constantly update it.
Sorry maybe I didnt explain that correctly or maybe my understanding is incorrect. It's my first time using flask-sqlalchemy. It's been great so far, but maybe I dont understand it well enough
Now that's new for me, I haven't worked around that yet so I can't help, sorry.
I am sure there are other tools to do that, it's not impossible but I just don't know how.
Try asking on flask reddit channel
Yea thank you for chiming in. I've posted a question there. So i inserted a print statement after the data = res.json() line inside my while loop and I am getting the desired information. The issue now would be somehow saving it into one big object that I can pass to my template and use jinja to paginate the data. Thank you again for helping. Most apis I've worked with have a num pages or num results option you can work with so you can request 100 results with one api call. This api for some reason only allows 20 results per call. Oh well, that's the fun part about working with apis. They all work differently.
I want to create a custom django model field.I want it to take email from user and store it in database in bytes form.How to create such a model field?
@stable kite override the save method and convert that field to bytes
@versed python I don't want to create model but custom model fields that are encrypted
@stable kite maybe this will help? https://docs.djangoproject.com/en/3.1/howto/custom-model-fields/
I saw that but i did'nt find answer to my question
what model are you trying to encrypt? Is it a custom user model or something else
show your models.py
I want to create open source model fields that encrypt that encrypts the data
from django.db import models
from .cryptography import Encrypter,Decrypter
class EncryptedCharField(models.BinaryField):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def from_db_value(self, value, expression, connection):
print('called from_db_value')
if value is None:
return value
return (Decrypter(value)).decode()
def to_python(self,value):
print('called to_python')
if value is None:
return value
else:
return Encrypter(value)
def get_prep_value(self, value):
print('called get_prep_value ')
if value is None:
return value
else:
return Encrypter(value)
def deconstruct(self):
name, path, args, kwargs = super().deconstruct()
print(name,path,args,kwargs)
return name, path, args, kwargs
I am creating an open source project not creating this for my project
this looks right to me, whats the problem?
I am working on this project because i did'nt find any project like this which encrypt data and and we can retrieve it again
This is for text
I want it to be for integer,email,etc
id = db.Column(db.Integer, db.Sequence('users_id_seq', start=100000000000000000000, increment=1), primary_key=True)
here the Sequence isn't working
it doesn't start with 100000000000000000000
but it startswith 1
I'm using SQLAlchemy ORM
with Flask, and Python
Python 3.8.5
for you uni students out there, found this pretty cool repository for a Rate My Professor scraper (scrapes RMP webpages and uses their hidden API).
It's two years old so I started working on it, cuz it's useful for another tool I'm working on. Lemme know if any of u are interested in helping!
don't integers have a limit?
Anyone?
@versed python can you help me?
anyone there?
@native tide did it reach the int limit?
I don't know
@stable kite I don't think I can, I am not that experienced about what you want, sorry
ok
Well, then Do I need to make it, bigint?
INTEGER. The value is a signed integer, stored in 1, 2, 3, 4, 6, or 8 bytes depending on the magnitude of the value.
That is, you can only store values from -2**63 to (2**63-1). What does SQLite do for a value outside of this range? As we saw earlier, it switches over into floating point. Again, quoting from the SQLite reference:
We recently tackled an issue that seemed rather impossible โ an
unsigned 64-bit value was greater than the maximum value that a
64-bit value โฆ
Might not be ur problem, so not sure anymore
I'll try bigint
Let me migrate now
forgot to migrate
now not working
@worn rapids I get like this
INFO [alembic.ddl.postgresql] Detected sequence named 'users_id_seq' as owned by integer column 'users(id)', assuming SERIAL and omitting
I'm using PostgreSQL
done
removed everything
and retried again
but still the ID is same
it startswith 1
{
"users": [
{
"email": "sairamkumar2022@gmail.com",
"id": 1,
"keys": [],
"name": "Sairam",
"password": "123456789",
"type": "developer"
},
{
"email": "ponvannan2006@gmail.com",
"id": 2,
"keys": [],
"name": "Ponvannan",
"password": "28454",
"type": "developer"
}
]
}
Ignore password. This is a testing database, which I have hosted locally
99% complete
Only the seq needs to be fixed
@worn rapids ?
Hello, I am trying to style my webpage with flex and I am having so much trouble making simple 2 column page... It looks like this now:
How do i extend second row (highlighted) to the same width as first row?
Are you using a CSS framework @maiden kraken ? Most of them allow you to set a number of columns for your rows:
<!-- bootstrap example -->
<div class="row"><div class=col-6>Row 1 column A</div><div class=col-6>Row 1 column B</div></div>
<div class="row"><div class=col-12>Row 2 column A</div></div>
Hello Patryk, no, I am trying to learn Flex without any bootstrap or any other framework
In that case, you probably want to assign some styles to your row class.
min-width and max-width, or fixed width
I think most frameworks use javascript to do some magic
okay, this is kinda hard coded solution which I thought can be avoided. I thought there is some magic command which expands row to width of container
In my flask application, I have something that spins up a new threading.Thread (cache eviction for rate limiting purposes). when i try to run flask db migrate, it never exits (obviously). Is there a way that i can prevent certain code from being run if flask is being invoked with flask db *, like an inbuilt environment variable or something?
okay, this is kinda hard coded solution which I thought can be avoided. I thought there is some magic command which expands row to width of container
If you have a parent container, you should just be able to setwidth: 100%;no?
You don't have to apply it to the row class. You can add a new class. .row-100 or something.
yeah, I will try, I am definiteley doing something wrong, this should be much easier
can any one help?
@frosty bluff https://dontasktoask.com/
thanks a lot
NP
ok
CSS is the worst part of web dev ๐
i want to sum of column and subtract with another column total and i know how to do this but i want this with filter like for example if seller = xyz then subtract the total anyone can look into it i will be thankful
i want to login to a website uiong requests
but it doesnt seem to work
where is the problem ?
i want to sum of column and subtract with another column total and i know how to do this but i want this with filter like for example if seller = xyz then subtract the total anyone can look into it i will be thankful
@frosty bluff can you expand? What do your models look like? What columns are you filtering? Do you want to filter on one column, or both?
@cinder plank I think you are passing string instead of variable inside your dictionary
how can i change that ? @maiden kraken
Feel free to DM if you don't want to share the code publicly.
@cinder plank well I dont know if its your full code but you probably have email defined as variable, but in dictionary you had something like "email" : "email" <-- this should maybe be variable?
i assume you want to pass real email instead of string 'email'
yes
i just put email and pass instead so people dont see my real account @maiden kraken
ah okay
@maiden kraken
what do you guys use for entering dates in a flask form field?
I want to asser that I opened the page successfully in django channels, but eve after a redirect the page status code is 200
How could I test if it did not redirect and is in the same view as before?
Guys, is it better to ask a user to login separately after they register or just log them in directly with their new account?
@versed python Iโve seen it done both ways from my perspective I donโt see an issue either way. ๐คทโโ๏ธ for convince I prefer to be logged in straight away ^^
If you need user to confirm (e-mail, phone number), you can wait for confirmation. Otherwise, no reason to do it in two steps, IMO.
cant people from somewhere else connect to my socketio?
I mean thats true for everything exposed yh
which is why you implement auths and cors
is there any way to block direct access to django rest api, like from browsers and such, I want it to accept only ajax requests
Can we ask CSS here also
Can we ask CSS here also
@twilit dagger sure, it is web dev
Being a python server, probably not everyone is a CSS expert though
@errant junco change this setting and remove the browsable api renderer
https://www.django-rest-framework.org/api-guide/renderers/
Django, API, REST, Renderers
Is there a way to automatically replace all the links, scripts and hrefs in a pre-existing template with flask url_for or Django url?
I googled but couldn't find anything. Maybe I will create myself.
@marble carbon ok I did that, browsable api is gone, but still there's plain json data itself that's still visible through browser
oh ok
There's a margin between my footer and the bottom of the page
I did margin-bottom: 0;
but nothing's changed
hmm maybe you need 0px;? just guessing I am new to this stuff
How difficult do you guys think it would be to pull try and convert this data table to work with Jinja?
Porto Admin - Responsive HTML5 Template
I really like the "Rows with Details" one, i've never done this before lol
Does anyone know of any bootstrap data table templates specifically for jinja?
@maiden kraken align-items: stretch on the container
https://css-tricks.com/snippets/css/a-guide-to-flexbox/ is really helpful
wait
no
make a new container for the entire site
and make that flex
@warped timber thanks for response, I kept fighting and I've got to this conclusion:
}
.container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.row {
width:100%;
display: flex;
}
.column {
width: 50%;
}
but it was just trying blindly stuff in firefox developer
Does anyone know of any bootstrap data table templates specifically for jinja?
@sleek pecan Nope. But if you find a table that you like that takes json data, you can easily use it injinjawith javascript.
<script>
const table_data = {{ table_data_as_json }};
</script>
``` and feed that to your table. (Assuming `{{ }}` was how you printed variables in `jinja` - been a couple of years since I've last used that.)
@warped timber that's the result:
.column {
width: 50%;
}
``` You might want to do like most frameworks, and define `col-1, col-2... col-12` classes, and be able to choose which one you use. `col-6` would make sense with `50%` width (like many frameworks do).
But if you only have one style, it may be overkill.
Something to keep in mind for the future, at least.
@lethal orbit thanks a lot, that's a solid advice. I often saw scrolling through sites something like col-6, col-3 etc and I've wondered from where it comes from
@lethal orbit Would you suggest anything else? I have a mongodb that I store data in, and I want to create an html site to view it and do searches
@lethal orbit thanks a lot, that's a solid advice. I often saw scrolling through sites something like col-6, col-3 etc and I've wondered from where it comes from
Yeah, they break up rows into 12, usually. You can choose something else. Then add acol-12that takes all 12 (100%),col-3that takes 25%, etc.
Sometimes, it is better to blatantly copy the pros than reinvent the wheel lol
@lethal orbit Would you suggest anything else? I have a mongodb that I store data in, and I want to create an html site to view it and do searches
@sleek pecan do you already have a front-end framework that you use for the site? Basically any table should work, if it supports JSON data.
anyone familiar with django bakery?
Like my previous comment; find something you like and integrate it.... No point writing 10000 lines of JS to make your own dynamic tables ๐
Like my previous comment; find something you like and integrate it.... No point writing 10000 lines of JS to make your own dynamic tables ๐
@lethal orbit Nope... building it from scratch right now
I think i'm regretting creating nested dictonaries in the mongo documents, its just annyoing me now lol
Would python be good for making a web application for a controlpanel for a remote server where you can start and stop the server? or should i go for nodejs or any other things?
I feel like I learn alot better when seeing examples of what the end result would look like, wheres a good place to even go to find tables that support JSON data? i've been lookin on github
hmm
Hey all. I'm newish with flask/sqlalchemy and have built something that mostly works, except for when it doesnt. Unfortunately, it's not giving me any useful feedback when it fails beyond a 500 error response from apache2, and I would really appreciate if someone could spend a dozen minutes or so going over what Ive made to tell me if anything stands out. I'd normally google stuff and figure it out on my own, but I don't really know what Im doing wrong (especially since it does work, but then fails - and fixes itself - periodically).
@white tree No error logs?
What are some front end secret tricks that less people know about?
sadly, no. it does log "wsgi error" - but its not actually mentioning whats wrong
You can't turn on extra logging somewhere?
how do i disable static routes in django?
all I get is stuff like this:
19 [Sun Sep 13 09:47:07.200438 2020] [wsgi:error] [pid 14699] FROM pages ORDER BY pages.id
20 [Sun Sep 13 09:47:07.200544 2020] [wsgi:error] [pid 14699] 2020-09-13 09:47:07,200 INFO sqlalchemy.engine.base.Engin e {}
I could, Im just not sure where/how to turn on extra logging.
sometimes it takes days to get the error to occur, and thus far no clear indication of what causes it /why its happening, because it just seems to be like.. maybe a rate-limit caused by malicious bots? I do see a lot of scanner failures in my error.log, but I have fail2ban on so not sure how much else I can do to stop them from trying
here's a full dump of my current error.log https://pastebin.com/uH06MUi5
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
the script in question is here https://bitbucket.org/ota_hak/spa/src/master/spa.py
hi, i wanna ask something about flask. do u guys usually keep the main logic on routes or keep it separate? lets say i have a prediction using neural network, is it a good idea to put it on route files?
is it possible to iterate templates
like once u submit a giveaway with the values and everything
its creates/show the same template but with differect values
so like template for every pk giveaway
@lethal orbit Nope... building it from scratch right now
@sleek pecan fair enough :D
I like leveraging third-party things, especially for the front-endsince js is hell even if it is much better than it used to be.
Would python be good for making a web application for a controlpanel for a remote server where you can start and stop the server? or should i go for nodejs or any other things?
@sterile sphinx what kind of server? starting a remote physical server is hard to impossible... whether it is node js or django.
I feel like I learn alot better when seeing examples of what the end result would look like, wheres a good place to even go to find tables that support JSON data? i've been lookin on github
@sleek pecan I do as much of my web dev as possible using Quasar :p
https://quasar.dev/vue-components/table <-- these tables take JSON data
I have a div with margins inside a container, but the margins of that div aren't from the container border but rather from the page boundary itself. Why is this?
So when I change the screen size then it doesn't align and overflows
Anyone have any sort of experience with Cpanel i want to shoot myself because of this trash
so like template for every pk giveaway
@frozen spear depends how similar you want them, and what you are using. Django with function-based views, and have the same template but with different values? You can create acontextdict inside the view, assign it the values you want, and return a response, and access the context inside your template.
hello everyone
I would like to move this button next to the prompt
here is my html code
add css to do that
flexbox
<div class="tab-pane fade" id="Blacklist" role="tabpanel" aria-labelledby="blacklist">
<label for="input1" class="titillium-web left medium">Blacklist a website:</label>
<input type="text" id="GUI" placeholder="eg. https://google.com/" name="input1" class = "titillium-web medium-left"><br><br>
<button type="button" class="button">Add Site</button>
</div>```
@lethal orbit bit of confused but i will do more research
@native tide If you put both inside a div then give that div display:flex; then it should automatically move there
@lethal orbit bit of confused but i will do more research
@frozen spear https://docs.djangoproject.com/en/3.1/intro/tutorial03/#write-views-that-actually-do-something is a good start.
alrighty
lol
<div class="tab-pane fade" id="Blacklist" role="tabpanel" aria-labelledby="blacklist">
<label for="input1" class="titillium-web left medium">Blacklist a website:</label>
<div class="prompt">
<input type="text" id="GUI" placeholder="eg. https://google.com/" name="input1" class = "titillium-web medium-left">
<button type="button" class="button">Add Site</button>
</div>
</div>```
alright
ah okay
its also best to see live results like the inspect element in browser
u can edit there then copy paste
and save
it is a google extension
I am helping my friend
which is why i am so bad at html and css
it seems like the prompt and button are stuck together
actualy
i can inspect elemtn
if i open the html file
but i can't change css
because it's linked
i will try putting only the button in the div
not sure if that would defeat the purpose of a flexbox
no look
if the
button is linked with anothe text
so like
if u move the button
the text moves too
yea
what
the bulma css framework?
u can apply a css ontop of another css
so if ur using bootstrap or flexbox or anything
u can still
edit it
oh ok
and create ur own css
tanks
๐
@native tide also if ur doing just few css
u can do it directly in the html so
<button **style="position: relative; etc..."**>hi</button>
with the style attr
nice
hi
can someone recommend me a better design here https://i.imgur.com/dOMcvKT.png
i have been using bootstrap cards for a lot of my stuff, i want something new, any ideas?
How do I change the text color of a bootstrap button when it is hovered over?
!imporant on css
Are you looking for the :hover pseudo-class maybe? https://developer.mozilla.org/en-US/docs/Web/CSS/:hover
How do I change the text color of the button if I apply a:hover?
Because otherwise it changes the color of the entire button
What's the CSS rule you wrote?
flask
def home():
return render_template('home.html', title='CTF Foundation')
it says no template found, but the file exists
o/ folks
@shy forge I wrote
.header-a:hover{
color: #333333;
}
And the button is
<a type = "button" class = "btn btn-outline-light text-light header-a btn-lg">Contact</a>
Nothing actually changes with :hover
Did you mean .header>a or .header a? .header-a would be the class header-a
No I meant header-a since that's the custom class I gave the button
Oh, yup, see it. Then yeah, that's a css specificity issue. Try adding !important or add additional specificity.
I personally dislike most of the the css libraries out there for this right here. They over-specify their CSS rules which makes the cascade break.
Ok thanks !important worked
Now how do I align this button to the right of the navbar
There are precisely half a million ways. You're using bootstrap, right?
Yes
I think there's a class that can do it for you.
I don't remember what it is cause it's been a while.
(I use flexbox for stuff like that.)
https://getbootstrap.com/docs/4.0/utilities/float/ Try this one?
Float-right isn't working
I tried -
.navbar{
display: flex;
background-color: black;
}
.text-right{
justify-items: right;
}```
No luck
justify-items doesn't support right as a value.
Html -
<div class = "text-right float-right">
<a type = "button" class = "btn btn-outline-light text-light header-btn btn-lg">Contact</a>
</div>
I think you need float-right on the child not the container.
I tried that too
https://developer.mozilla.org/en-US/docs/Web/CSS/justify-content Try this on your flex context.
I have a really quick question
<input type="text" id="input1" placeholder="eg. https://google.com/" name="input1" class = "titillium-web medium-left">```
if I wanted to style this in css
would i do
o shit
whatever
im blind
for css i woudl do
Ok thanks justify-content:space-between did work @shy forge
titillium-web medium-left#input1 right
titillium-web medium-left#input1
that's how I would do it in css right
is I wanted to style the input
just #input1 is enough
You're asking how to select that element?
ye
And yeah, if there's an id, that's 4? points of priority and always unique.
wdym that's 4
Priority is how CSS determines which rule matters.
should i change id
It's loosely !import >>>> id > class > element, and if you combine them they are additive.
So if you have two conflicting rules for an element, one is defined by a class selector, and one by an element selector, the class selector wins.
oh
If you have two class rules, the one defined later wins.
If one has two classes, and one has one, the two class rule wins.
pepo is now confused beyond consideration
Well, you gave it an ID to work with the form, so I'd use that.
And it should just be the width attribute.
@twilit dagger what's your problem?
http://www.standardista.com/css3/css-specificity/ (Here's the fun poster about this.)
oh nice
<element> {
width: (your width)
}```
I am livesharing with my friend on my project and I'm editing a saved version in another editor and it turns out I was editing in the wrong editor
@native tide what's your probleme exactlly??
I am trying to change the width of an input box
change it from css file
input {
width: 300px
}```
yea i did that
result??
i was trying to figure out why it wasn't changing width
i was using the wrong thing
i used wrong class
and right id
then i used wrong id
check your browser version maybe.
ok nice.
I have a quesiton
for my blacklist a website thing, you are supposed to be able to add websites to the blacklist.
What I plan to do is add a click listener in the js file
and display all the sites on the page in the html
how would I add a new element every time I click the button
Not much different than Python: Somewhere in your js you define a global variable with an array, then when you press the button, you verify the input then deny_list.push(value)
What does r'^$' mean in Django
hmm
Or url(r'^contact/$')
prob some kind of regex

how is my_Btn null
there is an element with the id my_Btn
What does
r'^$'mean in Django
@twilit daggerr""means raw string,^means "string start", and$means "string end"
so r"^$" refers to an empty string..
So why is it used instead of just '' or 'contact/'
In fact, why is url() used instead of path()
url() is deprecated, pretty sure... it was the old django style
Basically pre-2.0, you used url() and regex.
Oh ok thanks
And the reason you used r"^contact/$" instead of "contact" was probably because of the way the regex matching worked....
If you don't explicitly mark the start/end, I think it might match http://example.com/sports/full-contact/hockey ...
Not 100% sure on that, but something along those lines. Good to know regex and ^/$ at any rate.
So why is it used instead of just '' or 'contact/'
@twilit dagger the regex matches the empty string and only the empty string
the empty string matches anything that contains an empty string, which is...every string
a bit counterintuitive, I know
so when clicking the button enter its gonna go to another detail view url called entries
now its sending this erorr
heres the url for that
views related to that
so the entrydetail view
i tried couple of ways but didnt worked so i left it as it is now
in the template
somehow
i didnt know how to define pk in the class
@frozen spear in the template {% url 'entries' pk=<some-int> %}
in the class, it is present as self.kwargs.get('pk')
defining self
@frozen spear you need to call it inside a method
what exactly are you trying to do with the pk in your view?
so its a hosting giveaways app..im done with the giveaway detail view and everything but now,it should generate a pk url which is Link/giveaway(some number)/entries
in that link it will see all the entries of that giveaway
so if the giveaway number is 15
it should see all entries of the giveaway 15 and redirects u to a detail view with a template when clicking a button
class EntryDetailView(DetailView):
# other stuff
def get_object(self):
primary_key = self.kwargs.get('pk')
return YourModel.objects.get(pk=primary_key)
@frozen spear
ok thanks
class Post(models.Model):
text = models.TextField()
class PostImage(models.Model):
image = models.ImageField(upload_to='images')
post = models.ForeignKey(Post, on_delete=models.CASCADE)
How can I put a constraint in place so that only 3 PostImage objects can be related to a single Postobject?
@versed python I think that isn't possible without restructuring your table
because that would amount to a check constraint on a groupby
that isn't an issue, i can just delete my table and start over again. Any idea on how to actually accomplish it?
which I believe isn't supported
okay, I'm not super experienced in this kind of thing, but my initial guess
is to add an additional field, like "image_index"
to which model?
then have a check constraint on that ([0, 3))
PostImage
as well as a unique constraint on (id, image_index)
but I'm sure there should be a better way
that sounds like a pretty hacky way tbh
you could have a constraint on a materialised view
@versed python hey ignis,thanks a lot its works but its throwing this and i already specified a template :
which I believe is the more idiomatic method
๐
but then you have to know how to create a materialised view
you could have a constraint on a materialised view
@vestal hound im using drf, so views are not in picture
uh
no
a materialised view is basically a precomputed result of a SQL query
in this case, a groupby count
so you're saying I should establish a database level constraint instead of a django level one?
wait
wasn't that what you were talking about?
doing this in Django is relatively easy
but in general restrictions should be placed as deep as possible
I just want to associate PostImage with Post, don't really care which method accomplishes it
otherwise it's quite simple
just override the .save method to check if there are already 3 images related to post
and raise error
hmmm, that sounds like a good way
Python-level checks are always easier than database-level checks
hmmm, that sounds like a good way
@versed python note that
you can use bulk_update or bulk_create to bypass that check
so you need to override those too
alternatively, you could have a periodically running task that performs an integrity check
it depends on how much effort you want to put in, I guess
which is why a database-level check is always the best
I don't really plan on giving my users access to my python logic so this won't be an issue
you can use
bulk_updateorbulk_createto bypass that check
@vestal hound