#web-development
2 messages ยท Page 104 of 1
so would this item be a widget your client is selling themselves? or a website that shows a product that might be on amazon and it shows on your site but when they want to buy it it takes them to amazon?
so your one site might link off to dozens of other places that are actually selling?
more of an product aggregator?
Sort of
I'm going to have a page to add and remove items though
I just need a secure place to store this data
k, where are you hosting your app that also doesn't have a db for you to store said data?
I'm not hosting it for them haha
where are they hosting it?
I'm not sure
cause if you need a "free" database that doesn't have secret info in it you can actually use google sheets as a crude backend
They're aren't being real explicit about things
@devout coral Hey, I got a new domain for my API. I set an A record pointed at the VPS. But my VPS is only accepting http for some reason. If I do the same domain but do https://, it doesn't work. It says This site cannot be reached. But if I do http://, it works but the css says forbidden. Do you know why this happens on my new domain and not my existing domain?
So I kinda just have to come up with a lot of stuff
but again, I wouldn't store anything in it that is "secret" even if it is a private sheet
yeah I've had clients like that man it's rough ๐
Lol
Im just like
give me a freaking requirements docs
so i can actually do stuff
xD
they'll be telling me to add stuff at the most random moments
@mortal mango A record points to VPS, but is the VPS using something like Apache or nginx as the web server? They need changed too to "catch" the throw from DNS. And also to listen on the port for SSL on that IP.
so you may have your first domain set up on say 12.13.14.15:80 and :443, but 22.23.24.25 is only listening on 80
also i have sort of a noobish question
go ahead
how do i make an optional parameter in a route for a flask app?
@warm igloo I have apache
like lets say you have /x/y which could be an index, but then you could have /x/y/z
@warm igloo do you know what I need to change to make it work?
oh ok
haha thats the same SO post i read earlier
but now that i read it again
i realize you can specify defaults from the method parameters themselves instead of the decorator params
So, in apache, do you get to make your own changes to the vhosts? Like you can edit your httpd.conf? @mortal mango
@native tide Exactly. Route doesn't need to be optional, the func can.
Cool. See the *:80? you need a virthost defined for 443 too
oh how do I do that?
it's nicer in nginx cause you can do both in same definition of vhost, but in apache I believe you have to have two separate ones
you said its working for your other domain? there should be an example in the same conf file (assuming this is same server you said it does work on)
no, same file is fine
oh so where do I put 443?
it's too much to type out so trying to find a good tut for you
cause what you'll probably want to do is reduce your :80 vhost down to "accept this traffic and redirect to 443", and the 443 vhost will have all your other directives there.
on my servers, cause I never want to serve over 80 but someone might still try to go to it without https, I catch the request and automatically redirect to 443 version
ok
so what's port 80?
http
oh
and 443 is https
I'm making an api
so people would use http requests
so that would stop working right?
well, still http protocol
you want them to do it via the ssl version
no real reason to let it be plain text over 80
you have a ssl cert installed and everything yeah?
so yeah change that to 443
k
and if you see people trying non-ssl version, then you can add a small vhost definition to say "nah bro, go here"
oh ok
it's giving me the default apache ubuntu page
how do I make my static files to show?
RewriteEngine On
RewriteRule (.*) https://yourdomain.com$1
</VirtualHost>```
That's from memory. Probably close but not *quite* right.
Oh, sorry, that's for the 80->443 redirect.
Looks like your DocumentRoot is /var/www/html?
good question .. why aren't they showing
no, not if that's where your files are
is this a flask app? django? totally static?
django
I'm django-dumb, hmm.
You changed the port on the vhost and then restarted apache but ... now only the default ubuntu page shows?
yeah
Makes me think there is another vhost definition of 443 with its own DocumentRoot
can you search for DocumentRoot in that conf?
wdym
something is answer on 443 and serving that ubuntu page
cause your definitions look good
oh so like there's another 443 that's handling it instead of mine?
perhaps yeah
apache can get weird cause the conf files can include OTHER conf files too
er, shit, I gotta bounce man, I hope you figure this out but if not I'll be back tomorrow .. good luck though
You shouldnt use http outside of localhost
port 80 should redirect to port 443
https
hey um im kinda stuck so i was making a thing where u click the button and a database will make a random generated code which is a room.
everytime a person pressess that button. they redirect to that room ther will be a global timer in there and scraping stuff
but.. heres the catch. Will it be like a session or like its globally each link?
or i should make a new file using the built in python file manager
wait why do you need to create files
@vivid spear
shouldn't your web framework have sessions
just use that and store the session data
for each room
session data is stored server side per user
hi need some help
is it possible to delete a session every 10 min?
when i downloaded python 3.9.0
what modules should i use?
it dowsn't work but for 3.8.0 it dose work
session timeouts?
so why is thta
@warped timber yeah like itll delete the room on my db
not all packages support 3.9 yet
not all packages support 3.9 yet
@warped timber ok
just put a check into the view route
what is the new runtime for 3.8.0 and 3.9.0
so i always have to check it
or you could do something with a background task
but idt that's necessary
just check whenever you access it
if it's past the timeout then stop the room
and clear the appropriate session data
oh ok thanks :) i tought my work would be fixed if i just made a new html file every time someone makes a room
Yea, but do it in Virtual environment
pip install django===3.1.2
the 2nd one just installs a specific version
uhhh so idk whta to do tho
the 1st installs the latest version compatible with your other deps
so do the 1st unless you have a specific reason no t to
please don't spam put your question in a short sentence
Do u have django installed? Do you have created virtualenv? Are u in ur virtualenv? Redo your error, and send ss of cmd here @gleaming basin
whhhhhhhhhhhhhaaaaaaaaaaaaaaaaaaaaaaaaaaaaaat
Give me screenshot of your cmd error
what error it raise when you type django-admin ?
Can someone help me with HTML tables?
keepalive
--keep-alive INT
2
The number of seconds to wait for requests on a Keep-Alive connection.
Generally set in the 1-5 seconds range for servers with direct connection to the client (e.g. when you donโt have separate load balancer). When Gunicorn is deployed behind a load balancer, it often makes sense to set this to a higher value.
Guys, what if my request takes more than 2 minutes, it's ok to increase this value ? It's about a flask app API with gunicorn and the request sometimes has to wait for some things to complete way over around 150-200 seconds
keepalive --keep-alive INT 2 The number of seconds to wait for requests on a Keep-Alive connection. Generally set in the 1-5 seconds range for servers with direct connection to the client (e.g. when you donโt have separate load balancer). When Gunicorn is deployed behind a load balancer, it often makes sense to set this to a higher value.Guys, what if my request takes more than 2 minutes, it's ok to increase this value ? It's about a flask app API with gunicorn and the request sometimes has to wait for some things to complete way over around 150-200 seconds
@peak meadow that's...really long.
why does your request take so long?
Because
I'm writing some ssh commands to my raspi
and Waiting for the output
and that's how long it takes
it will be used only by me
like
Hmm. I have no other way to wait for the output and also return something
because it might go wrong so I can return what's wrong
the orthodox way to do this is to return HTTP 202 with some sort of ID
then have the client periodically poll the server with that ID (or use server-sent events)
but if it's only for your personal use
do whatever you want
My web server will sent requests
and my clients
but for my clients
which is only one
for an api
it takes less than 1 minute for them
In the code I'm using time.wait so my ssh commands can make effect and return an actual output so I can work with it
Can someone help me with HTML tables?
@neat goblet Just use html table generator
Do I need the Professional edition of PyCharm to style css with suggestions etc.
#help-coconut selenium
When using templates (a base.html and a index.html) do you have the index.html css stylesheet loading in a link in the base.html, or does each html file have to load it's own css stylesheet?
using templates in django
Hello guys
I really need some help with my Django project.
The login system was all fine and working, but it's no longer working again. I've gone through the code even started the project afresh the registration works alright but I can't login not even with super admin to the admin portal.
I really need some help.
Please who can help me debug this.
@slim beacon you would use a base.html of course, follow django princile of DRYS(Don't Repeat YourSelf)
{base block}
{content block your index.html}
{base block}
@twin sable maybe post your login implementation so we can know what wrong with it
@native tide your img path?
I posted my website to production
static you need to run different
@native tide have you run django-admin collectstatic on production environment yet? django in production mode don't use path like development
try to open image with the media path then see if return
I'll do that
@gaunt marlin My CSS loads in the base.html, but it isn't loading in the index.html. Although my other static files (imgs) load up in the index.html no problem.
@slim beacon you can try going to developer mode in google chrome, check console and see if any of the css path return 404 first
It didn't work @gaunt marlin
@slim beacon on your child template should also add {% load static %} at the start so it detect static template tag
@gaunt marlin I have it load static loaded, but ill check chrome to see if the CSS is returning 404
@native tide you tried to go to the image path in src="" yet? does it return the image?
404
says it doesn't exist
yes so the image path is wrong or the image can't be access
But I can do so in development
do you deploy django with nginx ?
no. What is that
yes but django path is different on development and production
oh yeah ok
oh you just run django runserver?
in development yes
did you read over this part on django docs? https://docs.djangoproject.com/en/3.0/howto/static-files/#deployment
i haven't done pythonanywhere so sadly i don't know the process
i suspect that you set up like the docs
if so when you run collect static it should get all static file into a directory and it should work
@gaunt marlin Hey thank you for mentioning checking the dev tools in chrome. That pointed me to figuring out what the error had been and I fixed it.
@slim beacon oh nice, glad i can help
It seems that there was a 404 with a missing js.map file (a sourcemap i guess its called), and i googled what was going on and it seems that this is a somewhat common problem
found this that spoke more about it
Thank you for your help!
@gaunt marlin Thanks for replying
<form method="post" action="{% url 'login' %}">
{% csrf_token %}
<div class="form-group icon_form comments_form">
<input type="text" class="form-control require" name="username" placeholder="Username*">
</div>
<div class="form-group icon_form comments_form">
<input type="password" class="form-control require" name="password" placeholder="Password *">
</div>
<div class="login_remember_box">
<label class="control control--checkbox">Remember me
<input type="checkbox">
<span class="control__indicator"></span>
</label>
<a href="{% url 'password_reset' %}" class="forget_password">Forgot Password</a>
</div>
<div class="about_btn login_btn float_left">
<button class="btn btn-primary p-1 form-control" type="submit" name="button"> Login </button>
</div>
def userLogin (request):
if request.user.is_authenticated:
return redirect('dashboard')
else:
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('dashboard')
else:
messages.info(request, 'Username OR Password is incorrect')
context = {
'title' : 'Login'
}
return render(request, 'account/login.html', context)
in your view can you print out password and username?
this is my view above
Sorry am not familiar with discord, how do I do that?
def userLogin (request): if request.user.is_authenticated: return redirect('dashboard') else: if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('dashboard') else: messages.info(request, 'Username OR Password is incorrect') context = { 'title' : 'Login' } return render(request, 'account/login.html', context)
there '`' tick and python
Okay seen it
close with those three tick again
<form method="post" action="{% url 'login' %}"> {% csrf_token %} <div class="form-group icon_form comments_form"> <input type="text" class="form-control require" name="username" placeholder="Username*"> </div> <div class="form-group icon_form comments_form"> <input type="password" class="form-control require" name="password" placeholder="Password *"> </div> <div class="login_remember_box"> <label class="control control--checkbox">Remember me <input type="checkbox"> <span class="control__indicator"></span> </label> <a href="{% url 'password_reset' %}" class="forget_password">Forgot Password</a> </div> <div class="about_btn login_btn float_left"> <button class="btn btn-primary p-1 form-control" type="submit" name="button"> Login </button> </div> </form>
```lang
code comes here
```
from django.contrib.auth import views as auth_views
from . import views
urlpatterns = [
path("register/", views.registration, name="register"),
path("login/", views.userLogin, name="login"),```
@fast tendon thank you
@twin sable does it return any error while you trying to login?
else:
messages.info(request, 'Username OR Password is incorrect')
When I try logging in with a registered user account superuser I keep getting the else statement.
@twin sable can you try printing out user in your views to see what it return?
because it failed at the if statement so we need to know what it returned
okay
add print('user': + str(user)) in the code and try to login- > check console what does it print out
Hi guys, which request method is used to update an existing model?
@twin sable ok so the authentication() return None, now we know. Next print out username and password to see if it captured from the request
it's correct with database?
yes sir
you using django authenticate() method right?
yes
user = authenticate(request, username=username, password=password)
the imports are there too ```py
from django.contrib.auth import authenticate, login, logout, update_session_auth_hash
and in your settings included?:
#Authentication backends
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
)
oh btw are you using custom user model or django user model?
django user model
and in your settings included?:
#Authentication backends AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', )
@gaunt marlin no its not included in the settings
try adding it and restart the server
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
okay will do that
remember AUTHENTICATION_BACKENDS is not AUTH_PASSWORD_VALIDATORS, don't mix those 2 things into eachother
good to hear
Thanks a million and one extra
@twin sable i figured you missed this part of the documents https://docs.djangoproject.com/en/3.1/topics/auth/default/#selecting-the-authentication-backend
Taking the CS50 course
ah i see
on EDx am still finding my ground and getting used
Taking the CS50 course
@twin sable to Django
@twin sable i figured you missed this part of the documents https://docs.djangoproject.com/en/3.1/topics/auth/default/#selecting-the-authentication-backend
@gaunt marlin I did. I find the documentation overwhelming. But i really should pay more attention to it.
there's cs50 web as well if ur taking the regular course instead
it's ok since now you know, next time you will know how to fix it
debug is a skill
print every variables
Yes definitely.
it's ok since now you know, next time you will know how to fix it
@gaunt marlin
I just learnt that now. never would have learnt that on the course
yeah most course don't teach you how to debug
there's cs50 web as well if ur taking the regular course instead
@unborn dust CS50 Web dev by Brian Yu and Dave
yeah that course is cool
because when working 100% you would encounter bug
@gaunt marlin honestly that's true, 80% of the time I've spent working on this project was debugging error luckly solutions were on stackoverflow
yeah that course is cool
@unborn dust Best decision I've made this year.
i need some help
after i select * from register there are empty datas in it
even if i fill the input fields and check the tables register there are still empty datas
i wanna get the datas dynamically to my database
hi i need a little help with file uploading using flask_wtf. what does -> TypeError: object of type 'FileStorage' has no len() <- mean?
@wanton ridge I am guessing that is flask?
so i'm trying to implement an API that has to support login from two OpenID Providers (Google OAuth and OpenAthens).
i'm a bit unsure as to how to implement "secured" API endpoints - for these secured API endpoints i'd need to decode a JWT token but how can I tell if the token is Google's (and then use a google token validation service) or if i'ts OpenAthens (and figure out how to decode those) - perhaps once doing the regular oauth login flow I should generate my own JWT tokens instead of using the one supplied by the OAuth provider? thoughts?
@devout coral yes
For an API to update an object within a model... should I be using POST, PUT or PATCH requests?
@native tide patch
Ok, thanks! I don't really understand the difference between PUT or PATCH requests... Other than PUT is meant to update the whole object and PATCH just updates certain fields of an object... Is that right?
im not sure why my post method is not working
@native tide exactly
@swift sky i guess if you don't put in at least a screenshot of your code nobody can help you ๐
@app.route("/survey", methods=["GET", "POST"])
@login_required
def call_survey():
# forms and connection
phone_survey = PhoneSurvey()
connection = db_connection()
cursor = connection.cursor(pymysql.cursors.DictCursor)
# survey questions
terminal_number = request.form.get('terminal_number')
was_this_pandemic_related = request.form.get('was_this_a_pandemic_related_call')
what_was_the_call_about = request.form.get('what_was_the_call')
was_resolved = request.form.get('was_the_inquiry_resolved')
if request.method == "POST":
#query
insert_sql = "INSERT INTO phone_survey (terminal_number, was_this_a_pandemic_related_call, what_was_the_call," \
" was_the_inquiry_resolved ) VALUES(terminal_number = %s, was_this_a_pandemic_related_call = %s," \
" what_was_the_call= %s, was_the_inquiry_resolved= %s)"
#execution
cursor.execute(insert_sql, (terminal_number, was_this_pandemic_related, what_was_the_call_about, was_resolved))
connection.commit()
connection.close()
return redirect(url_for(call_survey))
return render_template("call_form.xhtml", form=phone_survey)```
I get a method not allowed
when i try to submit my form
@swift sky i guess if you don't put in at least a screenshot of your code nobody can help you ๐
@ebon gust i only wrote a small amount to see if people were interested, because it's tedious pasting code and explaining everything only to have nobody respond
@ebon gust but thank you for your advice ๐ i appreciate your efforts in helping.
@warm igloo I'm back. Are you back?
if someone fill the form then those datas should be direct to the database
that's what i want
Im using tailwindcss alongside django.
I've tried getting downloaded custom fonts in the way tailwind css tells you to, but its not working. Do I need to do something else since Im using django?
The font and the css file(not the one containing the utility classes, but the file from which the output css file is made) are in a folder alongside the mainapp folder, away from static folder
@jolly matrix have you downloaded your fonts the folder where you store statics?
nope
then?
everything with with tailwind generates the output css file is in a single folder, including the fonts
nope I'll try that out now
thanks
no problem
Hi there im struggling finding a way to export a dash datatable in order to get it into an outlook email using win32. Anyone perhaps know a solution to this?
Example here:
https://stackoverflow.com/questions/64498244/exporting-datatable-with-python-to-outlook-mail?r=SearchResults
:(
Do you guys know how to get total price (sum of all discount prices and prices).
return self.quantity * self.item.price
def get_total_item_discount_price(self):
return self.quantity * self.item.discount_price
def get_end_price(self):
pass```
If you need any code please tag me. Thanks
@wanton ridge try db.session.commit()
instead of
can you provide code in a bin?
@next needle how to do it, never done it
paste your code in and copy/paste link https://hastebin.com/about.md
well somehow i can't save it
save it there, and send url to it
For those using Flask, what front ends do yall utilize? I'm fairly new to webdev stuff
Heres my extremely beginner level question. Do websites built with flask or django still typically use javascript? Or is the scripting done in python?
For frontend u use js. Backend is done with python
@pulsar hinge quick question why i my link empty, i paste my code there
https://paste.pythondiscord.com/ click new, paste your code, save, send link
@next needle here is the code https://paste.pythondiscord.com/qatutejawi.py
should I use wtforms if i wanted to make something that a user can input text into, and that text would be loaded onto a db
Seems like it
i wasn't sure if there was another way
ahh, kk.
Guys, how to make a new connection to database everytime with Gunicorn ? I'm getting this every time: MySQL Connection not available. with flask app and mysql.connector
It worked with uWSGI when I have specified lazy apps to true
Which loaded app in each worked insted of master but I know that Gunicorn already does this however I can't connect to the database
it works if I specify this: mydb.reconnect() after every query I have to make..
uhh what i did was just place my connection info into a function
and reference that function in my methods
and code in the connect, the query, the disconnect.
the cursor.
you need to also close out the connection after every query otherwise server will force you out, since each worker will have its own connection running
it works if I specify this: mydb.reconnect() after every query I have to make..
@peak meadow so do that
idk
im noob
reconnect works :)) way simpler than your solution but both works
@swift sky
I was looking for something so I don't have to use this every time
i have different db that i connect to though
I'm using mysql connector
like more than 1 db
I will
anyone have experience using "FOR JSON PATH" for sqlserver with pyodbc?
Hello everyone.
I am very new to Flask I have gotten to the point were I have and input box and in the terminal it shows a POST html. I dont understand how i can take that and use it as a var to input into my other script. Could someone help.
@fast lagoon You have to use the request.form.get function and put the class of the form as the parameter
kind of like this
# Ensure username was submitted
if not request.form.get("username"):
return apology("must provide username", 403)```
The formatting on that may not be great so don't just copy paste
Time to renew my PyCharm license ๐
@pale dove i want to take request.form.get("username") and input that into a different python script to pull from an api
no print it on the website
idk if im making sense
that's fine just put what comes back from that and put it into a variable
you'll have whatever the user put into the form
You can add the logic of your script right on that post. request.form.get("field_name") will simply return the value of the field that you passed the field name. You can set that to a variable and use the value as needed.
you got it bud
also @devout coral you seem pretty smart do you know of any free libraries for speech recognition that work with the python library SpeechRecognition?
It is funny you ask that I was looking into starting my speech recognition project a little while back but I do not remember what the conclusion was for the research and I did not save it either...
May I ask what you are working on? You have caught my interest.
It's a homebrewing assistant app actually
I'm a homebrewer and I need something to take hands free notes/set timers etc so that's what I've made
only problem is the speech function has to run in the background to get woken up or else it's not really hands free
I've got the logic to work but google only gives 50 requests/day
and it requests once about every 10 seconds
Oh, well I know there are some free libraries
The application makes requests even on idle?
yeah it's similar to how alexa and siri work
so they don't really ever stop running they just keep processing your voice and wait for the "Hey siri" phrase to wake up
Yeah, but why not use a module that is not great but runs locally to process the wake up command?
Then once it hears it anything after that gets sent to Google
that's definitely an option that I'm open to
i don't really mind if the background one is on board or via the web
but the options are limited for on board ones
and I do plan on having this available to the public when I'm done
so using the web based one does seem more attractive
Well you would only need it to recognize one phrase pretty accurately and that is all
yeah that's it
And use the web based for everything else
Ok, I am currently taking a break from my project cause itโs Friday so let me see if I can help you out.
thanks bud
Also, out of curiosity why are you on the web deck one of you are working on something that is not related to web dev?
Not that I mind. Just wondering.
I wanted to help out UrgentCashew and you seemed knowledgeable so i figured I'd ask you haha
I already opened two rooms for my issue I'm in neon if you wanna switch to that
sure
Hi - is it possible to somehow add custom forms to admin site? I need to make a form where i enter some data which causes 3 model instances to be created in the right order with some constraints....so instead of having to remember that order and constraints and use default forms it would be very beneficial to make a custom form for that
I hosted a site year back on zeit (now called vercel).
I can't find my project anymore on my pc.
So I am trying to download the project I hosted but unable to find an option.
Can someone provide a solution ?
@bitter trail use scp or rsync?
No idea what you talking about.
@silver shell rsync is faster
@topaz widget that depends...
for big recursive copies, I think rsync is faster.
I changed my mind on trying to use a webscraper in django. It just seems that it works best as a plugin to a browser. Wouldn't really be any use in a web app.
Sure it would.
maybe
I can think of plenty of uses.
doesn't seem logical unless you use inter-process communication, because protractor is a separate instance of a program.
i have no idea what protractor is.
I don't see why that's a problem.
seems like too much work when you can just get the job done in a web browser client.
And your web app could totally run the scraping internally.
no, it needs a separate instance.
Not necessarily.
I don't know what protractor is, but there are other ways to do scraping that could be incorporated directly into your web application's logic.
completely synchronously.
most webscrapers are built from selenium internally and you need to plug into a browser driver
like chromedriver
yeah, there are headless browsers.
wdym?
but there are also simpler web scrapers that don't need a browser.
They just use pure http requests.
you know of any with an API I could use?
What I mean is that there are browsers that don't need a gui to run and can run on a server.
name one.
BeautifulSoup
ok
not a browser
That's a library for scraping.
You would use Python urllib for the scraping.
to make the requests*
how do I know the difference between something like selenium and beautiful soup?
where would be the determining factors?
Selenium can run JavaScript, beautifulSoup can only parse static html.
So BeautifulSoup is limited in what it can do compared to Selenium.
so, does it use spiders or something and read elements like a search engine would?
in static html?
BeautifulSoup is more of an html/xml parser.
It's not really used for making requiests.
That's done with Python's urllib.
why did you say you could make requests with it then?
I didn't
so you use one in combo with the other.
Anyway, here's some information on using Selenium on a server:
https://stackoverflow.com/questions/17854598/can-selenium-be-run-on-a-server-to-automate-tasks-or-does-it-need-a-browser-to
i don't want to read that , but I get you.
yes, you need to use beautifulsoup with urllib
ok thanks
my question wasn't if selenium works on a server.
it's a question of what is better to use.
and hooking into a chromedriver is not what I want to do
Hey, so I want to create a new field to my object, and that field will contain several users, how can I do that?
I would like to add a button to users' pages and that button will add them to that specific object field. (Django)
or running a separate script
Here's a somewhat trivial example of using BeautifulSoup:
import urllib.request, urllib.parse, urllib.error
from bs4 import BeautifulSoup
import ssl
# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
url = input('Enter - ')
html = urllib.request.urlopen(url, context=ctx).read()
soup = BeautifulSoup(html, 'html.parser')
# Retrieve all of the anchor tags
tags = soup('body')
for tag in tags:
# Look at the parts of a tag
print('TAG:', tag)
#print('URL:', tag.get('href', None))
print('Contents:', tag.contents[0])
#print('Attrs:', tag.attrs)
yeah it looks like that's what I would want. It's the tool I have been looking for
๐
Be forewarned, though, you probably shouldn't be using web scraping for some kind of web application in most cases.
If a website wants you to programmatically access their data, they will almost always have an API for that sort of thing.
If you plan on doing this ethically--even being able to use BeautifulSoup completely synchronously in your website's code--I would recommend doing the web scraping asynchronously since you can't control how long it will take a website to respond to a request.
Anyone here have experience setting up celery?
I might just use AJAX if I were going to use something like this and de-couple the web scraping functions from my website's "views".
With django that it.
AJAX would send a request to the server, which would then handle the scraping and return a response to the user in JSON.
yes, AJAX is nice.
I have not used any server-side asynchronicity yet.
I suppose I can run it in django and connect to sites on the backend and box the data into a database.
Yes, you could. I'm not sure how to handle asynchonous views or endpoints on the backend, though.
I want to create a controller logic that calls it
works as an intermediary between the view and model logic
well, you wouldn't need to use AJAX in django
oh
Not sure if it would be necessary or if all that stuff is just handled under the hood in Django.
there is an async python library I bet.
there 100% is.
I just don't know if you need to use it or if views are called asynchronously innately by Django.
yeah that would be the next step in my learning of Django
how to build the logic on the backend and send a view to the client
shouldn't be a big issue
Usually it's pretty straightforward, but communicating with a server controlled by a third party is another matter.
which is why I just want to use a browser plugin for it.
I might just be overcomplicating things.
If you're the only person using your application, you can use the browser plug-in, but if it's an application that will be used by other users, you can't really expect people to download a browser plugin to use your web app.
depends on how big your company is really, but generally a company has its own software.
If this is just going to be used internally to some organization, then yes, I suppose you could.
you could have a bunch of people using browser plugins on different clients
I was thinking more for mass consumer market.
yeah
Joe Schmoe should not have to download a plugin to use your website.
something that is client based would definitely need to be defined as that.
You might even just do the scraping on the front-end.
I've thought about this issue.
but you are overcomplicating things.
Here's why I might do it on the front-end...
not overcomplicating, may even be simpler.
it is
There is a good reason to do it from the browser.
Django does not work asynchronously you need something like celery for that.
Which is what I am trying to set up but setting it up on windows is a pain and I do not feel like putting it on the server to test that functionality atm.
Distribute the requests so that
- you don't have to worry about server resources
- spread the IP addresses of the requests to avoid getting IP banned due to excessive request volume from one source
Wait what are you trying to do?
Box is trying to do web scraping within a web app.
The web application does web scraping.
web-ception
it really depends on the application you are trying to make as to doing it front or back end.
true, but if all the data is just going to the user, the client can just do the scraping and then save whatever needs to be saved to the back-end when done.
the bigger issue is security
It would distribute the requests and resources better by having the front-end do the scraping.
Seems to me like JavaScript would have decent libraries for this sort of thing.
It really depends on your use case.
If you just want a server continuously analyzing certain web pages, then yes, better to do it on the back-end.
But if the scraping is initiated by a user's whim, it might be better to do it on the front-end.
i didn't really want advice on how to make an MVC app, so you are over-thinking
It's relevant to what you asked, though.
and it's straightforward
Like, I said, it really depends on your use case.
I said that before you did.
be nice y'all
also, front end scraping is gonna hit CORS issues amongst other things that limit js's reach
good point
If you want to scrape with js, it won't be in browser, it'll be nodejs and you'll back to backend at that point. nodejs does have scraping libs, but they're not gonna run in browser.
that's why i'm in this channel, because I know it's back to back end.
That's a good point and a big oversight on my part.
it's silly to think you can run this on the front end.
and if you're worried about being banned, you're building a scraper that is against TOS and that means we should NOT discuss that on this discord server
its against the rules
I know. But getting banned for doing it was mentioned, which then means the target has limits, which likely means some TOS setup, which IS against the rules to violate ANY tos on any site
Search engines use scraping though.
And Box, no need to be condescending, they worked through it, had a discussion, and now they see there would be a lot of limits to make it not a good choice
yes, and people like good bots and hate bad bots .. don't build a bad bot
er, my misread then cause it totally seemed like you were in the convo and being snarky .. my bad
chat is fun
so easy to misconstrue tone
I don't think you were misconstruing anything.
yeah, i'm not bothered by it.
hey, look, a squirrel! back to web dev talk? ๐
lol. I need to hit the weight room actually...
I didn't think you needed to connect to another server in urilib
it just let's you connect to endpoints
not any specific server but it's a feature of the api.
it doesn't even matter and you can connect from client or server.
it's just a built in web browser basically
kind of like what you would see in React Native.
this guy went on a rant about MVC but it's fine.
i'm not upset about it, so let's just drop it.
Trolls like that wouldn't land a job very well or find it hard to land a job.
that's why there is Karma for Trolls.
wtf are you talking about?
lol no worries
plz.
absolutely mental. i was trying to help you. jesus.
how many job interviews have you had?
wtf are you two arguing about
I'm done talking to you psycho
this is epistemological
@warm igloo I was going to ask you a question, but this chat has been poisoned.
just ignore me
"i'm not bothered by it" has to make sure to replay the conversation in a summary just to prove some point
lol
time to step away and paint some toy soldiers, peace y'all
pz
Reading through everything that you lot have gone through is mind boggling
it's an interesting topic, but I do think implementing a webscraper on the front-end is a waste
you need a data store if you are going to go that route I believe.
I know that webscrapers are frowned upon because they can be used for evil things, but I would be using it for legitimate business purposes.
The only reason todo it as if it was a actual 'client' would be to make use of the JS enabled system and testing
I blocked that other guy. He was being insane.
which does exist for the record
yeah you would use it for protractor
For example Selenium is a multi-language set of packages that completely automate the browser
I was trying to help him and then he just started going psycho on me.
front end testing for endpoints and that's it.
you generally wouldnt use the front end directly with a manual client on it because it causes all sorts of issues
but browser automation is not uncommon for testing
and entire systems are built around that
What do you mean by security issues though and in what context
you can make requests behind a reverse proxy on a cloud service for example instead of making it client specific
make what client specific though lol
so it's nice to give someone advice up to the point that they want it is my point. If you tried to give your boss advice you would get fired pretty quick.
Just a word of advice.
I think I have said enough and that includes advice for trolling.
i mean coming from someone viewing this outside of that conversation it looks like none of you really knew either what you were talking about or what the actual topic was, Just looks like a mess of one person talking about one thing and the other on another trail of thought
because you are in a different perspective.
how could you get what we are talking about
just like i didn't know what he was saying.
it works both ways
because i have eyes and a brain, I can scroll up and read through the conversation
:P
yeah right...give me one good point about it
It just looks like you two trying to one up each other every time tbh
you can't really speak paint with a broad brush and expect results either.
which is what you are doing right now...
๐คฃ Im starting to see who caused this original issue now
I'm the one who asked the question originally.
So yes, and what reading skills and brain if it took you that long.
Constructive Criticism.
That's not constructive criticism that's picking fights with people who originally were trying to help you Altho i think discuss would be a better word for this lmao
๐
well, I don't think anyone likes an over explanation of a topic.
I know this from experience.
you end up cheating yourself and making yourself look bad.
I was just trying to save him from embarassment.
๐คฃ Im gonna resist the temptation of opening this can of worms
whatever, I'm glad someone has a sense of humor in here.
I admit I don't know it all.
I know pythagorean theorem and that's enough for me.
you need petabytes of storage to be the best troll.
at that point you may as well be A.I.
troll bot 2.0
I'm making an API request with a username field which is less than 4 characters long. It is responding with "Ensure this field has at least 4 characters." but I don't know why.
This is my model, I added MinLengthValidator to the username field, but my message is different to that being shown on the API response. Does anyone know why?
class Users(models.Model):
username = models.CharField(max_length=20, unique=True, validators=[
MinLengthValidator(4, message={"error": "Username must be at least 4 characters in length."})])
email = models.EmailField(validators=[EmailValidator()], unique=True)
# Email validator similar to that within a form.
password = models.CharField(max_length=100, null=False)
lmao
MinLengthValidator has a param of 4 in it that's probably why ๐
The 4 specifies the minimum length of the passed value
you asked why is it giving you an error of minimum of 4 characters
I think that's it
idk
I didn't ask that
I think I've found my solution anyway. It's just that I specified the message="something" in my validator which should be the message shown in a ValidationError (I think?) but I can just write a custom validator with my desired message which does the same thing
if the issue I specified isn't the effect then it's certainly the cause.
Does message actually take a dictionary
i like sets
Looking at le docs it takes a normal string
I don't know. Probably not. But I have tried a string also and it doesn't work so idk
I take it you're using this as a model form not just saving it after making it
Yeah but they're not automatically ran technicall6
Though further reading validator Litterally just does
If X > nunber
No idea what you're going on about but okay
lmao
this wasn't the college course we were looking for.
I'll keep the main validation on the backend and the minor stuff (like making sure username > 4 characters) on the Frontend. Using react so might as well
Cant give a scooby doo to work out why django does what it does
but it is what it is
It's a weird issue I'll give you that
Most likely it'll be something random throwing it off
This is the validator itself
class MinLengthValidator(BaseValidator):
message = ngettext_lazy(
'Ensure this value has at least %(limit_value)d character (it has %(show_value)d).',
'Ensure this value has at least %(limit_value)d characters (it has %(show_value)d).',
'limit_value')
code = 'min_length'
def compare(self, a, b):
return a < b
def clean(self, x):
return len(x)```
And somehow it is returning this??
I don't even see how that validator is creating that message
I am using a serializer so maybe it's doing something
If you remove the validator does it give the same message out of curiosity
That message only came up when I added the validator to the model
Is this DRF?
Looking at their docs they have a bit of a diffrent system todo validator with the serializers
Then again this is probably going beyond my experience with django
Ooh that is probably the problem. The validation error in the docs is eerily similar to my one
Lol changing the message that the validator itself returns changes nothing. So it must be a serializer thing
This is definitely above me... gonna shove this behind the counter
Lol changing the message that the validator itself returns changes nothing. So it must be a serializer thing
@native tide it is
validation is a serializer-level operation
in DRF
HOLY SHIT NOW IT WORKS
yesssiiirrrrr
Thanks @vestal hound
So, the serializer does the validation. If I .save() a serializer object, will the model I already have also do its validation on the data?
So, the serializer does the validation. If I .save() a serializer object, will the model I already have also do its validation on the data?
@native tide nope
basically Django model validators are tied to Django forms
Oh okay, so any validation I have in a model's field is only for its forms?
uh...
okay maybe I didn't explain that properly
let me rephrase
in DRF, validation is run solely by the serializer
BUT if you use a ModelSerializer, then it pulls the validators from the (model) fields and uses appropriate substitutes when creating the serializer fields, as a convenience
you can read https://www.django-rest-framework.org/api-guide/validators/#validation-in-rest-framework for more info
Django, API, REST, Validators
With
ModelFormthe validation is performed partially on the form, and partially on the model instance. With REST framework the validation is performed entirely on the serializer class.
...
When you're usingModelSerializerall of this is handled automatically for you. If you want to drop down to usingSerializer classesinstead, then you need to define the validation rules explicitly.
(emphasis mine)
Ahhh. That explains a lot. I was using ModelSerializer and I didn't know where my validation message was coming from, so I guess it did it automatically for me. That was the thing I wanted to change
yeah, you can change it by manually defining the field in question
And is that only achievable by making it a Serializer Class?
If I have a modelSerializer like this...
Is there a way to manually define each field and add their validators?
And is that only achievable by making it a Serializer Class?
If I have a modelSerializer like this...
@native tide just like
title = serializers.CharField()
for example
Am I doing this right? I tried to define each field explicitly but for the ModelSerializer I need the class Meta and fields = [] defined... So I ended up with this:
class UserSerializer(ModelSerializer):
class Meta:
model = Users
fields = ["username", "email", "password"]
username = CharField(max_length=20,
validators=[MinLengthValidator(4, message="Usernames must be at least 4 characters long")])
email = EmailField()
password = CharField(max_length=100)```
This is just using the fields in the fields variable and not the others.
Doing it with Serializer, not ModelSerializer, works just fine.
@native tide no outside Meta
Awesome! Thanks @vestal hound that gave me a great practical understanding of validation with serializers. I'm new to DRF so I'm yet to understand all the theory but that's made what I want to do much more easier and understandable
Really appreciate it
yw
in django i need to save my email to a .log file. Should i just open and write to the file everytime the email is sent? Or is that a bad idea because if i sent a lot of email then i would have to open the file, write, etc everytime
in django i need to save my email to a .log file. Should i just open and write to the file everytime the email is sent? Or is that a bad idea because if i sent a lot of email then i would have to open the file, write, etc everytime
@quiet comet depends on how many emails you're sending
its just for testing
I'd suggest just using the simplest implementation
then if it's slow you can worry about it
premature optimisation is the root of all evil
so whenever i send a email i open the file and append the email? k, i was just wondering if there was something better
so whenever i send a email i open the file and append the email? k, i was just wondering if there was something better
@quiet comet well I mean
it's not a very complex problem so the number of alternatives is limited
open file every time you want to write
buffer and open file once in a while
hold file open constantly and write
well ty anyway for calming my paranoia
Anybody familiar with saleor ??
Why is an SPA considered non-ideal for an ecom website?
Why is an SPA considered non-ideal for an ecom website?
@near bison according to whom
That isn't true? i read it somewhere and stuck in my mind. Someone was saying that amazon has never even looked into SPAs because of the capping of scalability, which isn't good for an ecom venture
so I am using flask to make a website and I need this if statement to work inside the html code but it does not want to work everything has been defined correctly as far as I am aware and yet it still does not work any help would be greatly appreciated thanks: [https://paste.pythondiscord.com/uyorunomor.xml] Line 24 {% if server.get('owner_id') == owner %}
hi
someone told mwe we can use django for frontend
he is using it is this true
Hello #web-development! I am working on a web platform, currently working on some different authentication methods. I am seeking for your input. What authentication method should I use, when I want the best ease for my clients/users? I have worked with a passwordless method and jwt token based method. "My end goal would be to let the client only have to enter an e-mail adres where a verification link would be send to the clients e-mail adres, where if they click on it, it would ask for there information." If someone could give me somewhat information to reach my endgoal I would love to know that." Thanks in advance! ๐
hey people is there something in flask that lets you add more variables like link.com/name&date&email&stuff
hi
someone told mwe we can use django for frontend
he is using it is this true
@full steppe frontend is the elements that the user interacts with like buttons and pictures and stuff like that so front end would be html and css. html is used to display data and css is used to stylize that and customize your website further and as far as i am aware django does not do that.
anyone familiar with sqlalchemy. I need help to get my datas dynamically to my database when a user fill the input fields
this is what i am getting. I don't know what am doing wrong
Can anyone help me find out how i can send a styled dash datatable in an email? Or is this a problem that nobody can solve in python?
Looks like i found the problem that broke the python internet
try upgrading your SQLALCHEMY
pip install --upgrade Flask-SQLAlchemy
@wanton ridge ^
still same @next needle
@wanton ridge https://paste.pythondiscord.com/kedizogake.py
yeah i tried and it says no db is defined and then i define db, then it says scoped sesseion has no attribute execute
Does anyone use tailwindcss here? SOLVED
Im having a problem with customization. The changes I make in the tailwind config file does not take effect after building. Im trying to enable the active variant for the backgroundColors.
This is not related to Python but maybe some of you might know. Why this isn't working ?
so with sudo and same path the app is not found..
You haven't given it any cli arguments
@wanton ridge
Have you initialized your db
Also, wouldn't it be better to not use raw SQL? You could have a model Users and then say user = Users(username="x", password...) and then do db.session.add(user) then db.commit()
Was your code snippet in a different file to main.py (or whereever your DB is intiailized)?
no different file, same
Without seeing the rest of the code I don't know what else it could be.
But one thing I would recommend is using the ORM without raw sql, then just do db.session.add(object) then db.commit(), you know what I mean? @wanton ridge
Is there any reason as to why you can't use the ORM that way?
https://paste.pythondiscord.com/qatutejawi.py @native tide
i have this
it works but it doesn't send the datas to the database
Does your route '/' add data to the db
after i check my database i am getting this
empty datas
i talking about the /register
So why in the '/' route do you have db.execute and in '/register/' do you have session.execute
ahh yeah let me change it
but do you know why i am gettting empty datas in my database wheen i go to my register site and fill datas in then click on submit
Hey i am trying to deploy a web app in heruko and i am getting this error at log
at=error code=H14 desc="No web processes running" method=GET path="/" host=mouse-position-tool.herokuapp.com request_id=91c3aeb6-399a-4c82-be2a-8b24f096d720 fwd="183.83.152.226" dyno= connect= service= status=503 bytes= protocol=https
Here is the link to my project https://github.com/Prasanna-Natarajan-3595/Mouse-postion-tool if anying wrong please help me
name = request.form["Name"]
email = request.form["Email"]
password = request.form["Password"]
session.execute("INSERT INTO antworten13 (Name, Email, Password) VALUES(?, ?, ?)", (name, email, password))
@wanton ridge try this
@wanton ridge Did it work?
@native tide sadly no
@wanton ridge Yeah but isn't that a different error
See where the error lies
Also dude @wanton ridge why can't you just use ORM? Why raw sql?
for learning raw sql is better for me first
If you insist... if you just use ORM it wouldn't have been a problem. I think the sql complicates it
But anyways where is the new error
i have no keys
i have another question @native tide
if i use ORM i dont need to create a table in my .py right? i can just create a table via terminal mysql right?
@wanton ridge You create a model in Python... say you create a model called Users, then in your '/register/' you can just do:
user = Users(username="something".....)
db.session.add(user)
db.commit()
and the user object is added to the db
Read the docs on it
ahh thanks
It's much better to use models rather than raw SQL because with raw SQL you will be repeating yourself often e.g. if you want to validate userinfo and overall it's much easier
Hi there, which db would you use if you had to choose, PostgreSQL or MySQL, and why?
This is somehow related to Python. Does any of you have any ideea ?
The path is the same but when using sudo and the path, it's not working
Hello, has anyone integrated any crypto currency (Blockchain preferred) payment and receiving API with Django?
Please don't ignore if you have.
I want to have a React frontend with a Django backend. Can anyone let me know how I should do session management or auth?
can you guys explain to me how the urls/requesting/etc works?
https://docs.djangoproject.com/en/3.1/intro/tutorial01/#write-your-first-view
@fervent vortex When you make a request to a URL, your Django app will have a view which is a Python function which will run. For example, rendering a .html page for the user to see. In Django you can set which URLs you want your website to have and you can assign views to them. So, if I make a request to mywebsite.com/register/ my view renders a sign-up page. If I make a request to mywebsite.com/pricing/, another view will render a pricing page.
Are JWTs a good option for React-Django combo?
The urls.py in your root directory will contain the urls for your apps. So if you have apps polls and pricing, it will contain the urls for them.
Then in your apps if you want any leading urls, like /pricing/new/, you will add the new/ there
You don't need to have 2 urls.py but seperating it by app makes it nicer
hm ok
I am using django session based auth and i want to be able to test my endpoint via url using python manage.py test. How do I do that?
@native tide "Are JWTs a good option for React-Django combo?" use session based auth
Is that possible if I have a React frontend with a Django backend? They only communicate via APIs @silver shell
@native tide of course its possible - why shouldn't it be?
I'm not saying it isn't, I've not worked with Django auth yet so I'm just unsure on what to do.
then use session based auth ๐
I can refer you to this blog post that has a github repo which explains exactly how to do it: https://blog.tinbrain.net/blog/session-auth-spa.html
Thanks, much appreciated! @silver shell
yw
Just setup a signup API and currently I'm making a React signup form to try to test it out. I'll be back with some questions when I get to that point haha
ok. have fun'
Hi guys, anyone knows why I'm getting a 403 when I'm trying to run a test against a Django REST Framework API endpoint on my own localhost server?
class RegisterAccountTest(APITestCase):
def test_register_user(self):
url = '/users/'
data = {
"username": "testuser",
"email": "testuser@gmail.com",
"password": "password321",
"is_staff": 'false',
"is_active": 'true',
}
# Use APIClient provided by Django REST Framework
client = APIClient()
client.login(username='pidgeon-admin', password='[insert password here]')
response = client.post(url, data, format='json')
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(User.objects.count(), 3)
self.assertEqual(User.objects.get().username, 'bobdoe')
client.logout()```
This is my code so far for my test case
Hello, guys
I was working in Docker python web
I have got this error
Docker version: 19.0.12, python: 3.7.9 , Os: Mac Os (Catalina)
Trying to make an API call with axios. But I'm getting this error right after I submit my form:
This is my JS (React)
handleSubmit(){
if (this.state["password"] === this.state["confirm-password"]){
axios.defaults.xsrfCookieName = 'csrftoken'
axios.defaults.xsrfHeaderName = "X-CSRFTOKEN"
axios.POST("localhost:5000/api/register/", {
"username": "ReactUser",
"email": "ReactEmail@gmail.com",
"password": "React",
"confirm-password": "React"
}).then(res => {console.log(res)})
}
}```
And my API view if that will help...
@api_view(["POST"]) # API view for POST requests
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)```
I'm getting a 404 error and my API view does not return them. So the request is not reaching the API
The same issue occurs with post being lowercase
apparently it's something to do with csrf
you should check if you have a session token
I haven't added any session auth yet
Just trying to make a plain POST call to the API view to sign up a user
You should try to clone that repo and see if you can make it work there first....that would be easier to debug for you
I think it's something to do with the form itself. not the axios call (but idk)
return(
<div className="container-fluid">
<form method="get" onSubmit={this.handleSubmit}>
<div className="form-group">
<label className="text-muted">Username</label>
<input type="text" id="username" />
</div>
<div className="form-group">
<label className='text-muted'>Email</label>
<input type="text" id="email" />
</div>
<div className="form-group">
<label className="text-muted">Password</label>
<input type="text" id="password" />
</div>
<div className="form-group">
<label className="text-muted">Confirm Password</label>
<input type="text" id="confirm-password" />
</div>
<div className="form-group">
<button className="btn-lg btn btn-block" type="submit">Submit</button>
</div>```
When I switch the form method from post to get the error message disappears
but if I switch the method on the axios request nothing changes
so it leads me to think it's somethin to do with the form
hehe ok...looks like you didnt read that blog at all
but how can I implement a cookie for a user if they don't even have an account?
what is the best place to learn django?
@native tide you are posting json which is totally wrong for django session auth
and which quite clearly shows you did not read the blog at all
@silver shell but the first API view in the blog checks if a user has an account. I need the user to actually create an account first, by doing this signup form -> api
const data = new FormData()
data.append('username', username);
data.append('password', password);
from the blog
honestly I don't understand what they're doing in that paragraph
In which paragraph?
const user;
document.querySelector('#login-form').addEventListener('submit', async ev => {
ev.preventDefault();
const data = new FormData(ev.target);
const resp = await fetch('/user/', {
method: 'POST',
body: data,
credentials: 'same-origin'
headers: { 'X-CSRFToken': csrf_token },
})
if (resp.ok) {
user = await resp.json();
} else {
errors = await resp.json();
}
})```
And to me it seems like that blog only covers the fact that a user has already created an account. But I have not gotten to that stage yet...
from django import http
from django.views.generic import View
class UserView(View):
def get(self, request):
if not request.user.is_authenticated:
return http.HttpResponseForbidden()
return http.JsonResponse({
"id": request.user.pk,
"username": request.user.get_username(),
})```
@native tide then i can tell you that you are wrong
@native tide it covers sign up, validation and sign out
Could you kindly explain how it covers sign up? Because that's the part which I can't see
You have it right there. You just pasted the javascript part of the sign up code
Ok... so you're making a POST request with these lines:
fetch('/user/', {
method: 'POST',
body: data,
credentials: 'same-origin'
headers: { 'X-CSRFToken': csrf_token }```
where the data is FormData(ev.target) (idk what this is but I assume it's just a dict with username/password etc)
and then that request is handled by this view?
```py
from django import http
from django.views.generic import View
class UserView(View):
def get(self, request):
if not request.user.is_authenticated:
return http.HttpResponseForbidden()
return http.JsonResponse({
"id": request.user.pk,
"username": request.user.get_username(),
})
def post(self, request):
form = AuthenticationForm(request, request.POST)
if form.is_valid():
login(request, form.get_user())
return self.get(request)
return http.JsonResponse(form.errors.get_json_data(), status=400)
})```
and the user data is passed here?
if form.is_valid():
login(request, form.get_user())
return self.get(request)```
Is that the signup route?
const resp = await fetch('/user/', { is the signup route
and why is that?
mmm because thats how its built i guess ๐ I am not sure i understand your question
user data is passed here const data = new FormData(ev.target);
Well as a beginner to Django session auth and having a react frontend I don't think that blog does any favors in teaching why
And yes I did read it
e.g. why this is signup:
fetch('/user/', {
method: 'POST',
body: data,
credentials: 'same-origin'
headers: { 'X-CSRFToken': csrf_token }
Because /user/ handles sign up and data contains signup data
Hi Iโm new this would be to know or can I best learn web-development**
@random karma its good to learn web-development** yes ๐
I am in school but the web development courses are not good enough and it is difficult to learn well
@silver shell Do you know where I can learn more on my own?
Yes, here is an absolutely excellent place to start ๐ https://docs.djangoproject.com/en/3.1/intro/tutorial01/
Ok. So that that was what I'm trying to do. But in the line headers: { 'X-CSRFToken': csrf_token } where is csrf_token defined?
thats what i was asking you initially...to check if the csrf has been saved on your client. Anyway...the github repo linked to from that blog shows how to fish out the csrf_token on your client: https://github.com/bsdis/django_react_session_auth/blob/master/frontend/src/App.tsx#L12
Thanks ^^
how do i run some code every time someone connects to my website?
its flask
like i want to print something like
{ip} connected
or if they are signed in
{username}/{ip} connected
@patent badger I assume you are using templates of some kind? Just print their IP address/username into your template.
return render_template('welcome.html', ip=request.remote_addr, username=username)
then print() it
i wanted one function that would run on every request so i don't have to add it to every page.
so.. gunicorn/your proxy should do apache style logging of the IP address right?
if not..
you can setup logging that includes the IP address/username
'[%(asctime)s] %(remote_addr)s requested %(url)s\n'
'%(levelname)s in %(module)s: %(message)s'
)```
I mean, this is what it logs rn
127.0.0.1 - - [24/Oct/2020 17:37:33] "[37mGET /gallery/kausbrai/ HTTP/1.1[0m" 200 -
127.0.0.1 - - [24/Oct/2020 17:37:34] "[37mGET /gallery/kausbrai/cat-1.png HTTP/1.1[0m" 200 -
127.0.0.1 - - [24/Oct/2020 17:37:34] "[37mGET /gallery/kausbrai/static/bootstrap.min.css HTTP/1.1[0m" 200 -
127.0.0.1 - - [24/Oct/2020 17:37:35] "[37mGET /favicon.ico HTTP/1.1[0m" 200 -
read that link on flask logging, it should help
in django, how to check if contract_date exists?
customer/4/
customer/4/?contract_date=&contract_end_date
so if i do a get request i want to check if it have the contract_date in the url, tried my_param = request.GET.get('contract_date ') but when contract_date have nothing it returns none
@patent badger Im pretty sure that page talks about getting t he proxy IP address
hehehe
setTimeout(() => {window.location.replace("https://www.youtube.com/watch?v=dQw4w9WgXcQ");}, 3000);
add this to make your website 1000 times better
is shitposting allowed?
in django, how to check if contract_date exists?
customer/4/
customer/4/?contract_date=&contract_end_dateso if i do a get request i want to check if it have the contract_date in the url, tried my_param = request.GET.get('contract_date ') but when contract_date have nothing it returns none
@quiet comet so what do you expect to happen ifcontract_dateis not passed?
it says there's no module named random_words @vivid spear
where is it supposed to be located?
replit is having issues i just open shell and pip install it
@steady cypress im just gonna install rnadom words wait
its a pip package?
hehehe
@steady cypress hmmm u tryna rick roll me if i timeout?