#web-development
2 messages · Page 105 of 1
just put that in your <script> element and after 3 seconds you will see a cool thing
peeps
What exactly does {% load static %} do?
@vivid spear peeeeps
What exactly does
{% load static %}do?
@limber laurel it just loads your static folder... then you could just type {%static' urlinsidestaticfolder'%} as the url to get the files in it.
Thanks
And if I for example had a media direcotry I could techinaclly load media the same way right?
like if there is an images folder inside the static folder... then you just type {%static 'images/name.format'%}.
And if I for example had a media direcotry I could techinaclly load media the same way right?
@limber laurel you can't load it... just have it in static folder.
ok
@limber laurel you can't load it... just have it in static folder.
@nova nacelle and follow the {%static' '%} thing.
Any react devs here?
how can I convert csv to excel and send it download without saving locally
for example I have a excel file I upload it and convert it into dataframe and in the same view I change some data in the dataframe now I want that data frame to convert into excel and download it to user
response=HttpResponse(data.to_excel("a.xlsx"),content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename=%s_Report.xlsx' % excel_file.name
in this case it get saved locally with name of a.xlsx
I AM using django
I wanna do if the user account exists in the database the it will redirect to my homepage
even if i type the correct datas in the login and click on submit i am getting the msg
anyone know what i am doing wrong?
https://repl.it/@Yoshiinori/PaltrySteelAdaware#main.py
rturning a 404 error
hey guys i have a bit problem i want connect it to styl.css file that link rel but idk why it just doesnt react anyway. i tired a lot of ways but any of them worked can anyon ehelp please?
@vivid canopy try removing the first slash in your href
i did it also with it but didnt work i can try it agian
nothing changed
this is maybe some error report from cmd "127.0.0.1 - - [25/Oct/2020 12:24:02] "[33mGET /demoapp/visualize/styl.css HTTP/1.1[0m" 404 -"
hey guys, when should i use breakpoints for responsiveness?
my homepage loooks fine at 500px now and i wondered when to set the media-queries
@vivid canopy Have you tried something like <link rel="stylesheet" href="{{ url_for('visualize', filename='styl.css') }}" /> (you will need from flask import url_for)?
added: i can use them whenever i want i know, but when is it best to use, are there some standards?
@raw vortex didnt try it but now i m reding something like in templates shouldnt be home or about page. bur thanks i will try it
it didnt worked
Can I see what you tried to do?
me?
Yes
okey so in about and home.hmtl is just h1 wich says this is home / about page
in styl. css is just body {background color grey}
this is index.html which can't connect rel to css idk why
and if u want see this is main.py
and this is what i get
just that prob it dont want to connect with css
i already tried evrything
What I would suggest is to have a different folder for your non-template files. For example, you can have:
demoapp ├── templates │ ├── index.html └──── assets └── css └── styl.css
i can try it but
Then, you can change your linktag to <link rel="stylesheet" href="{{ url_for('assets', filename='css/styl.css') }}" />
I am a team lead in Dubai and looking to work with a remote engineer who has at least junior level of technology. 👋👋👋👋👋 🇦🇪
It will be part time work at first.
- Basic understanding of technical - at least junior developer
- Experience working remote.
- Open-minded and think out of box.
- Always kind & cooperative.
DM me for more details
@raw vortex didnt work gonna try another things but ty for your time
b'1::F::1::10::48067\n',
b'2::M::56::16::70072\n', here i wanna omit b and \n in each line
b'1::F::1::10::48067\n',
b'2::M::56::16::70072\n', here i wanna omit b and \n in each line
@native tide what do you mean "omit b"?
so you want to replace '\n' with nothing?
@native tide #bot-commands message
#bot-commands message
@vivid canopy You need to use {% load static %} then provide the src as "{% static path %}"
Oh you're using flask
It's something similar to that it's on stackoverflow somewhere
i fell like i will rip my hair out
i made new env from the start
and this is what i get jinja2.exceptions.TemplateNotFound: templates/home.html
if i have just return render_template('about.html') site writes me back jinja2.exceptions.TemplateNotFound: inedx.html
Show the code
is it in a top level folder called templates
yes
so in home and about html is again just h1 this is home/about page
index.html
Have you tried making your styleshert href = url_for(filename in templatefolder)
didnt but i have other prob it dont even open site
does it load any other templates?
this is the site
okay
/about /home any of them doesnt work
like rerun?
restart it
as in -> turn it off -> turn it on again
i did same
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
put it in there^
in home ist just extands index.html and it says h1 this is home page
what i have to do?
don't you see your error?
in vs?
in vs any errors
What is the error?
From that message
jinja2.exceptions.TemplateNotFound : inedx.html
What does that mean? In your code you tried to load a template caleld inedx.html but there is no such template.
Now find where you typed that.
And change it to what it should be
propably i know what u mean
do you understand what the error is telling you?
yes but i didnt call file template if i understand it right render_template calls file templates automaticly like u dont need to connect it with code like if u understand me
now i absolutly dont understand i m mixed
@vivid canopy Can you explain what extends does?
how can I simultaneously return response and render html by same view?
for example I want to acheive this
wb.save(response)
return response,render(request,'location/index.html',{'columns':data.columns.values.tolist(),'rows':data.to_dict('records')})
propably it takes from index.html form taht block to that site where is extends
. not ,
response.render() renders a template?
thanks guys but maybe in few mins i will have a nother prob with that link rel
sry D
@vivid canopy extends "template" adds your {% block content }% to that template. It's Flask template inheritance.
Read about it here to understand:
https://flask.palletsprojects.com/en/1.1.x/patterns/templateinheritance/
You tried to extend to a template which doesn't exist. "inedx.html" is not "index.html" so it's a typo. You could've changed the filename and it would've worked.
cool elegant and it looks easy to orientation @quick cargo
@quick cargo It's nice. Maybe have the black div extend lower?
i sorta wanna keep how low the black goes the same rn because the lower half will look better with the lighter
Also just my opinion but the top right discord button looks a bit out of place
The text of the button doesn't really line up with the text of the navbar
but that's just nitpicking
probably a dodgy margin
hi! anyone here good with jquery?
okey guys sry for hussle u but i have 2 more probs one is with that link rel
and second problem is with this ul and li it doesnt show propably its not called but idk rly
@native tide can you not spurt random nonsense in every channel
So I have about 25 items that I need to rotate through on my main page, but I am only displaying 3 at a time. To do this is it through Django or JS
Why is there like 50 chemical names
Those are the help channels @native tide and wrong channel to discuss that in
@vivid canopy also use endblock not endblock main
anybody ever managed to add a custom page in django admin panel?
Hmm, so to create a slider to obtain my items from the DB through Django and display them using VueJS
<link rel="stylesheet" href="{% static css/style.css %}">
Could not parse the remainder: '/style.css' from 'css/style.css'
I get this error
What is causing it?
Even if I add ``
Try {% load static %} above it
I already have load static in the file
<!DOCTYPE html>
{% load static %}
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="{% static `css/style.css` %}">
<title>{{ video.title }}</title>
In your settings.py you might need to set your static directory
If I remember correctly
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
This is from my settings.py
seems like I should have everything for it to work
at least in development
@limber laurel which django version do you use?
Opinions on this site design so far?
@quick cargo How do you make that wave like seperation ? is is an svg? i have seen that kinda design, but never looked into how to do it
@limber laurel so can you show us your directory layout
@near bison svg ye
How can I get the tree in the terminal?
what part is the svg?
@limber laurel which django version do you use?
like .. Is the gradient also in the svg?
@limber laurel try this py STATICFILES_DIRS = [ BASE_DIR/'static', ]
TypeError: unsupported operand type(s) for /: 'str' and 'str'```
I think what you are trying to say does the same as join
@limber laurel in the new version of django we can do directly this
this is a shortcut because django uses pathlib
Well if I use the snippet I get an error
@stable kite
and in the static directory I have css directory
and then I have a style.css file
Wierd
It just started randomly working
But for some reason when I make changes in my css I dont see the new changes
But for some reason when I make changes in my css I dont see the new changes
@limber laurel It happend like that? No errors?
That was some glitch now it works
No error
Now it seems to be working
really wierd
If it ever happens again just go into inspect mode, network, right click ur style.css and click clear browser cache and cookies. Refresh the page and shoudl be working fine
Ok
Hi!
Sqlalchemy page shows that I can work with sessions like that:
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
# an Engine, which the Session will use for connection
# resources
some_engine = create_engine('postgresql://scott:tiger@localhost/')
# create a configured "Session" class
Session = sessionmaker(bind=some_engine)
# create a Session
session = Session()
# work with sess
myobject = MyObject('foo', 'bar')
session.add(myobject)
session.commit()
However, whenever I do session = Session() in my Flask app, the whole thing hangs.
For more context - I'm doing the engine and sessionmaker instance (Session) in my init file, and importing this Session into another file where I do session=Session().
I have been googling around and can't figure out what I'm doing wrong.
@limber laurel oh.. so your CSS page wasnt loading in the browser? Just CTRL F5 each time you make updates as that'll clear browser cache to load the css as its saved in cache.
@limber laurel have you added this in your urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)```
Hi Guys, need some help with deplying an django app on heroku
Can anyone help?
Getting this error
git push heroku main
Enumerating objects: 1011, done.
Counting objects: 100% (1011/1011), done.
Delta compression using up to 4 threads
Compressing objects: 100% (402/402), done.
Writing objects: 100% (1011/1011), 4.12 MiB | 120.00 KiB/s, done.
Total 1011 (delta 578), reused 1007 (delta 576)
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz
remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure
remote:
remote: ! Push failed
remote: Verifying deploy...
remote:
remote: ! Push rejected to duspy.
remote:
To https://git.heroku.com/xyz.git
! [remote rejected] main -> main (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/xyz.git'
Anyone willing to make a quiz application? Has to be in Django, and I'm paying for it, though not much.
Ping or DM me if you are interested.
Sending on DM.
ok
How can i get a list of servers user is in and check if user is administrator with flask-discord?
Ping if answering
2 votes and 6 comments so far on Reddit
Answer is you can't @jolly pilot
And pretty obvious
Because it's on a lot of servers and it just checks mutuals
Wdym
I just wanna display the server list on the website
And see if the user has manage_guild perms
@rapid bramble
Anyone willing to make a quiz application? Has to be in Django, and I'm paying for it, though not much.
@rapid bramble Can you elaborate?
Sending a DM
Okay.
@jolly pilot Oh, you mean display his own list, that's doable via Oauth2 callback
Yes
But how
fetch_guilds gives me an empty list
getting the username and profile picture works fine but getting guilds just does not work
pretty simple question, im running a quick and dirty Quart server to test the payload of another application, however i cant seem to print anything out to the console: ```py
from quart import Quart, websocket, request
app = Quart(name)
@app.route('/death')
async def hello():
print("test")
return 'hello'
app.run()
i can see something was posted but i cant get anything to print, be it the request, the payload, or anything else such as just 'test'
[2020-10-25 10:11:48,767] 127.0.0.1:60752 POST /death 1.1 405 137 997```
I guess because it returns 'hello'?
?
wait.
it should print before it returns anything
the second code box i sent is the entire console output, i need the request payload to print to the output but nothing is printing
okay i see it now... I'm really working so just paid half attention to that.
I am looking to send request from one user to another in django can some tell me how can I do that!!?
guys want to ask how can fix problem with reloading site for explain lets say i have in main.py port set to 1717 and lets say sites background in css is set to grey color so next i change grey to green and let port stay to be 1717 reload site and sites background is still grey but if i change port lets say to 1716 and load site again with port 1716 , sites background is green. So dont u have anybody experience with this how to fix it?
should be problem with this link? <link rel="stylesheet" type='text/css' href="{{ url_for('static' , filename='style.css') }}">
yeah
@minor pumice ForeignKeys?
flask
Sorry I know 0 flask xD
foreignkeys?
ForeignKeys can be used to connect users / models which can be accessed
@vivid canopy talking to Rahul
aha sry
I am using django notification along with it
I am looking send accept and decline option from one user to another
@toxic flame dont u know how is this problem called in django propably its similiar problem so i can better search for some solutions?
Anybody here had any success making a custom page in django admin board?
@vivid canopy in django you just add a STATIC_URL on settings and then on the template:
{% load static %}
{% static 'css/stlye.css' %} to load the css
yea sometimes css doesn't load in real time for me
bc it's saved in cache which needs to be reset for you to see updated code
@native tide whaaat it works thanks a lot
hey guys, anyone works with FastAPI ? I have a question about the structure of a project, i would like to implement OAuth2 following this tutorial https://fastapi.tiangolo.com/tutorial/security/oauth2-jwt/ but i don't know where should i put my code for it, so for now i placed the source code at auth.py in the main folder but i don't know
FastAPI framework, high performance, easy to learn, fast to code, ready for production
I'm sending a request to my API and all my fields are empty. But, my serializer is only returning an error this field may not be blank for 2 out of 3 of my fields...
class UserSerializer(ModelSerializer): # In DRF serializer validation is done serializer-side
class Meta:
model = Users
fields = ["username", "email", "password"]
username = CharField(max_length=20, allow_null=False, required=True,
validators=[UniqueValidator(queryset=Users.objects.all(),
message="Username is taken, try something else"),
MinLengthValidator(4, message="Username is too short (<4 characters)")])
email = EmailField(allow_null=False, required=True, validators=[UniqueValidator(queryset=Users.objects.all(),
message="An account with that email already exists")])
password = CharField(allow_null=False, required=True, max_length=100)```
The password field isn't getting the validation. But the only difference is that it doesn't have the UniqueValidator validator... how strange
Anyone know how I can fix this?
I made a fix. In my serializer if any of my fields are empty it returns a dict with key error so in my JS I checked if the response object contains and error key and it will render one message saying that the form is incomplete, rather than a seperate error message for every field.
So yeah that's pretty much done. Now I need to do session auth and I don't understand it 😄
Hello all, i am using django, let me know which module is better for image gallery. here is HTML screenshot. 
farmer propoganda
Is it possible in python/django to verify that a file extension matches its type?
I know in linux the file command does this but I want to avoid executing this command via subprocess if I can do it in python natively
Is it possible in python/django to verify that a file extension matches its type?
@trim star what do you mean "matches"?
like whether a file with a particular extension is actually what it advertises?
ah
I'm not sure if there's a library for that
there probably is
but if not, it's not a very hard problem, but it is a wide one
because the difficulty of verifying if a file is the type it's supposed to be varies, right?
e.g. how do you tell if a Python file is a valid one? you have to compile it.
but I guess you only want to do this for a specific set of extensions, right?
@vestal hound yes
@vestal hound yes
@trim star namely?
okay
if you can't find a prebuilt solution
I'm sure each of these has some kind of header
you can open the file and check for that
@vestal hound yes. I think security wise if I cannot find a well supported solution, then doing that myself in native python is better than calling subprocess and more platform independent
Hi guys, how can I pass a value to javascript in a jinja template from flask?
is there a way I can edit the error pages (404, 403, etc) on my apache web server?
@native tide from your flask view, you can pass context variable to template, and in the template you can use {{ variable }} anywhere for example:
<script>
var a = "{{ variable }}";
</script>
django, does anyone have experience with no reverse match error? Apparently its due to an html url call
Can anyone help me with fetching data from django models and applying it into my templates. I am a vey beginner of django?
@plucky tapir the error will show up if django can't find the url you specified, are you using url's name in your code to specify or the url path itself? it's better to use url's name as it work like variables
@zealous tusk show your model
@zealous tusk yes there a tutorial for what you asking. I think you just missed that part in the tutorial document https://docs.djangoproject.com/en/3.1/intro/tutorial03/#write-views-that-actually-do-something
okay wait
@native tide from your flask view, you can pass context variable to template, and in the template you can use
{{ variable }}anywhere for example:<script> var a = "{{ variable }}"; </script>
@gaunt marlin aight thnx
@gaunt marlin path('<int:pk>/update/', views.updateRegister, name='update'),
It has to be something with my primary key?
<td><a class="btn btn-sm btn-info" href="{% url 'update' Userinfo.id %}">Update</a></td>
@plucky tapir can you show the full error?
is Userinfo a context variable you passed to the template?
@gaunt marlin https://dpaste.org/DhTH Userinfo is my model's name
@plucky tapir here is the problem
with arguments '('',)' not found
your Userinfo.id return a tuple with a blank string element inside of it
check why it return that instead of an integer
would Userinfo.id be the way to pass the pk? @gaunt marlin
@plucky tapir you pass your model query as variables to the template right?
have you tried to see {{ Userinfo.fname }} show up in your template?
yourview(request):
...
query = YouModelName.query_stuffs
return render('template_path.html', {
'a_variable': query
})
this is an example
so i can use {{ a_variable.model_attribute ]} on template to render
Userreg = Userinfo.objects.all()
context = {'users': Userinfo}
return render(request, 'users/dashboard.html', context) ```
@gaunt marlin objects.all() passes it correct?
yes
@plucky tapir wait that is wrong
you set variable of your query as Userreg
and you settings {'users': Userinfo} which is wrong
it supposed to be {'users': Userreg}
and in your template @plucky tapir
{% for user in users %}
{{ user.id }}
{% endfor %}
you should pass variable instead of model name
@gaunt marlin would I need to add anything in the url 'update' button?
@plucky tapir not yet, first you need to fix your view code like i mentioned above
you passing the wrong thing to your context variable
that why it returned empty tuple
here the fix
your view:
def home(request):
Userreg = Userinfo.objects.all()
context = {'users': Userreg}
return render(request, 'users/dashboard.html', context)
your template(just an example, apply to your template logic):
{% for user in users %}
{{ user.id }}
{% endfor %}
you users = Userinfo.objects.all() when you set from template
@gaunt marlin {% block content %}<h5> Hello {{user.username}} {{ user.id }}</h5>
I can see the username and user id although I have a model called Userinfo that I cannot really display any information from
@plucky tapir user is an instance of your Userinfo model, you can display any of the Userinfo attributes like normal. What is your goal ? I cannot really display any information from which information you looking for?
For now it was first name last name and city from Userinfo, I also have a User model for Users to login with a password, but focusing on Userinfo at the moment, I had a button there for Update but I wasnt passing a pk properly so I removed it
@plucky tapir now you will be passing like this with different parameter variable
<td><a class="btn btn-sm btn-info" href="{% url 'update' user.id %}">Update</a></td>
remember pk in django is also any field that has primary_key=True
django, does anyone have experience with no reverse match error? Apparently its due to an html url call
@plucky tapir can you share the ss of the error?
For now it was first name last name and city from Userinfo, I also have a User model for Users to login with a password, but focusing on Userinfo at the moment, I had a button there for Update but I wasnt passing a pk properly so I removed it
@plucky tapir is your query solved?
@nova nacelle https://dpaste.org/msDU
@plucky tapir Can you share your model and view?
@nova nacelle https://dpaste.org/LDgH model
view will be pretty messy, got stuck, started using both class based and function based
view will be pretty messy, got stuck, started using both class based and function based
@plucky tapir Share that too.
https://dpaste.org/Qy9O views
I had cbv working at one point but messed it
@plucky tapir pn=models.CharField(validators=[RegexValidator("^0?[5-9]{1}\d{9}$")],max_length=15, null=True, blank=True). use this for the phone number. NOT RELATED TO YOUR QUE ANYWAYS
@nova nacelle i found out his problem earlier this is his view:
def home(request):
Userreg = Userinfo.objects.all()
context = {'users': Userinfo}
return render(request, 'users/dashboard.html', context)
he was passing the wrong context variable to the template
if you scroll up you can see my messages
@gaunt marlin That is why i first asked- if his query is already solved.
he set users variable to Userinfo which is the model by mistake
it suppsoed to be {'users': Userreg}
pn=models.CharField(validators=[RegexValidator("^0?[5-9]{1}\d{9}$")],max_length=15, null=True, blank=True). use this for the phone number.
@gaunt marlin what do you think about this?
i'm no expert in regex but that is not his error which he just posted
Exception Value: Reverse for 'update' with arguments '('',)
he was using this <td><a class="btn btn-sm btn-info" href="{% url 'update' Userinfo.id %}">Update</a></td> so you can see the problem
Userinfo
@gaunt marlin Yeah, I just saw that he tried to import a phone field and later commented it and user a simple charfield... So, i just suggested using the regex.
xy-problem
Asking about your attempted solution rather than your actual problem.
Often programmers will get distracted with a potential solution they've come up with, and will try asking for help getting it to work. However, it's possible this solution either wouldn't work as they expect, or there's a much better solution instead.
For more information and examples: http://xyproblem.info/
What do y'all suggest, going back to cbv? Atm I'm wanting to create, details, update, delete input
@plucky tapir your current problem is this error right ?
Exception Type: NoReverseMatch at /users/dash/ Exception Value: Reverse for 'update' with arguments '('',)' not found
@gaunt marlin Yeah
@plucky tapir now you will be passing like this with different parameter variable
<td><a class="btn btn-sm btn-info" href="{% url 'update' user.id %}">Update</a></td>
@plucky tapir have you tried my solution ?
@gaunt marlin Alright so now its pulling up my user id, when I believe I need to pull up the primary key that is from the "Create" that I just made
From here #web-development message create goes to a form to input info, then it takes me back to the 'dashboard'
@plucky tapir can you describe the flow more clearly? i'm having trouble understanding this I need to pull up the primary key that is from the "Create" that I just made
so you have dashboard page that list all the user info with a create button and an update button for each user. The create button will redirect to a create form, the update button redirect to the update form
is that what you trying to tell me ?
when you create an object from create form, you need to redirect to the dashboard page -> which will query the userInfo table again and list all the userInfo old and new
so the dashboard will list all users id order in ascended order
Unsure if this is the best place to ask. Currently researching to build a price aggregator for specific products would python be the best option for scraping ecommerce prices and feeding into a database? Any suggestions on front end frameworks would be appreciated.
@native tide for python there are dedicated package for scraping like scrapy and other. For javascript i can only think of https://github.com/puppeteer/puppeteer , but use what you more comfortable and needed
for frontend you might encounter javascript generated contents, for those you can use headless browser
@gaunt marlin have used scrapy in the past I haven't touched a scraper in a few years so just making sure it's still my best option needs to be highly scalable. Doing the leg work before I search for a developer.
there alot of tools, but i generally just use python requests and xml to get web content 😄
@gaunt marlin u can be highly naughty at an exceptional speed with requests 😄
as long as i'm not breaking the web site scraping rules and have not too much requests per interval
@gaunt marlin what do you think about single board computers hosting the scrapers and pushing results to web server vs having web server based scrapers??
@native tide i think it's based on your design, of course having a web scraper running in the background is much cheaper than using single board computers. I don't think web scraping would take that much resource if you have the correct flow
i'm no dev ops so i have little or no knowledge about VPS or AWS
@gaunt marlin I have around 50 odroids n2 sitting in a box and thought I could use them for this project.
i think you can use those if you want, but you have to be the one maintaining the hardware. I generally run scraper on the server then i only need to maintain the software not the hardware itself
imagine this: your android die - > server web still alive get no data
vs
the scraper only die when your server hosting the website
hey guys wanna ask when i have this bar finished how do i make that if i click on it it send me to that site. dont want to know how to do it to details but want to know if i have add there buttn?
@vivid canopy you can use a tag with href attribute for it
<a href='https://www.google.com'>click to go to google</a>
ty
anyone working django w/ react?
how can i make width of that right text width to 35%?
just do it in css?
Yeah
idk what comand to use
anyone working django w/ react?
@native tide yes
google it
googling it for 45 min D
when i use this text goes from left
so you need to re-position your text...
which is another css tag
@stable kite Have you implemented any auth yet, session/token auth to be specific?
@native tide yes
i made tag for left and right text but when i used width text anyways goes from left
you can use float: right or float:left in your div css
and just center the text.
@nova nacelle thanks
@stable kite which auth method?
@vivid canopy Your welcome.
@native tide the inbuilt one
@stable kite I mean... session, token? Which one?
@native tide session
within the API endpoints?
@native tide no with ajax
could you upload your code for that?
Hey guys! some Django expert here? I just asked this in stackoverflow, could you help me with it? I know i'm missing something stupid but It's driving me crazy! https://stackoverflow.com/questions/64535154/django-not-showing-a-model-in-admin-page
I have created a new model for my app Consumptions but it doesn't show up.
I know that I have to put it on the admin.py page but still not working.
I don't know what could be happening
This is my m...
could you upload your code for that?
@native tide for that you should have both frontend & backend on the same sever
@primal kernel Have you done makemigrations?
Yeah I did it
and then migrate?
Ofc
And I can see the results in my DB, my only problem is that I can not see it in my admin page
@stable kite not really, but if you can upload your code I'll understand what you're talking about. How can you be doing session auth if it's not in the API endpoints 😄
i am using POST ajax Request for that
Yea. So you're making a request to your API which handles the session auth?
@native tide ```py
#views.py
def signin(request):
if request.method=='GET':
return render(request,'index.html')
elif request.method =='POST':
try:
username=request.POST['username']
password=request.POST['password']
try:
validators.validate_email(username)
print('hi')
username=CustomUser.objects.get(email=username).username
return function.signin(request,username,password)
except:
return function.signin(request,username,password)
except:
return JsonResponse({'status':'Failed','error':'Unable to get user data'})
else:
pass
def signup(request):
if request.method=='GET':
return render(request,'index.html')
elif request.is_ajax() and request.method =='POST':
try:
username=request.POST['username']
password=request.POST['password']
firstname=request.POST['firstname']
lastname=request.POST['lastname']
email=request.POST['email']
re_password=request.POST['re_password']
try:
validators.validate_email(email)
return function.signup(request,firstname,lastname,username,email,password,re_password)
except:
return JsonResponse({'status':'Failed','error':'Please enter a vaild email address'})
except:
return JsonResponse({'status':'Failed','error':'Unable to get user data'})
else:
pass
@native tide ```py
#functions.py
def signin(request,username,password):
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
return JsonResponse({'status':'Success','error':None,'uuid':user.uuid.hex},status=200)
return JsonResponse({'status':'Failed','error':'Please Enter the correct Username & Password'})
def signup(request,f_name,l_name,username,email,password,re_pass):
if password == re_pass:
try:
CustomUser.objects.create_user(username=username,email=email,password=password,firstName=f_name,lastName=l_name)
return JsonResponse({'status':'Success','error':None,},status=200)
except :
return JsonResponse({'status':'Failed','error':'Username already exists,Please try with other username',})
else:
return JsonResponse({'status':'Success','error':'Password dose'nt match,Please try again',})
Thank you 🙂
@native tide if you want API auth here is the reference
https://www.django-rest-framework.org/api-guide/authentication/
Django, API, REST, Authentication
hey i used namecheap and hosted my google site
it works when i added www at the beginning but it does not works ( error 404 ) when i just typed sitename.me any help ?
you need to either add a DNS entry, or setup a redirect
Do you know if i can request a website with a specific local storage variable ?
Like have a different result depending of this value
for web scrapping
Or more easy, simulate a click on a button 
{% for product in featured_products %}
<h4>{{product.product_name}}</h4>
{% endfor %}
Why I cant see this is my template .
But when I do this with python I get the required output.
def index(request):
featured_products = Product.objects.order_by('product_name')[:4]
# This gives me the correct output
for product in featured_products:
print(product.product_name)
print(featured_products)
context = {'featured_product': featured_products}
return render(request, "shop/index.html", context)
class Product(models.Model):
"""
This class defines the information related to a product.
"""
product_id = models.AutoField
product_name = models.CharField(max_length=50)
product_category = models.CharField(max_length=50, default="")
product_subcategory = models.CharField(max_length=50, default="")
product_price = models.IntegerField(default=0)
product_desc = models.CharField(max_length=700)
publish_date = models.DateField()
product_img = models.ImageField(upload_to="img/home/", default="")
product_rating = models.PositiveIntegerField(default=10, validators=[MinValueValidator(1), MaxValueValidator(5)])
def __str__(self):
return self.product_name
This is my model.
Ping me once, if you can help.
Should I go with Django or Flask?
any advantages?
honestly it doesn't matter what u choose
which is easier for begginers?
probably flask ig
ig means I guess?
context = {'featured_product': featured_products}
shouldn't it be 'featured_products' for the key
well thx for your suggestion
@zealous tusk
Can you link me to some of django resources?
lemme do it
def index(request):
featured_products = Product.objects.order_by('product_name')[:4]
for product in featured_products:
print(product.product_name)
print(featured_products)
context = {'featured_products': featured_products}
return render(request, "shop/index.html", context)
is this what you asked me to do right?
But when I do this with python I get the required output.
@zealous tusk wdym?
a
means when i itrate that featured_prod list i can see the names of products.
but i cant get it into template
yeah i solved the problem.. thanks guys
How to slice items in django ?
yes that was right
did it solve the issue?
if you do {% for product in featured_products %} the context key is "featured_products" but you had "featured_product" which isn't the same
and what do you mean by slice
Good Morning, does anyone here have some advice on how I should be handling caching and sessions in production for a Django web app?
@zealous tusk do model.objects.get(e.g. username="user").pk
and .pk gives you the primary key
so then you can find that element
okay thanks man!
Has anyone here set up celery for Django before?
Has anyone here implemented sign in with apple? I was wondering if someone had some good reads or code somewhere they are willing to share. I am trying to implement sign in with apple on my fastAPI backend.
Log in with Apple ID you mean?
Yes
Has anyone here set up celery for Django before?
@devout coral why
I am trying to set it up and running into issues
Well the issue is the task just stays pending forever.
do you have a worker running?
I have redis inside of a docker and it connects to it just fine but it never executes
sounds like you don't...? that's my initial guess
Alright, worker is what exactly? Redis is the broker right?
yes
no
well
okay, let's just say yes
anyway
so there'll be one process that basically keeps track of tasks
and assigns them
to workers.
so it sounds like you only have the Celery server running
but not workers
so it has nothing to dispatch the work to
Well, I have celery running. And I have redis in a docker running as well. I thought celery received the task from django when I use the .delay() then it gets sent from celery to redis to be executed...
Is that not how it works. This is what I understood from the docs.
yup, basically
okay, never mind what I just said
do you have the logs
from your running process?
Well, I could not find where to get the logs...
Yes
yeah, that window should have logs
I did the info for the log to show on the terminal but I could not find a txt or anything with logs if that is what you mean
Oh yeah, I can re run it one sec
Forgot to run my docker... One more sec
-------------- celery@d012-itmgrlb2 v5.0.1 (singularity)
--- ***** -----
-- ******* ---- Windows-10-10.0.17763-SP0 2020-10-26 11:43:49
- *** --- * ---
- ** ---------- [config]
- ** ---------- .> app: DivisionManagementSystem:0x54735c8
- ** ---------- .> transport: redis://127.0.0.1:6379/0
- ** ---------- .> results: redis://127.0.0.1:6379/0
- *** --- * --- .> concurrency: 8 (prefork)
-- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker)
--- ***** -----
-------------- [queues]
.> celery exchange=celery(direct) key=celery
[tasks]
. DivisionManagementSystem.celery.debug_task
. main.tasks.add
. main.tasks.send_email
[2020-10-26 11:44:37,519: INFO/MainProcess] Connected to redis://127.0.0.1:6379/0
[2020-10-26 11:44:37,538: INFO/MainProcess] mingle: searching for neighbors
[2020-10-26 11:44:38,612: INFO/MainProcess] mingle: all alone
[2020-10-26 11:44:38,663: WARNING/MainProcess] c:\users\edwin.cruz\desktop\divisionmanagementsystem\venv\lib\site-packages\celery\fixups\django.py:203: UserWarning: Using settings.DEBUG leads to a memory
leak, never use this setting in production environments!
warnings.warn('''Using settings.DEBUG leads to a memory
[2020-10-26 11:44:38,663: INFO/MainProcess] celery@d012-itmgrlb2 ready.
@vestal hound
[2020-10-26 11:44:38,663: INFO/MainProcess] celery@d012-itmgrlb2 ready.
[2020-10-26 11:45:57,550: INFO/MainProcess] Received task: main.tasks.add[cdc7e954-d5c5-4b8a-8ef2-343f6e16acc2]
[2020-10-26 11:45:59,584: INFO/SpawnPoolWorker-9] child process 10356 calling self.run()
Then when I run a task it does that and it is still pending 3 minutes later.
How can I create a decorator that gets triggered from a websocket event which then calls the method it's wrapping
Could I load my nav bar from static?
@limber laurel wdym?
Hi, i am trying to use django test client to log in, like this: https://dpaste.org/NLJB My view looks like this: https://dpaste.org/yFiS I know the view works because i can log in via both browser and POSTMAN. For some reason i get Forbidden: /api/v1/users/auth/ when i try with django test client. What am I doing wrong here?
@devout coral like have my navbar.html file in a static folder
guys, any advice for someone who just started learning django?
@limber laurel No that should be a template really, I would put it wherever you are putting you base html stuff
@sterile peak Read the docs, then follow a tutorial. Then once you can understand everything in the tutorial build something.
@sterile peak Read the docs, then follow a tutorial. Then once you can understand everything in the tutorial build something.
@devout coral alright, you mean the official django documentation right?
Can anyone suggest me a good tutorial on django?
video
@devout coral also i haven't worked on front end technologies before so for coding django templates are the basics enough or do i have dig deeper
do i have to*
@sterile peak Well you would want to learn the Django Templating Language which is very similar to jinja2
@clear arch There is probably the best one out there.
@devout coral thx
@sterile peak Well you would want to learn the Django Templating Language which is very similar to jinja2
@devout coral jinja2? oh man haven't learnt it either.. looks like i have long way ahead of me
and are you currently working on any django proejcts?
Also the templating language is super easy
@sterile peak Me yes
@devout coral what are various frameworks/technologies that come in handy while working on your projects in django?
i am looking to shift my job so i am trying to gauge some essential skills
Well the good thing about Django is that it is a "Batteries Included" so you only really need django to get a site running.
oh that's great to know.. so react or any other fancy JS framework is required?
oh that's great.. but how do we make good UI?
Also if you want to make your front end life a lot easier use bootstrap
i mean clean UI that is pleasnt to look at
Bootstrap is probably your go to at the beggining.
i have some experience with it, i worked with bootstrap and jquery couple of years ago
bootstrap 4 is great
So if you have some experience with it I would say use it.
great man, thanks! since how long you've been coding using django ?
At the beginning bootstrap sucks because you are not sure everything it has and the grid system confuses some but once you have some experience you can make the most of it.
@sterile peak A little over a year now
When I started using Bootstrap it took me like half an hour to figure where everything was xD
Had my first client(that needed web dev) last August which was also my django project
At the beginning bootstrap sucks because you are not sure everything it has and the grid system confuses some but once you have some experience you can make the most of it.
@devout coral totally true! i generally dont enjoy working with JS or any of the UI technologies but i am keen to chage that
@clear arch Nice, it took me about an entire project lmao
Had my first client(that needed web dev) last August which was also my django project
@devout coral Congrats on that! are you freelancing?
@devout coral can you please explain why we use templates?
static ---> dynamic is that it or something else?
@sterile peak I was I no longer do it. Got annoying after a bit.
@clear arch The reason we use templates is to make life easier and no need to re write a bunch of stuff. Also helps a lot with dynamic content.
okay, let me get my hands dirty with django
Templating allows you to have a base file(base.html) which will contain things that every page will share (header, nav bar, footer, etc.) and then in your body you can place a "block". Later when you are ready to make a page you can "extend" from that base file and replace that "block" with the code in the current html file.
Other things it allows you to do is add loops and logic right in your html. So for example if you want to display multiple users in one html page but do not know the quantity or who it is. You can simply pass a query set to your template then use a for loop right in your html to make the necessary tag(s) for each of the users.
Other things it allows you to do is add loops and logic right in your html. So for example if you want to display multiple users in one html page but do not know the quantity or who it is. You can simply pass a query set to your template then use a for loop right in your html to make the necessary tag(s) for each of the users.
@devout coral this is one of the best things about django
Yes, it is.
@toxic flame You have any prior experience with celery and django integration?
thx @devout coral
I heard flask is more lightweight
I've been working with django for around 3-4 months now and I can build large scale projects
django is easy to learj and understand
The only way flask is lightweight is that it is smaller in size(because Django includes a lot more out of the box). However, for the same size project doing the same things the performance differences are negligible.
@devout coral quick question: jinja vs dtl
I've been working with django for around 3-4 months now and I can build large scale projects
@toxic flame so what else do you use apart from django??
@toxic flame for backend and front end.. i would lke to know the things that are absolutely necessary to build large scale projects
@clear arch no real big difference from what i know tbh. Just that DTL is already included in Django.
oh
Hi ! i'm trying to scrapping and i've some sort of "selector" which aren't button but we can click on it, how can i trigger this action ?
html, css, sass, js, vuejs, django, these are the default I use for a large scale project
sass? software as a service?
no
ok @devout coral thx
Syntactically Awesome Style Sheets
https://sass-lang.com/
@toxic flame i worked too long on saas and paas so i got confused lol
Syntactically Awesome Style Sheets
okay xD
vuejs? i am new to UI so please bear with me. i hear about react, flutter and angular but not much of vue.. what is your opinion?
imo vue is easier and flexible than react
vue can have scoped / nested css for each element which is very flexible for me
VueJS is good, its open source, I would recommend it if you want to learn it personally, but job wise VueJS isnt as popular as React of Angular atm I have heard. So if you are determined to get a job off the bat then go with something like React or Angular, I personally am going with VueJS then will play with Angular or React later on.
oh alright, so many js frameworks it gets overwhelming very easily
currently i am very focused on getting up to speed with django post that i reckon some js framework would be good thing to learn?
from django.db import models
class Category(models.Model):
category_name = models.CharField(max_length=100)
class Product(models.Model):
product_name = models.CharField(max_length=200)
product_price = models.DecimalField(max_digits=5, decimal_places=2)
```
I am creating a Category model in which new categories can be created such as Clothing, Accesories, Textiles etc. I want my Product model to inherect one of the categories created. How would I go about doing this
I am getting an error when I am typing os.path.join(BASE_DIR, 'templates') the error is name os is not defined?
did you import os
in the settings?
where you have the following code
in the settings.py file
then yes import it there
ok does it matter where I import it?
yes..
nvm got it thx @haughty turtle
@clear arch Not trying to be rude but it does not seem you are too familiar with python. If this is the case I would suggest you learn python basics before diving into django or you will get VERY overwhelmed.
@haughty turtle Did you get your model thing figured out or need some help still?
yea need some help still
Trying to figure out the best way to go forward, I need to have my products specify what categories they are in as I will need to display them per category later on, as also per gender.}
@devout coral I thought os was already imported as I am following a tutorial in that os module was already imported
@haughty turtle Ok, and your category is a whole model correct?
@clear arch Yes it is in there by default.
for mine it was not xD
latest
Ok weird.
@devout coral yeah I imagine this would be the best way in Django, will it not? Allowing me to add new categories later on?
In terms of user friendliness new categories could just be added in the admin panel
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
2) Quit, and let me add a default in models.py
``` I'm trying to add an author to a models, do I just add default=True into its definition?
I learnt css in two days
@haughty turtle wow
Css is very complicated
When I look at css
Its
@haughty turtle Yeah that works. What I would suggest is to make a relationship between categories and product.
CSS is hard to remember isn't it
Yeah
All those rules
Plus u have so many kinds of framework
Scss bootstrap
Grid css
css is very confusing, so many ways to style a element
Flex box
Programming is not about remembering stuff its about learning the fundamentals and being able to research at any given time.
In this video I will cram as much as possible about CSS. We will be looking at styles, selectors, declarations, etc. We will build a CSS cheat sheet that you can keep as a resource and we will also create a basic website layout. We are using CSS3 but mostly the basics. I will ...
Does anyone here use FastAPI?
Programming is not about remembering stuff its about learning the fundamentals and being able to research at any given time.
https://www.youtube.com/watch?v=yfoY53QXEnI
@haughty turtle css is a programming language
In this video I will cram as much as possible about CSS. We will be looking at styles, selectors, declarations, etc. We will build a CSS cheat sheet that you can keep as a resource and we will also create a basic website layout. We are using CSS3 but mostly the basics. I will ...
Not a
Css is not a programming name
Language
Programming is not about remembering stuff its about learning the fundamentals and being able to research at any given time.
https://www.youtube.com/watch?v=yfoY53QXEnI
@haughty turtle while i agree with this but without remembering sometimes it is hard to debug old code. i had to do that a lot on my previous project and all that legacy drove me crazy
@haughty turtle do you know how to establish relationships in django?
@haughty turtle Lol... I do not need to read it I know how to do it. I was saying it for your question.
Plus I have probably read that a few times already..
html and css is probably the easiest
Yeah, thats what I am reading right now, I completed the Django tut, but that was like 4 weeks agos
have been completing the HTML and CSS got that done, now have to refresh what I learnt
If you are starting out with django my suggestion is to always focus on the django part of it instead of front end. Once you have your funcitonality then do the front end.
you need the basic python knowledge too for django
Ah, I did it backwards
@haughty turtle Ok, well for your issue a OneToMany relationship is probably what you are looking for.
you need the basic python knowledge too for django
@toxic flame I cannot stress this enough. Seems like a lot of people just want to jump right into django but that is such a big mistake. You will run into all types of issues.
ForeignKey(Category, on_delete=models.CASCADE) is what u need @haughty turtle
put it on the product models
cateogroy = models.F....
then you can assign a category to a product, which can be filtered by:
Product.objects.filter(category__category_name="nameofyourcategiry")
I'm on my phone hehee
@toxic flame Any experience with celery in django?
You asked me this already, no.
Did not see your answer. Thank you
It's okay
There are alot of ways on making relations but I like this method more
it's easier than the OneToManyFields since you have to drag and drop, and do all sort of things before actually linking them together
Hello everyone ! Does anyone here have experience with Flask/Celery use ? I need help with setting up so if you have done this before, would be grateful for your help
Thanks!
@royal radish I have been trying to get some help with celery for the past three days... No such luck so far.
But if you figure something out and can help me out with my issue let me know.
Celery seems to be a realtime processor for python stuff
Well it it for asynchronous work, and my set up gives no errors which is even more frustrating. Just sits on pending and never finishes the task.
@devout coral Could I create a template folder but for the whole project?
@limber laurel Yes, this is normally where you would put your error templates and admin templates to re write the django back end look.
Ok
However, for the individual app templates you would normally have your templates in there.
Ok\
Just want to note I finally figured out my issue with celery. Apparently it is a weird issue with celery and windows and you need to add the --pool=solo to your worker.
Question, anyone here have a clever way to get a absolute url without the request object?
Hi, I'm getting error with js this time.
at register
at HTMLSpanElement.onclick```
I have
```{% extends 'base.html' %}```
at my account.html(site with problem). I included scripts.html and linked main.js before in base.html. This script is the only one not working:
```/* Toggle Form */
var LoginForm = document.getElementById("LoginForm");
var RegForm = document.getElementById("RegForm");
var Indicator = document.getElementById("Indicator");
function register(){
RegForm.style.transform = "translateX(0px)";
LoginForm.style.transform = "translateX(0px)";
Indicator.style.transform = "translateX(134px)";
}
function login(){
RegForm.style.transform = "translateX(-400px)";
LoginForm.style.transform = "translateX(390px)";
Indicator.style.transform = "translateX(15px)";
}```
Although when I just copy this script into account.html irt magically works. But that's not how it is supposed to work. It should work by including scripts in base.html. When going into Dev mode at site, my scripts are loading, but they aren't working. I've done everything with staticfiles.
@pulsar hinge seems like those two elements do not exist.
But when pasting this script into <script> tag at account.html, it works fine
I'm making a request to my API endpoint to sign users up and I just tried to add session authentication, but I don't know what to do and the DRF docs are confusing.
My error:
{"detail":"Authentication credentials were not provided."}
My view:
@api_view(["POST"]) # API view for POST requests
@permission_classes([IsAuthenticated])
def register(request): # This will register a user from their POST request.
if request.method == "POST":
if "username" and "email" and "password" and "confirm_password" in request.data:
if request.data["confirm_password"] == request.data["password"]: # Checks that password is confirmed.
hashed_password = make_password(str(request.data["password"])) # Hashes password
request.data["password"] = hashed_password
else:
return Response(data={"password": "Passwords do not match"}, status=status.HTTP_400_BAD_REQUEST)
serializer = UserSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(data=serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(data=serializer.errors, status=status.HTTP_400_BAD_REQUEST)
else:
return Response(data={"error": "Model fields not satisfied"}, status=status.HTTP_400_BAD_REQUEST)```
How do I provide auth details?
It just doesn't work while including
@pulsar hinge You are probably referencing before it is loaded in then. Try loading the script at the end.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href=" {% static 'css/style.css' %} ">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<title>RedStore |{% block title %}{% endblock title %}</title>
</head>
<body>
{% include 'navbar.html' %}
{% block content %}
{% endblock content %}
{% include 'scripts.html' %}
</body>
</html>``` Replacing include scripts after body or html doesn't make a diffrence
That's weird cause other scripts are working just fine. There is only one error, but at pages that don'trequire this script.
@devout coral sorry for ping, just want to make sure u see it
is flaskforms appropriate for building a dashboard which can pull data from a mysql db, and export in xls format?
ive only used flaskforms for logins and data upload pages.
print your query
lookup how to mogrify and print the content of your sql query
object of type none has no len
type none
check to see if your script is even querying properly
that is my guess
someone more experienced maybe
ive only done auth 1 time
i used this way though
#login page and location logic
@app.route("/login", methods=["GET", "POST"])
def login():
connection = db_connection()
error = None
if request.method == "POST":
email = request.form.get('email')
# print(email)
password = request.form.get('password')
# print(password)
with connection.cursor() as cursor:
sql = "SELECT email, password_hash FROM users WHERE email=%s"
cursor.execute(sql, (email,))
result = cursor.fetchone()
connection.close()
# print(type(result['password_hash']))
# print(result['password_hash'])
if result is None:
flash("That email doesn't exist")
return render_template("login.xhtml", error=error)
else:
if bcrypt.check_password_hash(result['password_hash'], password.encode('utf8')):
# print(bcrypt.check_password_hash(result['password_hash'], password.encode('utf8')))
# print(bytearray(bcrypt.check_password_hash(result['password_hash'], password.encode('utf8'))))
session["logged_in"] = True
flash("You were just logged in!")
return redirect(url_for("staffdashboard"))
else:
flash("Incorrect password, please try again.")
return render_template("login.xhtml")```
check your db as well
make sure the columns are loaded properly
because it's already in my query
sql = "SELECT email, password_hash FROM users WHERE email=%s"
ahh i see
hehe
for me the big error was that I actually was not pulling the right hash
so iw as getting invalid salt
but i feel like yours isn't pulling anything because you're getting a none type
i can't help you more than I've done already though 😦 i suggest use lotsa prints
now i have this error
i just removed the len() > 0
and then i tried and got this error
@pulsar hinge Sorry, I went to a meeting. Why do you have a scripts.html? Why not have a js file with them and load those into the base file in the header or after the body tag?
sry I can't help too busy 😦
@pulsar hinge Sorry, I went to a meeting. Why do you have a scripts.html? Why not have a js file with them and load those into the base file in the header or after the body tag?
@devout coral Yea, tried that as well. Didn't change anything. But I solved it removed variables and referenced to it directly.
@pulsar hinge I just noticed your variables were not in the same scope... They were made outside of the functions.
Yes, as the error reads you are trying to add a non-nullable field and you need a default or allow it to be null.
oh
@devout coral so what would I do? I just want to create a new model.
would I allow it to be null?
@mortal mango If the picture is not needed sure, otherwise set a default. Like if it is for a profile picture I would suggest you set a default.
I want to put an image url so I set it as charfield.
Can't I just go into the admin page and put in the URL?
so what is the default?
what would it be used for?
@devout coral
Ah Django is so beautiful, my model relationships worked perfectly, was worried about how I would be able to identify which one I would want, but Django made sure to take care of that for me.
@mortal mango Show a snippet of the code you are trying to add into models
@mortal mango You can set the default to just an empty string then.
@haughty turtle Good to hear!
I thought you were using a FileField but since it is just a CharField empty string for default is fine.
Yea I just now need to figure out how to get it to give my users the same options outside of admin.
Nice. How did you end up implementing it ? With a select widget?
Yea the default it would be the most user friendly way for my client to access the admin panel.
anyone here familiar with the paypalrestsdk?
@mortal mango You can set the default to just an empty string then.
@devout coral oh ok
you can't set it as an empty string
it says please enter some code
and if I put a space, it says Invalid Input
What do you mean?
You mean the form is not validating and it is giving you that error? Or you cannot migrate?
@toxic flame I am not.
Anyone knows how to display a foreign key's attribute instead of its default representation? For example, display the sender's username instead of their primary key
Here's my model for the Message object:
class Message(models.Model):
sender = models.ForeignKey(Account, on_delete=models.CASCADE, null=False,
blank=False, verbose_name="Sender", related_name='sender')
receiver = models.ForeignKey(Account, on_delete=models.CASCADE, null=False,
blank=False, verbose_name="Receiver", related_name='receiver')
content = models.TextField(max_length=512, blank=False, null=False,
unique=False, editable=False, verbose_name="Message")
read = models.BooleanField(default=False)
timestamp = models.DateTimeField(auto_now_add=True)```
class Account(AbstractBaseUser):
email = models.EmailField(verbose_name="Email", max_length=64, unique=True)
username = models.CharField(max_length=30, unique=True)
date_joined = models.DateTimeField(
verbose_name='Date Joined', auto_now_add=True)
last_login = models.DateTimeField(verbose_name="Last Login", auto_now=True)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
objects = PigeonAccountManager()
def __str__(self):
return self.username
def has_perm(self, perm, obj=None):
return self.is_admin
def has_module_perms(self, app_label):
return True
def get_username(self):
return self.username```
That's my model for my account object
@icy fog You mean you want to change it's default representation, like if you were to do a print(object_here)
Yeah, something like that
cuz it's not helpful to debug when it's only showing me the ID of the Account object instead of its username
Your __str__ method handles that. So change the return of it
The str method works fine for other representation because it works here where it actually displays the username of the Account object
My problem is that it doesn't display the username on the 'sender' attribute when it's represented on the API view of DRF
Is it a good practice to have your migration files in your version control repo? It seems not
is there some way to manually change the representation of that without affecting the value of the attribute itself?
@trim star Yeah not a good idea, you normally want to add migrations to gitignore
@icy fog What representation, I am sort of confused now.
This representation
@devout coral Thats what I thought
It seems to retrieve the Account object's ID and display it directly instead of using the str method of the Account object
I don't know if it's possible to change the way DRF API-view displays it
@icy fog Can you not just change it in the view where you do the return for the get request??
Hmm, I think it might be possible but I'm using generics for that one
here's what my view for it is:
class MessageListView(ListCreateAPIView):
queryset = Message.objects.all()
serializer_class = MessageSerializer
permission_classes = [permissions.IsAuthenticated]```
I don't know if it's possible to define a method which alters the presentation of the Account object's value so that it uses the str method
@icy fog I think a custom serializer is the only way to go then..
@mortal mango ... I meant to set a default in your model... Not just press 1 and give it a one off.
oh
default=''
oh ok
it worked!
is there a way to upload an image to my domain url? like mydomain.com/image and it would show the image
Like an image field?
no like I want my domain to be an image url
so like I would do mydomain.com/image and it would show the image
Like an image field?
@devout coral is there an option for an image field?
Yes image fields exists in django models
oh so I just want my logo to show up. So people can get the logo.
so the easy way would be to do an image field right?
I have another best practices question:
So the application that I'm contributing to has a non-interactive mode for instances in which the admin does not have access to the command line. They print an initial default password to stdout for the admin to log in, and never enforce that the admin change that default password.
This seems like a security issue to me..what do you think?
So would one recommend flask more for api development and django for progressive web apps? Or would it work better to use a flask backend to a react/angular app?
So would one recommend flask more for api development and django for progressive web apps? Or would it work better to use a flask backend to a react/angular app?
@vale orbit what do you mean "progressive web app"?
you can use DRF (Django REST Framework) to build an API
consider also FastAPI
Single Page Application is what I mean.
I have also heard good things about connexion for api development, any thoughts on that one?
Single Page Application is what I mean.
I have also heard good things about connexion for api development, any thoughts on that one?
@vale orbit if anything, vanilla Django would be worse than Flask for SPAs
never heard of that, sorry
Ok, then I guess I will stick to my initial instinct of “use flask backend as a replacement for express js”
DRF will work for that too
Which one allows for faster development time?
Does anyone know how to set up post requests in django rest framework?
or does anyone know any good tutorials
Does anyone know how to set up post requests in django rest framework?
@mortal mango what do you mean?
I want to post something to my API json data
Which one allows for faster development time?
@vale orbit I'd say Django...? because it's opinionated
but idk exactly how
do you mean you want to POST from Django, or handle POST requests in Django?
in
I'm new to django
yeah I've done that
how to get Voice Verified
I have pretty much everything set up except for the post
@vestal hound
Django, API, REST, Views
does return Response send the user data?
from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from . models import exo
from . serializers import exoSerializer
class exoList(APIView):
def get(self, request):
exo1 = exo.objects.all()
serializer = exoSerializer(exo1, many=True)
return Response(serializer.data)
def post(self):
return Response({"message": "Got some data!", "data": request.data})
return Response({"message": "Hello, world!"})
def home(request):
return render(request, 'files/index.html')
@vestal hound this is my code but it's not working
"detail": "JSON parse error - Expecting value: line 1 column 1 (char 0)"
oh
still not working
same error
"detail": "JSON parse error - Extra data: line 1 column 5 (char 4)"
I'm making a request to my API endpoint to sign users up and I just tried to add session authentication, but I don't know what to do and the DRF docs are confusing.
My error:
{"detail":"Authentication credentials were not provided."}
My view:
@api_view(["POST"]) # API view for POST requests
@permission_classes([IsAuthenticated])
def register(request): # This will register a user from their POST request.
if request.method == "POST":
if "username" and "email" and "password" and "confirm_password" in request.data:
if request.data["confirm_password"] == request.data["password"]: # Checks that password is confirmed.
hashed_password = make_password(str(request.data["password"])) # Hashes password
request.data["password"] = hashed_password
else:
return Response(data={"password": "Passwords do not match"}, status=status.HTTP_400_BAD_REQUEST)
serializer = UserSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(data=serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(data=serializer.errors, status=status.HTTP_400_BAD_REQUEST)
else:
return Response(data={"error": "Model fields not satisfied"}, status=status.HTTP_400_BAD_REQUEST)```
How do I provide auth details?
same error
@mortal mango what are you passing in the request
@native tide hm.
you should let your serializer do all of that
what should it do? 😳
the view?
the view should pass the data to the serializer
and let it do validation.
in particular
if you use, for example, is.valid(raise_exception=True)
a ValidationError will automatically be caught and returned in the Response as 400
basically, any work involving converting from/to data that will be sent over HTTP should be done by the serializer
Sure I can move over the validation to the serializers, but what do I need to counter:
{"detail":"Authentication credentials were not provided."}
It only appeared as soon as I added session auth. I think I need to provide a CSRF header in my request but I did that (I think) and I'm not getting anywhere
@mortal mango in your Response, do data={your dict}
that's probably a frontend problem
Probably, I just don't know what it wants as "Authentication credentials"
Ah, actually I think I see what I may have done wrong
For session auth I think I need to include the user's username and password in the request
of a user that already exists
yeah, I'd guess that you're sending your auth stuff wrong
@mortal mango in your Response, do data={your dict}
@native tide is response in my views or in my actual post request?
#settings.py
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication'
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
]
}```
It's so weird. As soon as a enable SessionAuth I get that error, even on the signup view. So I must be doing something wrong
@mortal mango Your POST request is a request to the server. The response is the server's JSON response, which is in your view.
I heard that using token auth is bad, is that true? I got discouraged from using it in favor of sessions - but that's a headache.
I heard that using token auth is bad, is that true? I got discouraged from using it in favor of sessions - but that's a headache.
@native tide why is it bad?
I don't know, I just got told session auth > token auth
and now that I'm reading about it, for my specific use case making AJAX requests to my api, I think that token auth is more suited
just because I don't want to fiddle around with cors and cookies 😄
no, I mean, why session auth > token auth
I wouldn't know. I just got told it is, infact it was in this channel lmao
@native tide if you using session authentication then you need to pass csrf token in your POST request, how are you passing it on the frontend?
ajax ? or just normal form
Was doing it with a normal form, I had the header with the X-CSRFToken but I was getting an error (its somewhere up in the chat).
I'm going to stick with tokens though.
@native tide that not really answer my question. There 2 way to send a POST request from the front end. Use normal form with {% csrf_token %} in the form. But you said had the header with the X-CSRFToken which is the method of using ajax/jquery to send POST request
its
{% csrf_token %}
ty i was mistyping
I'm hoping to use Django to make a website for my current side hustle. I know what I want my site to look like. Are there any WYSIWYG style editors that leave with pretty standard html I could read/use? Are they all damn near obfuscated with javascript. I literally only know of dreamweaver
@oak cave yes django have a package for that, it's called django-ckeditor you can check out it here https://github.com/django-ckeditor/django-ckeditor
Hello👋, I am looking for a solution to add notifications 📩 to my flask website. Can you lead me to an solution that you know is working? Thank you 🙏
JavaScript has a notification API if that's what you mean
hey need help with my p5.js setup using cdn
hello what do you need help with ? @native tide
Uhhh i am getting syntax error here:
return {
"success": True, {
"Company": company,
"User": user,
"Staff": staff
}
}
I just cannot see why? Can anybody here see what i am doing wrong?
@silver shell post your error traceback message instead of the code if it's syntax error. It can tell which line the error happened
@gaunt marlin found the issue
@silver shell yeah i see you passing dict, but the second element don't have key value
exactly
hello what do you need help with ? @native tide
@gaunt marlin p5.js cdn embed link plzzz
@native tide it's on the p5 project website https://p5js.org/get-started/#hosted
p5.js a JS client-side library for creating graphic and interactive experiences, based on the core principles of Processing.
ok
jquery link in jquery official site, you only asked me for p5.js cdn...
@native tide https://cdnjs.com/libraries/jquery
Hello
I need help with the concatenation
I'm trying to concat str and dictionary .
I already used str()
but I'm not satisfied with the result.
this is what I've got after using str()
@app.get('/api/case-image/{case_id}')
def case_image(case_id: int):
db = DB.init_db()
image_path = DB.get_case_image(db, case_id)
db.connection.close()
#print(image_path)
site_url = 'http://10.34.102.60/jupyter-suture/view/suture-api/'
#return {'image_path': site_url+str(image_path)}
return {'image_path': site_url + image_path}
@app.get('/api/case-image/{case_id}')
def case_image(case_id: int):
db = DB.init_db()
image_path = DB.get_case_image(db, case_id)
db.connection.close()
#print(image_path)
site_url = 'http://10.34.102.60/jupyter-suture/view/suture-api/'
return {'image_path': site_url+str(image_path)}
#return {'image_path': site_url + image_path}
@merry copper this is my code
!code @merry copper use this to format your code so it don't look messy
Discord has support for Markdown, which allows you to post code with full syntax highlighting. Please use these whenever you paste code, as this helps improve the legibility and makes it easier for us to help you.
To do this, use the following method:
```python
print('Hello world!')
```
Note:
• These are backticks, not quotes. Backticks can usually be found on the tilde key.
• You can also use py as the language instead of python
• The language must be on the first line next to the backticks with no space between them
This will result in the following:
print('Hello world!')
also what is your unsatisfied with the return string?
!code
Discord has support for Markdown, which allows you to post code with full syntax highlighting. Please use these whenever you paste code, as this helps improve the legibility and makes it easier for us to help you.
To do this, use the following method:
```python
print('Hello world!')
```
Note:
• These are backticks, not quotes. Backticks can usually be found on the tilde key.
• You can also use py as the language instead of python
• The language must be on the first line next to the backticks with no space between them
This will result in the following:
print('Hello world!')
Hello guys, I'm using Flask for almost 6 months now. Can anyone link some Projects done with Flask on Github so that I can read a bit of code and it'll be easy for me to learn more concepts on Flask.
Thank You 🙂
!projects maybe there are some here
Kindling Projects
The Kindling projects page on Ned Batchelder's website contains a list of projects and ideas programmers can tackle to build their skills and knowledge.
i guess not
@hard spear i can't post all of it because there are many, but if you search http://www.google.com/search?q=flask+project+example+github then you can find some. Most of them are open source
Wow that'll be really nice
@hard spear also i recommend this one https://github.com/gothinkster/flask-realworld-example-app as it's one the popular github repo of real world apps https://github.com/gothinkster/realworld (collection of real world repo base structure of all framework)
Exemplary real world JSON API built with Flask (Python) - gothinkster/flask-realworld-example-app
"The mother of all demo apps" — Exemplary fullstack Medium.com clone powered by React, Angular, Node, Django, and many more 🏅 - gothinkster/realworld
Okay I'll def check this out
Is there an easy way to reuse a navbar?
@gentle ingot yes if you talking about code base then you can apply that navbar in a block and reuse that block in other templates.
Okay thanks. Ill look into blocks. I only have three pages and it's already getting annoying updating the links lol.
Can anyone tell from where I can download templates?
Can anyone tell from where I can download templates?
@clear arch what do you mean
Can anyone tell from where I can download templates?
@clear arch colorlib.com
@nova nacelle thx
@nova nacelle thx
@clear arch np
@gaunt marlin I'm not using Django forms. I'm using a React frontend, with the csrf token in the header. But idk lol
@native tide for react you need to set header in your POST request
headers: {"X-CSRFToken": csrfToken}
your csrfToken you get from Django
if you using react then why not use JWT token instead?
session way harder to manager with a front end framework
Yea I'm using token auth, well im trying to
Apparently my models need to extend the base User model which Django provides
So now I'm changing it all :D
that sound like reinventing the wheel for me
Is there anyway to do password hashing within a Django model, instead of doing it outside the model then passing the hashed password to the model?
you can override save() method of your model to do hashing within model when call save() outside
sounds good, thanks!
also what is your unsatisfied with the return string?
@gaunt marlin I don't want it to return in list format tho.
@merry copper from your image seem like image_path data return a list of many image path, you can do a for loop on image_path and just return each one
for example
image_path_list = []
for path in image_path:
image_path_list.append(site_url + path)
return {'image_path': image_path_list}
does this make sense ?
@gentle ingot yes if you talking about code base then you can apply that navbar in a block and reuse that block in other templates.
@gaunt marlin I didn't think about this earlier but can I update the active tab?
When you switch from home to games>brotastic, look at the change in highlight on the navbar.
Hi. I have a serializer which is based on a model with a relationship to another model. Relationship is called staff and it has blank=True and null=True. However, when i ask my serializer to validate some dict-like data with a missing staff field, it invalidates and says: "This field is required.". Ok - fine...So to counter that i then setup in my serializer staff = serializers.PrimaryKeyRelatedField(queryset=Staff.objects.all(),required=False) and now i don't get the required error anymore... But heck, if i then now use my serializer to serialize an existing object, I now then get this error: "AttributeError: 'RelatedManager' object has no attribute 'pk'"... So what do I do? How do i use serializers on models with non-mandatory relationships?
@gaunt marlin session way harder to manager with a front end framework no its not. And sessions are safer
JWT is mainly for public APIs and JWT's are heavily overused and misunderstood. Just dont use them
further they require you to maintain whitelists/blacklists, frequent and infrequent refreshing etc..... loads of annoyances... Session cookies has been around for a long time and have proven their worth. They are httponly (as opposed to e.g. JWT which can be read easily from JS)...and they are nativly supported in most webframeworks
@native tide sure you can...but you cannot store it in an http only cookie
for obvious reasons
sure you can?
ok, how on earth would you do that?
nah bruh session auth is harder to do if you have a react frontend at least
compared to token
im not about to argue best practice and if you should or shouldnt
im simply saying you can and it eliminates the js can access it thing
@native tide eh no...got my session based cookie stuff going w. react frontend in 1 hour or so
good for you
@native tide further...why would you even do that if thats what sessions are already doing?