#web-development
2 messages · Page 92 of 1
what's in your procfile? and what's your project file layout?
@marble carbon pretty much yeah because its only really become production ready in recent years
its still rather new
@cold anchor:
This is my structure where I am having my git repo:
where is the .git folder?
in procfile i have:
web: gunicorn app:homepage
it looks like that's one folder deeper than the git folder might be
hmm... it looks like my .git file is two directories higher
I assume I cannot create another repo inside
the Procfile and requirements.txt need to be on the same level as the .git folder
just read that here: https://stackoverflow.com/questions/46109465/app-not-compatible-with-buildpack-heroku#51121582
@marble carbon I meant for JS front-end stuff. Like React or Angular.
Wondered if there are any new favorites. Maybe Vue?
Or one that's more friendly with Django
I am trying to make migrations in django
py manage.py makemigrations
and i see this
You are trying to add a non-nullable field 'confirm_password' to person without a default; we can't do that (the database needs something to populate existing rows).
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```
it bothers me...
i might do something wrong
Do you already have data in that table?
You are trying to add a non-nullable field 'confirm_password' to person without a default; we can't do that (the database needs something to populate existing rows). 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```
@native tide we are the same
but i give it a number
Do you already have data in that table?
@dense slate yes in that model
what number @mystic wyvern
Is this a new field?
yes that's a new field
So you either need to give it a default, so that it fills in the current data in that column, or set it to be allowed to be null.
bcz it at have a null value
Because by default it cannot be null.
Because by default it cannot be null.
@dense slate yep
Set default="" or just null=True
@dense slate yes in that model
@native tide u can give it a value
null=True I think is typically frowned upon.
So I would probably set a default in this case.
anyone got experience with selenium?\
Howdy, how would I insert data into a db when I have two different models? I'm pulling in data to a form from another model but the data is not being inserted.
Sorry, I'm using Django
null=True I think is typically frowned upon.
@dense slate nullability is fine if you have a reason for it
That seems like a weird reason. What if the reason is just so it works. 😄
it’s kind of hard to talk about this
without bringing up stuff like database normalisation
and the meaning of nullity
My understanding is that if something nefarious was to be placed in there, when you expected no data, then that could be the main issue.
That's just anecdotal from stuff I think I read.
That it's better not to have null, because something COULD go wrong, but it's not inherently bad to have that set to True.
yeah, basically that
@half bough You want one form to put data in two models?
I came across this a while ago and I thought it was quite a good read
Thanks, @vestal hound
What are your favorite front-end libraries to use? Aiming for minimal but still covering most of the bases. I use python/django for backend if that matters.
@dense slate I use Angular with Django
IMO Angular is like Django and React is like Flask
opinionated framework vs one purpose library
you can also consider Ember...?
there was this quite comprehensive series on Medium that compared them
this
Or one that's more friendly with Django
@dense slate should all be pretty equal, tbh, at least in terms of interoperability. I haven't used Angular, but Vue.js is absolutely beautiful, easy to learn, and works well, so I would recommend that.react is garbage soup, IMO.
My favourite stack is Django, ariadne-graphql, apollo-client, and quasar (vue.js-based CSS framework+).
But definitely do consider other options.
What are apollo and ariadne generally for?
I hear a lot about Vue recently. I'll take a look.
@vestal hound How would you fit Vue in those comparisons?
I'm not an expert FE dev by any means, having only used React and Angular, and only Angular for any length of time
which is why I linked the article
which I think would be much more useful to you than my opinion, written as it was by someone who is an expert FE dev
I'll have a read tonight.
the thing I like about Angular is that it let me build my site with the least amount of cognitive overload
because it is very opinionated, like Django
"you do things MY way and for that I'll give you a solution for every problem you might face"
That sounds about right.
Side note: has anyone used bubble.io?
I'm playing with it recently and.. wow.
Like a new age of Wordpress only on steroids.
Albeit slightly more complicated than WP.
I could see a lot of SaaS type platforms doing this in the future.
I haven't used many SaaS offerings
but I hear the things they can do nowadays are crazy
Anyone available to help with django ? I have the website working. I'm trying to add google api authentication/authroization. I wrote that code already in 1 file. But I realized i may need to do stuff to models.py and add it's own function in views.py not just piggyback off an existing function. also maybe url.py
what is a good beginner web framework?
@visual lake flask is pretty simple
ok I'll try it out thanks!
Hi, I am sure somebody here also knows some JS.
I have a function with 3 arguments,
function foo(a, b = 10, c = false) {
//baah
}
I would like to call it like this:
foo(10, c = true)
- a bit like using keyword arguments in python, referring to them with the name of the argument. Is there a way to do this in JS?
could you give an example for this case?
function f(params) {
const {a, b = 10, c = false} = params
// ...do stuff...
}
f({a: 5, c: true})
also, I thought about using something like default so it uses the default value
foo(10, default, false)
it errors for me tho
but thanks, that object workaround surely has some use cases
?
authorization_response = flask.request.url
flow.fetch_token(authorization_response=authorization_response)
how do you get the django version of this flask code?
and what do you mean "Django version"?
suppose to authenticate and authorize google api
like what is flask.request.url in django. b/c that's a flask function no?
hm
that's the URL to which the request was sent, right?
so if you're moving that to a Django view
think you could use request.build_absolute_uri()?
😮 oh
any tips where you can public your website with webservers. Maybe a tutorial for that would be nice. If someone can help me it would be cool
"public your website with webservers" you mean web hosting? @wanton ridge
maybe try https://pages.github.com/ to start
Websites for you and your projects, hosted directly from your GitHub repository. Just edit, push, and your changes are live.
does anyone have experience with Quart - apparently its an async version of Flask. With the performance increase that you get using asyncpg over psycopg2, I've been thinking about migrating.
I have a pretty massive project so if its going to be a headache and a half I'd rather just stick with my current performance.
I did also consider just using asyncpg with Flask and an event loop, but with all of the blueprints I am using, I feel like it would be chaos (and very impractical).
I only have so much sanity left and I didn't feel like spending it on such an outlandish approach
*pls @ me if you respond, not really active in this channel *
does anyone have experience with Quart - apparently its an async version of Flask. With the performance increase that you get using asyncpg over psycopg2, I've been thinking about migrating.
I have a pretty massive project so if its going to be a headache and a half I'd rather just stick with my current performance.
@normal flintsanic?
or Django?
okay, not Django, ignore that
but anyway...premature optimisation is the root of all evil
actually, ignore everything I just said
if those are your concerns, and you're facing performance problems now, why not do it?
okay, not Django, ignore that
Django 3.2 should be getting an async ORM, so if you want async, it's not a bad choice. It already has async views.
But it won't be out for a few months.
@normal flint there may be other ways to improve performance though. Pre-calculation and memoization, caching, etc.
@vestal hound IT WORKED. thanks. note to self if a webframework like django has a built in functionality dont try to take shortcuts and learn it lol
- literally write code in views.py
- use 2 functions: 1st function has return httpresonseredirect(external url) 2nd function has response code = httprequest.build_absolute_uri()
- add urls.py paths
- index.html write a form tag with action=function_name (views.py ones) and write method="POST"
instead of writing functions to circumvent the views.py and thinking about celery taskschedulers and async stuff/ rabbitmq queues
UGHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH it feels so gooooood. i was stuck on this for dayssssssssssssss.
Django 3.2 should be getting an async ORM, so if you want async, it's not a bad choice. It already has async views.
@lethal orbit the reason I said "ignore that" was
I Googled Quart and it's apparently really meant to be a drop-in replacement for Flask
like
in terms of nomenclature and namespacing
so really most of what you have to do is change package names and add async/await as appropriate
@weak chasm good job!
@vestal hound my project is gobstoppingly humongous, so I was excited when I saw the chance for find/replace imports and adding async/await
performance isn't a huge issue right now unless it gets more than about 3000 requests per sec (my baseline average is around 2400)
my worry is that if it gets any more popular, I will need to upgrade. If I need to rebase the code for a different framework, that would need to start now
that way I don't get caught with my pants down
I only see about a 20% increase in response time at 3000 req/s and my top 1% (4100 req/s) sees a 37% increase
@normal flint what tools do you use to calculate this stuff?
that data is just from looking at traffic metrics for the server
I suppose i could simulate trafffic using a test module
yeah i was asking about these tests
do you know any libraries that can help simulate these conditions?
ill look into those
as for now, i'll probably just start the migration to Quart and hope it goes well
Hello guys, my name is Rômulo, i've been studying python for a few months and i've got to say, i'm loving it! Its my first programming language, and i'm looking foward develop some webapp/website now. i've heard that Django can help me with this task. does anyone knows a free course or tutorials to begin with? thanks
hello people. i have a jinja2 issue
env = Environment(
loader=FileSystemLoader('templates'),
autoescape=select_autoescape(['html', 'xml'])
)
my files are arranged like so ```
app
-templates
-main.py
but jinja raises exception when i try to generate file from template
template = env.get_template('example.html')
#raises and exception, template not found
I have a queryset of users, and I filter that based on the username that is typed into the search field. I'm getting an error that username already exists if I put the full name, but it filters correctly if I only put part of the name:
if form.cleaned_data['username']:
try:
gm_list = gm_list.filter(username__icontains=form.cleaned_data['username'])
query['username'] = str(form.cleaned_data['username'])
except:
query['username'] = "None"```
thoughts on why that's happening?
Forms.py:
username = forms.CharField(required=False)
What's the best way to store an object until a user clicks "Run" to execute it?
what kind of object?
Well, the user completes a form which sends a post request with the instance arguments needed to init a class
I want that class to remain dormant/unused until that button click
in this case a prediction based on previous data which he filters in the form
well maybe you can achieve this via Javascript and make an api view for it
clicking on said button can trigger an ajax or axios request to the api view, which will respond with the required form data
and you can render that data in the html accordingly
class PersonLoginForm(forms.Form):
username = forms.CharField(max_length=20, required=True)
password = forms.CharField(max_length=100, required=True)
def clean(self):
cd = self.cleaned_data
print(self.username) # to debug
actual_password = Person.objects.get(username=self.username).password
if cd.get('password') != actual_password:
self.add_error('password', 'That is not the correct password!')
return cd
i get this error AttributeError: 'PersonLoginForm' object has no attribute 'username'
it clearly has a username attribute
but i still get that error
@native tide its self.cleaned_data["username"] and not self.username
is someone know Telegram bot
@native tide its
self.cleaned_data["username"]and notself.username
@marsh canyon You were a big help. thx man!
I asked this on stackoverflow and look what someone answered.
he even demoted my question
I asked this on stackoverflow and look what someone answered.
@native tide well, the thing is
Stack Overflow isn't really for stuff like this
you're expected to do a LOT of research
before posting there.
@native tide u are using the built in user model?
Who have site of django?
@native tide u are using the built in user model?
yes
you're expected to do a LOT of research
@vestal hound actually i did.
And these types of questions i see most of the time
django provides a view for login if ur using built in user model
and i don't see them get downvoted
I mean
from django.contrib.auth.views import login_view
https://github.com/RohanJnr/IceBook-Django/blob/old_version/icebook/apps/accounts/urls.py
@native tide here is an example
like honestly there's no point arguing about this since you got your answer already
all I will say is that I have answered a lot of questions on SO (per unit time), and I have seen a ton of low effort ones
@native tide how much is "a lot"?
@vestal hound reading two whole pages of the django docs... searching related questions on stackoverflow
to illustrate, the one time I asked a question
from django.contrib.auth.views import login_view
ok i might use this
I more or less read the whole docs (it was a Spark question), the book written by the Spark devs, looked through the source code, etc.
so, yeah.
SO's standards are really high
which is why you'll probably have much better luck in more informal forums like this Discord/reddit
I'm not saying you were wrong
https://docs.djangoproject.com/en/3.1/topics/forms/#field-data
its mentioned in the docs, u had to read the forms section @native tide
but this is honestly quite a basic problem
that suggests that you didn't do enough research for SO.
just my two cents
well, okay
https://docs.djangoproject.com/en/3.1/topics/forms/#field-data
its mentioned in the docs, u had to read the forms section
@marsh canyon Ooh i read that, but didn't get really anything out of it.
Am i forced to use class based views?
the built in view is class based
so, yes?
my whole views.py uses function based views
does that mean i have to convert everything to classes
to prevent confusion?
u can use mixture of class and function based
no restriction there
to prevent confusion?
@native tide this depends on u
I generally prefer class-based views everywhere, but it's up to you
yep 
Am i forced to use class based views?
@native tide for this, yes
in particular, if you want to support several verbs (which is typical of a more RESTful style)
IMO a class-based view is clearer
if you just want a simple RPC-style API, then class-based views kind of lose some of their advantage
So now that i am going to use a class based view for my login page and register page, this clean method isn't needed right?```python
class PersonLoginForm(forms.Form):
username = forms.CharField(max_length=20, required=True)
password = forms.CharField(max_length=100, required=True)
def clean(self):
cd = self.cleaned_data
print(cd['username']) # to debug
actual_password = Person.objects.get(username=cd['username']).password
if cd.get('password') != actual_password:
self.add_error('password', 'That is not the correct password!')
return cd```
what is RPC-style API?
what is RPC-style API?
@native tide hm
probably something you don't need to worry about right now
not that important
you're probably writing it RPC-style anyway
if I simplify it a super lot
basically, REST-style describes what actions you're taking through HTTP verbs (GET, POST, PUT, PATCH, DELETE)
whereas RPC-style tends to use only GET and maybe POST and describe the action through the URL
it's a lot more complex than that but that's basically it
but you really don't need to worry about this
Ok. No i don't
yup
going back to function-based vs class-based
in particular, if you decide to migrate to DRF (and a lot of projects use it)
class-based views are a lot easier to specify authentication, permissions, serializers etc. for
How do i convert this function to class based then
def user_login(request):
if request.method == 'POST':
form = PersonLoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = Person.objects.get(username=username)
if user.password == password:
return redirect('all-users/')
form = PersonLoginForm()
context = {
'form': form,
'title': 'Login',
}
return render(request, 'index/login.html', context)```
then I will authenticate the user inside of it.
have you complete the django tutorial on the official website?
they showcase auth in there don't they?
I'm going to have to check out again then.
any flask developers able to hop over to flourine help channel?
Hello. Can anyone tell me wth is going with Heroku with this error? I am running django app:
2020-09-22T16:18:38.614366+00:00 app[web.1]: ModuleNotFoundError: No module named 'firstDjango' 2020-09-22T16:18:38.614556+00:00 app[web.1]: [2020-09-22 16:18:38 +0000] [10] [INFO] Worker exiting (pid: 10) 2020-09-22T16:18:38.649293+00:00 app[web.1]: [2020-09-22 16:18:38 +0000] [4] [INFO] Shutting down: Master 2020-09-22T16:18:38.649408+00:00 app[web.1]: [2020-09-22 16:18:38 +0000] [4] [INFO] Reason: Worker failed to boot. 2020-09-22T16:18:38.710259+00:00 heroku[web.1]: Process exited with status 3 2020-09-22T16:18:38.743167+00:00 heroku[web.1]: State changed from starting to crashed 2020-09-22T16:18:39.767394+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=django-test-12345.herokuapp.com request_id=1084bab6-5947-4fd2-915b-0bbdea44946c fwd="157.25.189.243" dyno= connect= service= status=503 bytes= protocol=https
Problem is... I don't even know what 'firstDjango' is, I am not sure why it is needed
😩
@maiden kraken show your code
is github okay? https://github.com/mathematicianx/web_scraping_test or do you need anything specific?
to be more specific
im not a django expert, but your procfile is wrong
i think it should be mysite.mysite.mysite.wsgi if i read the docs right
well I was messing around it pretty hard, right now I think that there maybe is a problem because my manage.py is located below, it is not in parent directory
I will try your suggestion, but I also will create new repo with simpler structuture, meaning mysite/mysite will be my main directory
@warped timber Man, thanks a lot for your help... It wasn't exactly that but you gave me an idea. The problem was the nested structure as I worried, I found some information that heroku requires app to be at root repo, so I guess manage.py must be there
just marvel at these ingenius names...
how am I supposed to find literally anythng
class_ = "number" has 250 entries
Whats better for dynamic web apps, PostgreSQL or MongoDB?
Hey, I guess its the best Channel to ask the following question: Is it possible to change the ip adress in A-Record by strato with python. In generall my public adress is changing everey two days and I dont want to pay 50€/per Month for a static one. Maybe somebody got an other Idea, let me know. thanks
@gaunt berry I find mongodb easier to work with
@gaunt berry i think mongodb is easier and you can scale it up verry much better if you need
Thanks 😊
i need to deploy a flask site that works in tandem with a script that webscrapes a few sites, but im not sure how to actually deploy that
yall know any good ways to deploy
pythonanywhere
does anyone know how relative imports work with jinja2??
Folks I need advice again.. I want to create Django/Flask app for transfer payments (Visa/MasterCard/Paypal). Problem is I'm from Ukraine and Stripe and Braintree not available here. Do you have any other solution to create money transfer app on python?
hey, i am trying to build a social network web app using django.
what i need is, when a user create a post it gets updated on feed without reloading the whole page as real time database works on firebase.
do i need to use django channels for that or ajax?
either of those would work
this function based view
def profile(request, pk):
user = Person.objects.get(id=pk)
context = {
'user': user,
'title': 'Profile'
}
return render(request, 'index/profile.html', context)
i am trying to convert to a class based view
using DetailView
but i don't know where to pass pk to now
Hi, somebody knows how to redirect to a certain URL with extra arguments?
I have this at the moment ```python
class Profile(DetailView):
model = Person
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['user'] = Person.objects.get(id=pk)
context['title'] = 'Profile'
return context```
but pk is undefined
Hi, somebody knows how to redirect to a certain URL with extra arguments?
@lavish plover do you mean something like thispython return redirect(f'http://localhost:8000/profile/{new_user.id}/')?
man, I learnt Flask and I loved it. I'm now learning Django and I love it even more... Django hype train, it really is the wave...
I learned Flask too but i don't like it as much as i like Django
I want to redirect it to index
But index only takes request as an argument
I've read that if a view has n number of args, every argument should be added to the url
Idk if I'm wrong
Basically, redirect to index to show an error message, without including that message in the url
And @native tide what's the difference between function based and class based views?
You are kinda limited with function based views, with class based you are not.
with class based views you can inherit methods and attributes from other views. You can't do that with function based views.
damn
I learned about Class based views a couple of hours ago. And i told you my experiences.😀
So,
return redirect(f'http://localhost:8000/profile/{new_user.id}/')
would redirect to /profile/{userid}
But, wouldn't anyone be able to view that page?
And i think i'll be using Classbased views quite often from now on.
yes
and yes
In the project i am creating at least, I am allowing anyone to view anyone
I guess you can then use session management with Django to authenticate that, but I've not learnt that yet.
Ah I see.
Do you guys think Django and Flask will always be neck to neck?
Oh lets make a fun comparison
class-based views is Django. function-based views is Flask
Also, if I wanna create a 404 page
if the view is like this:
def 404_view(request, error_message):
fck
Okay anyways
The url must contain somewhere error_message?
@app.route("/api/launcher/<api_request>")
def LauncherAPI(api_request : str):
if api_request.lower() == "info":
jsonFile = open("oskarsmc-launcher.json", "r")
string = json.loads(jsonFile.read())
string.update({"timestamp": time.time()})
jsonFile.close()
return string
else:
return "404", 404
apparently the code above is calling a dict when i run it through gunicorn3?
that doesn't make sense?
anyway, i managed to fix it by putting ```py
str(string)
instead of ```py
string
yeah because you're returning a dict
oh lmao
you should use json.dumps() to correctly escape it though
also look at json_response() i think it is with flask
actually it doesent matter for my use case because the .json file will always be safe
thanks tho
i wonder why it didnt bug out on my windows installation but did on gunicorn on raspberry pi os
hmm
@golden parrot no but i mean it will fuck up the returning data by doing str() like that
oh
ok then
this should be fine then?
also according to update logs (https://github.com/pallets/flask/blob/master/CHANGES.rst#version-110) flask automatically jsonify's any dict
confuses me more
this says otherwise https://github.com/pallets/flask/pull/3111
password = forms.CharField(label="Enter a password, make it strong!", widget=forms.PasswordInput)
confirm_password = forms.CharField(label="Confirm your awesome password", widget=forms.PasswordInput)```
In Flask there's a validator EqualTo which checks that confirm_password equals password. Is there any such thing in Django, or must I make the user post the request and then manually check if they are equal?
here
Thanks 👍
@gaunt berry i think mongodb is easier and you can scale it up verry much better if you need
@dusk rose you can horizontally scale Postgres with read replicas (read) and partitioning (write).
and MongoDB being "easier" is kind of like dynamic typing being "easier" - part of it is because certain errors are deferred to runtime.
Whats better for dynamic web apps, PostgreSQL or MongoDB?
@gaunt berry both may be applicable depending on your data.
in general, SQL will work.
Hi All, I have a Django question that I'm having trouble with. This is the error "get() returned more than one Detail -- it returned 2!" I'm trying to use get_object_or_404 to return multiple values, is there something else that is equivalent to get_object_or_404 but for multiple objects? or what's my best option?
Hi All, I have a Django question that I'm having trouble with. This is the error "get() returned more than one Detail -- it returned 2!" I'm trying to use get_object_or_404 to return multiple values, is there something else that is equivalent to get_object_or_404 but for multiple objects? or what's my best option?
@naive oar how many objects do you want?
the point of get or 404 is that there should only be two possible results: one or none
I thought I can pull a list from the entire table
you can, but the point is
get or 404 has behaviour specifically for the case where no object is found
it feels like what you want to do is just get a QuerySet of instances that fit some criteria
this is what I'm trying to do, I want to build a parts site and depending on what vehicle brand the user picks it displays the entire table related to that brand
sorry more like everything that is linked to that specific brand
what is "everything"
you're going to need to be specific here
like I said, what are your models?
class Detail(models.Model):
wheelImage = models.ImageField(upload_to='images/')
name = models.CharField(max_length=255)
name_href = models.CharField(max_length=255, default = "")
model = models.CharField(max_length=255)
sizes = models.CharField(max_length=255)
oh lord
please don't mix camel case and snake case
so where's the brand?
that can't be your only model
I'm going off name_href
okay
walk me through your thought process
I'm not seeing what the relationship is
ok
sorry forgot to inculde this
class Logo(models.Model):
brandLogo = models.ImageField(upload_to='images/')
name_href = models.CharField(max_length=255, default = "")
so I have the logo and using the name_href to connect with the detail model
so you're saying
that Logo actually represents a brand?
and when the user picks a Logo
you want to get the name_href
name_href is meant to be a slug
so on one page the logo is displayed with the brand logo image and the name_href so when the user selects that logo it will link to the name_href on the Detail model and display all parts associated with name_href
and find all the
Detailentries which have the samename_hrefand display them
so is this correct?
what are the "parts" then?
so it could be Toyota image with name_href=toyota on Detail it will connect with name_href=toyota and display name, model,sizes,
yes with Detail
okay, so first
if you're trying to describe what you're doing
use your model names.
if you keep saying "part" but show a model named Detail, everyone is going to wonder
what the difference is
whether they're two different things
or not
and it's super confusing.
second
your fields are set up wrongly, I think
so sorry about the confusion
I believe what you want is actually a foreign key
have you heard of the concept?
actually, go back a bit
yes I've heard of that
can a Detail be linked to multiple Logos?
i.e. say you have one Toyota Logo and one Honda Logo; can you have a Detail that belongs to both/
No only one Logo
okay
so what you have is a one-to-many relationship
first, I suggest changing your Logo model name to Brand
next, in your Detail model you can have a field like this: brand = models.ForeignKey(Brand, related_name='details' on_delete=models.CASCADE)
if you set it up this way
say you have an instance of a Brand called brand
and you want all the Details associated with it
you can just do brand.details
and pass that to your view.
does everything I've said make sense?
or is there any part that is unclear
as for why not use that slug field matching approach thingy:
- Referential integrity. A foreign key approach guarantees that if a
Detailreferences aBrand, thatBrandalways exists. - Efficiency. Joining on an indexed foreign key is a lot faster than matching your entire table on a string field.
- Readability. Because this is the most common and idiomatic approach, it is the one that will help people reading your code understand most quickly what you want to do.
so in the view what would be the best way to return it?
@naive oar well, that depends on your template, right?
show your get_object_or_404 call
okay okay
this is what I currently have.
def detail(request, name_href):
detailparts = get_object_or_404(Detail, name_href=name_href)
return render (request, 'allmanufacturers/detail.html', {'detailparts':detailparts})
it makes sense on using a foreign key
uh
no, because you want to get multiple Details, right?
I suggest
you pass the logo ID to your view instead.
this is definilty growing pains
then you can do details = Detail.objects.filter(logo_id=logo_id)
okay I think
you're a bit confused
about how Django models work
have you gone through the Django tutorial?
yes I have gone through the Django tutorial
I'm still trying to get the hang of this.
but since you have multiple Detail objects associated with a Logo
what you need is a QuerySet
which is basically a collection of objects
that fits your criteria
in this case, "belonging to the same Logo that the user chose"
make sense?
yea you mentiond that, I thought you asked me on what I have as the view?
sorry maybe I got confused on that part
yea you mentiond that, I thought you asked me on what I have as the view?
@naive oar yup, we need to see what you have in the view to change it
anyway, your original idea was "get the name_href of the Logo and match that with the Details
so now I'm suggesting
get the id instead
but with a QuerySet right?
got it
yeah
don't worry about not getting all this, though
it's a lot to take in
and please remember to use snake_case
okay I'll clean it up to snake_case
Sometimes this can get really discouraging.
I really do appreciate your help.
I have a lot of reading to do and a lot of things to break in order to grow. 🤣
you're welcome
it's a fun journey
I only started on Django a while ago
there are a lot of things you kind of need to know to understand the whole system
like the theory behind RDBMS
you make it sound so easy?
yea I'm realizing that now
about the naming
was just talking about it a while ago
Hello I would like to ask if some one could explain to me why my Django site isn't loading the correct page.
This is the code that is in {prokect} urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('blog/', include('blog.urls')),
]
```It should lead to here
```Python
urlpatterns = [
path('', views.home, name='blog-home'),
]
urlpatterns = [
path('about/', views.about, name='blog-about'),
]
```Then this should go here and load the page
```Python
def home(request):
return HttpResponse("<h1>You have landed at home</h1>")
def about(request):
return HttpResponse("<h1>You have landed at about</h1>")
But instead it loads the 404 page
@sweet mantle
urlpatterns = [
path('about/', views.about, name='blog-about'),
path('', views.home, name='blog-home'),
]```
you're overwriting your urlpatterns variable
I need some ideas on how to solve a small personal project
project is :
There is a site which gives training like tutorials, I want to make program in python which will visit each tutorial page and click a specific button so that I finishes the lesson and I want it to do it automatically, like automation and I should show me the last page of the tutorial page.. How can I do this? please help
@halcyon bronze use selenium
using selenium for like web automation?
yes
so, how should I do it like do I need to program a web crawler or something else?
I am new to programming learning it
no it's a framework it will do the work you want
ok, so what I have to do in order to use selenium? is there any guide for it?
I don't know much of testing and all those stuff
just see it's documentation
I'm building a flask web app and I'm trying to build an infinite scroll of content. I'm getting that content from a python function but the scroll is built with js. Anyway to have the two languages communicate with each other?
@hexed zenith ajax calls
js makes a request to an endpoint
then your python code responds
oh interesting. @warped timber thanks
u need to look at fetch() api at the js side and returning json content(mostly) with ur flask views or even flask restful can help(if not overkill) @hexed zenith
yooo if any of u are students at a uni, I've been making a Course API. I've added support for three schools with two more on the way! If anyone wants their uni supported, or wants to help out, hmu!
https://docs.coursecake.tisuela.com/
tools: FastAPI | SQLAlchemy | Beautifulsoup
Any with Django knowledge
u can put down ur question here and people with relevent knowledge will assist you @tulip jasper
Ok thanks @marsh canyon
Could anyone explain how I'd go about using apache2 as a reverse proxy for 2 of the subdomains to the domain apache2 is already serving?
I have a async API + cdn That I need to host on the subdomains, but apache2 does not support ASGI so I need to pass the request on to daphne then my app
Hi, is there anyone with experience on selenium and python? I need to scrape Instagram
Scraping instagram is against their TOS, use their API
5. Do not provide or request help on projects that may break laws, breach terms of services, be considered malicious/inappropriate or be for graded coursework/exams.
I knew with Selenium it was kind of possible...
there also on git hub some repos about it. Can you tell me more?
they're illegal
obviously
I don't think any small operations will land you in trouble. But that being said, see rule 5 above.
Thanks @versed python for the info 🙂
always check the robots.txt of a website / TOS to be safe.
https://instagram.com/robots.txt
at the bottom
Disallow: /```
TIL. Is this robots.txt present for all websites? @weak chasm
TIL. Is this robots.txt present for all websites? @weak chasm
@versed python not necessarily
but most big sites will include it
it's more a convention thing
[django]
can someone explain what this regex(?) is doing? found in urls.py
name='complete'),```
can someone explain what this regex(?) is doing? found in urls.py
name='complete'),```
@weak chasm "match any URL that starts with complete/ and a string (call this backend) that does not contain a slash, followed by the string contained in extra. make backend available as a captured group.
at least, that's how I read it
>>> import re
>>> extra = 'something'
>>> regex = re.compile(r'^complete/(?P<backend>[^/]+){0}$'.format(extra))
>>> regex.search('complete/goes_into_backendsomething')
<re.Match object; span=(0, 35), match='complete/goes_into_backendsomething'>
>>> regex.search('complete/goes_into_backendsomething').group('backend')
'goes_into_backend'
if you mean why, I'm not very sure
okay...i'm thinking i might have to use it. trying to figure out why my urls.py changes the url path before i can grab the url in the url box from a httpresponseredirect.
How can I have error handling in my django form?
Hi, I'm using Django and am trying to make an API call but when i print r It returns 'None' can anyone help me?
def get(self, request):
r = request.GET.get('https://www.reddit.com/r/terraria/about.json')
print(r)```
Also, it seems like you're using the django request object. This object can only communicate with the django server, not outside it. @sullen basalt
Looks into requests module which can do this for you
Well that fixed my issue, thank you!
Any thoughts of the justdjango.com site for familiarizing oneself with Django?
I’m enjoying what I’m learning so far and the lessons look pretty extensive
Was wondering if anyone else had any thoughts from trying it
Asking because my free trial has or will expire (I just know it’s sometime this week)
hey
i need some guidance in finding a django package for my need
need for description
i am looking for a django package that let me add social accounts per object rather than user himself.
example i am a userX, in my app i have model company, each company have there own social accounts, so i am looking for this behaviour that userX can attach social accounts to companies object.
any thoughts ?
your question makes no sense. Elaborate
or do you mean using a different mime type, like for images?
return Response(resp. mimetype="image/png")
Anyone good with Heroku? I'm having some weird issues that I can't figure out.
detailed explanation of my problem: https://www.reddit.com/r/Heroku/comments/iy91k4/flask_app_works_locally_but_crashes_when_deployed/
Any Flask developers able to help me out? - #help-lollipop
Is there a reason why my form, when searching/filtering a queryset, throws an "already exists" error if they type the exact username they are searching for but not if they only put part of the name?
I'm not sure why it's doing a check to see if the field exists.
Anyone hear of justdjango.com ?
Is there a way to change the django.contrib.auth.models.User __str__ function ?
I want to return the first_name field, instead of the default username
https://stackoverflow.com/questions/34214320/django-customize-the-user-models-return-field this approach works, but is there not another, possibly better way?
@solar ridge You could use a django custom user model and have complete control. Django recommends it too https://docs.djangoproject.com/en/3.1/topics/auth/customizing/#using-a-custom-user-model-when-starting-a-project
Thank you, i'll have look into this method
i have a tricky session problem if someone is keen: let's say i use auth0 to manage sessions for people logged into my site, but then i have another service managing some 3rd party external session. a user's auth0 session goes stale, but they are still logged in via the aforementioned service to the 3rd party platform. right now my idea is to just pass the auth0 token to the service each time while caching the issue date from the session, check if current_auth0_token_issue_date > previously_cached_issue_date + configured_auth0_staleness_TTL and revoke the 3rd party token--can anybody think of a cleaner way of doing this? seems pretty jank but i'm struggling with finding a better method
Does anybody know why Django is not finding my css file, with this code?
This is the error:
[23/Sep/2020 16:32:07] "GET /static/register.css HTTP/1.1" 404 1662```
{% load static %}
you need this
and to load static files you will need to do this:
href="{% static 'path of css' %}"
@honest dock Is the path of the css, relative to the HTML file, or from the project directory?
You should use the settings.py in the main folder and define where is the static file for the project
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
os.path.join(BASE_DIR, "media"),
]
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static_cdn')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media_cdn ')
I use this
what is the best library for managing and deploying hundreds of databases for distributed workload?
our arsenal right now:
- flask
- sqlalchemy
- pscopycog2
- pygal
- jinja2
- flask-caching
and if you're in development mode, add this to your urls.py file in main as well:
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
@native tide you're only mentioned 1 db driver sooooo
all is postgres
@honest dock Thanks 🙂 This solved it for me:
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
os.path.join(BASE_DIR, "media"),
]```
so in your project, you will have later on a directory called static, inside of it should be a directory called css
I'm running a Flask app on an Ubuntu 16.04 VPS using Apache, nginx & Gunicorn.
When I run the same Flask app on my local machine (just using python website.py) it runs fine, but when on the VPS it fails at the 4th & final API POST request.
API I'm calling: Roblox
Response code: 429
Response headers:
{'content-length': '51', 'expires': '-1', 'roblox-machine-id': 'CHI1-WEB5027', 'pragma': 'no-cache', 'cache-control': 'no-cache', 'date': 'Wed, 23 Sep 2020 12:29:48 GMT', 'x-frame-options': 'SAMEORIGIN', 'content-type': 'application/json', 'p3p': 'CP="CAO DSP COR CURa ADMa DEVa OUR IND PHY ONL UNI COM NAV INT DEM PRE"'}
Cannot find ratelimit documentation online, nor anything about why that response doesn't contain a Retry_After
<img src="{% static 'img/apple_logo.png' %}"
And here is an example of how you will use it later on
@native tide i mean if you want performance you dont use flask or psycopg2
asgi's and asyncpg™️
Anyone? ^^^
Is there any way to assign the label a class, in Django?
Hello, I'm trying to deploy a simple flask app I made to Heroku. When I deploy, the logs at Heroku say it cannot find a user nginx
This is my dockerfile - as you can see I've added user nginx, but no effect
Any idea why?
the USER command does not add a user to the container, i believe. i think what you want is RUN useradd -ms /bin/bash nginx or to run it as an existing user
CMIIW
***then you need USER nginx, after running useradd @brittle basin
***then you need USER nginx, after running useradd @brittle basin
@uncut spire Like that?
assuming ubuntu and a valid bash in that location then yes i think that's right
post the output if not and i'll help you
post the output if not and i'll help you
@uncut spire Thank you mate 🙂 I added the line, but it says it is already added
and previously it said user not found
@uncut spire This happens in later point
The already exists message appears sooner
it's just one container yeah?
Yep
how are you running nginx in there
Hi guys this is my form. Could you guys lead me into a direction to help authenticate the username, to make sure it is unique? Should I check if the username exists in my DB on every post request, or is there an alternative option?
Django btw
how are you running nginx in there
@uncut spire Well basically I call "heroku container:push web -a <app_name>" to create the container and "heroku container:release web -a ourtale" to start it. The nginx starts in the entrypoint script which is inside that image
Is anyone here familiar with using DataTables?
so the user nginx seems to exist within the container, but not on the deploy target which i would guess is the source of that mix up
seems you're using this https://elements.heroku.com/buttons/rjoonas/heroku-docker-nginx-example yeah?
A barebones nginx installation using Docker
do you wish the container itself to host nginx?
so I've only used heroku once many years ago, i believe it's difficult to run images as root, is that still true?
looking at Mr. Ramirez's repo, someone else has had this issue: https://github.com/tiangolo/uwsgi-nginx-flask-docker/issues/201
i'd try following up there @brittle basin or changing your deployment strategy, as it looks like what you're trying to do is run an nginx image as root on heroku
SELECT cash_amount FROM tablename WHERE USER = FrenchFries#8854```
You should probably change your system to use id's, since usernames can be changed.
@atomic hill everything looks fine. Maybe vscode added some tabs or spaces randomly?
pip install autopep8 and autopep8 -ri . in the project root will take care of formatting issues if any
i'd try following up there @brittle basin or changing your deployment strategy, as it looks like what you're trying to do is run an nginx image as root on heroku
@uncut spire Thanks! I'll try that
Would this be the right channel to talk about web scraping?
I'm curious if anyone familiar with Scrapy has used google cache for scraping before. I was surprised to see there wasn't an extension to make scrapy use it. So, I'd like to write one so you can easily set a setting like "GOOGLE_CACHE_ENABLE": True
it was a problem with the enviroment
Not sure if an extension can modify the URLs to be scraped though.
heroku can run docker containers too what
@bot.command(pass_context=True)
@commands.has_role(680261746707267593)
async def addcash(self, usercash: discord.Member, amountcashadd: int):
# TODO actually code this command
cashamountdownload = MySQLConnection.mycursor.execute("SELECT cash_amount FROM Money WHERE USER" == str(usercash))
MySQLConnection.mycursor.execute("UPDATE Money SET cash_amount = %s WHERE USER == %s", (cashamountdownload + amountcashadd, str(usercash)))
MySQLConnection.db.commit()
cashprnt = int(cashamountdownload) + amountcashadd
add_cash_embed = discord.Embed(
title="Adding of Cash Successful",
description=":white_check_mark: Added **$" + str(amountcashadd) + "** to " + str(usercash) + "'s cash balance \
\n cash balance is now **$" + str(cashprnt) + "**",
colour=discord.colour.Color.green()
)
add_cash_embed.set_author(name=str(usercash), icon_url=usercash.avatar_url)
await self.send(embed=amountcashadd)
it says
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
how do i fix?
hi
i have some buttons on a page and i want to add a new class tp each of them with jquery one by one when clicked but what i ve tried isnt working, any idea why?
.turnred{
height: 100px;
width: 100px;
text-align: center;
border: 5px solid black;
border-radius: 50%;
background-color: red;
}
var cells=document.querySelectorAll('button');
for (var i = 0; i < cells.length; i++) {
$('cells[i]').on("click",function() {
$('cells[i]').this.addClass('turnred');
})
}
do you think sending a youtube channel with videos of me coding, and explaining how I'm doing things to an employer would benefit me? I've been making videos, and I've realised when I am talking it through on video and explaining it, I find writing the code so easy. When there is a bug, because I am explaining it on video, and fixing shit real quick. Just wondering if an employer would even take the time to watch these videos ?
@bot.command(pass_context=True)
@commands.has_role(680261746707267593)
async def addcash(self, usercash: discord.Member, amountcashadd: int):
# TODO actually code this command
cashamountdownload = MySQLConnection.mycursor.execute("SELECT cash_amount FROM Money WHERE USER" == str(usercash))
MySQLConnection.mycursor.execute("UPDATE Money SET cash_amount = %s WHERE USER == %s", (cashamountdownload + amountcashadd, str(usercash)))
MySQLConnection.db.commit()
cashprnt = int(cashamountdownload) + amountcashadd
add_cash_embed = discord.Embed(
title="Adding of Cash Successful",
description=":white_check_mark: Added **$" + str(amountcashadd) + "** to " + str(usercash) + "'s cash balance \
\n cash balance is now **$" + str(cashprnt) + "**",
colour=discord.colour.Color.green()
)
add_cash_embed.set_author(name=str(usercash), icon_url=usercash.avatar_url)
await self.send(embed=amountcashadd)
it says
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
how would i fix this?
How can I check if a username is already taken? This doesn't work.
User.objects.filter(username=username) doesn't return None when a random username is passed
oh nevermind found the docs for it
if the queryset is empty .exists() returns False
yeah
But now... the RegexValidator...
How tf does that even work
Maybe it was a bad idea making my own django forms after all
i have this ```python
cashamountdownload = MySQLConnection.mycursor.execute("SELECT cash_amount FROM Money WHERE moneyuser =" + str(usercash))
print(cashamountdownload)
MySQLConnection.mycursor.execute("UPDATE Money SET cash_amount = %s WHERE moneyuser = %s", (cashamountdownload + amountcashadd, str(usercash)))
MySQLConnection.db.commit()
but it says
Command raised an exception: ProgrammingError: 1054 (42S22): Unknown column 'FrenchFries' in 'where clause'
trying to use the fetch() api to GET a json from a flask function. Is that possible?
I used fetch("http://localhost:5000/add-movie") since that would be the link to the function but ofc that gives me an internal server error. any advice?
@wide leaf don't use string concatenation; use parametrized queries
what's usercash?
also
!traceback
Please provide a full traceback to your exception in order for us to identify your issue.
A full traceback could look like:
Traceback (most recent call last):
File "tiny", line 3, in
do_something()
File "tiny", line 2, in do_something
a = 6 / 0
ZeroDivisionError: integer division or modulo by zero
The best way to read your traceback is bottom to top.
• Identify the exception raised (e.g. ZeroDivisionError)
• Make note of the line number, and navigate there in your program.
• Try to understand why the error occurred.
To read more about exceptions and errors, please refer to the PyDis Wiki or the official Python tutorial.
how do i do that? @warped timber
trying to use the fetch() api to GET a json from a flask function. Is that possible?
@hexed zenith you mean a route?
do you think sending a youtube channel with videos of me coding, and explaining how I'm doing things to an employer would benefit me? I've been making videos, and I've realised when I am talking it through on video and explaining it, I find writing the code so easy. When there is a bug, because I am explaining it on video, and fixing shit real quick. Just wondering if an employer would even take the time to watch these videos ?
@past cipher try #career-advice, but I would say make your videos for a wider audience; your channel can be one of the things in your portfolio.
:incoming_envelope: :ok_hand: applied mute to @native tide until 2020-09-23 21:57 (9 minutes and 59 seconds) (reason: duplicates rule: sent 4 duplicated messages in 10s).
@vestal hound yeah but I think i got it
hey guys, HEROKU QUESTION: I have a problem with updating the requirements.txt file when deploying, it simply doesn't update from local
hey guys, HEROKU QUESTION: I have a problem with updating the requirements.txt file when deploying, it simply doesn't update from local
@warm nymph are you sure you modified the right file?
i'll send a few screenshots to show what I mean, btw i'm new to heroku, so please bare with me
i'll send a few screenshots to show what I mean, btw i'm new to heroku, so please bare with me
@warm nymph please send stuff as text
it seems to be more of a hassle for the channel, since it has a long output
are you sure?
showing requirements.txt on local, and on the server
yeah but it doesn't for some reason, idk. the requirements,txt file doesn't update
yes
ah, okay
i connected github to heroku and tried again, heroku still doesn't update, even though github did
how do you know what's on the server?
heroku run "cat requirements.txt"
I checked github commits to verify requirements.txt updated as I intended
i just checked and the build didn't succeed, i'll try to fix it and come back if I need any help
it did succeed in previous times though, it didn't because I changed the python version
i just checked and the build didn't succeed, i'll try to fix it and come back if I need any help
@warm nymph yup, that must be why
it would be a truly horrific thing if your code updated but requirements.txt didn't 😉
! Requested runtime (Python 3.6.12) is not available for this stack (heroku-18).
although it does say so here - https://github.com/cloudfoundry/python-buildpack/releases
i only updated the requrements.txt file to fix the problem
ah, I see...
hm
it's generally better to use newer versions unless you have a specific reason
but yeah, anyway, I think you found the answer to your original problem
I probably need to give runtime.txt as 3.8.x to resolve it maybe'
it says it's supported though, which is kinda odd
! Requested runtime (Python 3.6.12) is not available for this stack (heroku-18).
although it does say so here - https://github.com/cloudfoundry/python-buildpack/releases
@warm nymph
thank you for the help 🙂
beats me
Django or flask? 👀
about the 3.6 thing
Django or flask? 👀
@native tide depends on nature of project and your level of experience
Django or flask? 👀
@native tide flask
I actually started with django not too long ago and I really like it
it depends on what you want to do, I just want to create a simple api
if you have to do anything with a database
Django starts to look more attractive
until you are experienced enough with SQLAlchemy or something similar
to make it worth it
it's a small app, i wanna start with something simple to minimize variables
is a rest api with authentication a thing? I don't want everyone being able to access the api, just authenticated users
I heard people say django is difficult, and it really isn’t.
I knew nothing about it and just by building one project I learned a lot
is a rest api with authentication a thing? I don't want everyone being able to access the api, just authenticated users
@warm nymph yes
wait
what do you mean by "a thing"
it's a small app, i wanna start with something simple to minimize variables
@warm nymph IMO Django is actually simpler
because it's opinionated
I fell in love with it lol ^^
you may be right idk, I just have a bad experience from when I was a noob
@warm nymph IMO Django is actually simpler
@vestal hound
what do you mean by "a thing"
@vestal hound I haven't looked it up yet, I was just wondering if it's not too complicated to implement
it doesn't sound too hard for a simple application, checking http headers and such right ?
for Flask?
yes\
and for django?
okay so the thing about Django is
yes, it is pretty complex
so it's best (IMO) for people who are experienced with Python
but new to web dev
Flask is probably easier for people who are new to both
I see
what about light weight api, why django over flask? opinionated? how is it opinionated in that regard
what about light weight api, why django over flask? opinionated? how is it opinionated in that regard
@warm nymph well, it has its own ORM
and templating system
and authentication methods
it handles some aspects of security
it has its own method of testing
etc. etc. etc.
in short, the answer to many questions like "how do I do <x> in Django" is "Django's way"
on the other hand, for Flask it's more like "find another library to do it"
what about light weight api, why django over flask? opinionated? how is it opinionated in that regard
@warm nymph what is "lightweight" to you?
requests/s?
I see.
wouldn't flask teach you more maybe in that regard? different libraries, probably more elaborate syntax? but a larger headache of course
wouldn't flask teach you more maybe in that regard? different libraries, probably more elaborate syntax? but a larger headache of course
@warm nymph depends on what you wanna learn...?
Flask does more or less one thing: routing URLs to functions
Django imposes its own structure
thank you for the input, good night 🙂
picking_sites/?q=y
{% url 'picking_sites' q as picking_sites %}
{% url 'picking_sites' as picking_sites %}
Heya, I was wondering how I can use the url picking_sites with a query as variable in django template
hi guys! im new in Django. i got problem when i use postgresql. (createdb: could not connect to database template1: FATAL: Peer authentication failed for user "username"
). i tried to change the pg_hba.conf file and restarted but it didnt work. can you guys help me(i'm using Debian).Thanks! Have a good day!
I followed these step
why does a website need a backend, why not just talk directly to the database from the front end?
One reason is security
If the database was accessible via the front end directly, then users could perform arbitrary queries.
Any any client-side checks you put in place to prevent that could easily be patched out and circumvented.
if only all that backend did was communicating with the database
our jobs would be much more easier

which is best ui framework for react?
is that a python question?
@thorn parcel this channel isn't only for python
well then
see sidebar for more info
This channel IS the frontend channel
Help with web technologies such as Flask, Django, HTML, CSS, and JS.
yeah
I mean if you wanna ask about, say, how to fix a Redux problem
maybe it would be off-topic
but in general frontend stuff goes here IME?
ELI5 time:
What is Gunicorn?
wsgi server
WSGI is the foundation of most Python web frameworks, but there's a good chance you've never had to interact with it directly. In this talk we'll explore why it exists, how it works, and what the heck it's doing in your stack.
A great web framework abstracts away all the low-...
watch this, sums it up real nice
Thank you 🙂
https://discordapp.com/channels/267624335836053506/366673702533988363/758277433077792810
Something like
{
"var1":"value1",
"var2":"value2"
}
and to make get request return
requestdata.var1
>>> value1
requestdata.var2
>>> value2
Does anyone know how to pass data from a React form to django?
Does anyone know how to pass data from a React form to django?
@native tide POST
to your Django route
Thanks. So they'll send a POST request to my route... and I'll validate through their info. Is it possible to send a request from Django -> React for this?
??
why would you send a request the other way
that would mean that the user is the server
.topic
Django lol
Whats the best possible way to allow users to create their own "custom address"
e.g. gofven leads to my profile page
putting it into the user class would generate heaps of null columns, not ideal for something that will be queried for search results
@bright spindle can you elaborate more
@bright spindle look into a python package. it's called faker. Might be what you want
faker is pretty extensive and can be used fpr other stuff
but yeah you could create your own and or actually work on what you need to
no i mean i would want to know whats the best way to make a model for custom user address
within my domain
your domain name, you can prepend
e.g. people can set their address to, baconlover
then they can go to example.com/users/baconlover
and for people who havent set they will access it trough their userid
something like url = my_domain + fake.url()
eg. users/id/8592
nooooouu this is django
its not about the domain
its about models
i can make the domain
what would be the most ideal way to store it
cus if i put it in the usermodel it would generate ALOT of NULL values
maybe JSONField is what you need?
make a new table called aliases or something and you only need 2 columns
or use postgresql ArrayFields
or just add a column to your existing table for a username
JSONField would be pathetic,
aliases maybe
if i do an onetoonefield for the userclass and link it to the alias
that would work
yeah whatever works, works
well not quite
i mean yes
but u need performance
searching trough jsonfields and arrayfields is slow
making a dedicated table for it is alot quicker
and i dont need many NULL values
yeah that sounds like a better idea
perhaps I am missing something
but I don't really see
what the problem is
have a view bound to that route with a parameter
@native tide you can share it in here as well 😄
I have created a registration page, and I need a unique id in it
This is the requirement -
Unique Id :- it would be a six digit alpha numeric combination unique if it isn’t entered by the
user it would be auto generated from backend.
is this the right area for django related stuff?
could somebody explain that, please?
sorry, i am wrong. the urls.py in the subdirectory was created by a tutorial
I'm not really sure someone commented that I should look into this chat
Yes this is related to Django and I'm really confused in the unique id part
2 seperate topics
Sorry?
my posting is independant from yours
I don't know if this is right channel to put this on but im trying to login to heroku in the VS code terminal and I get this error 'heroku : The term 'heroku' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1'
and i have check that the path is right
Whats the best possible way to allow users to create their own "custom address"
@bright spindle What framework? in Django, I would make it aSlugField... verify that it is unique on save.
If users can have zero or one addresses, make it part of the user model and nullable.
If you can have more, make it with a foreign key to user.
What's the standard design choice for displaying a success or an error response to the user from an api call on JS? Ideally the UI displays some sort of a loading screen or a loading message until receiving the response.
I'm having issues with Django's RegexValidator... Do you guys know why this won't work?
username = models.CharField(max_length=20, unique=True, validators=[RegexValidator(regex="^[a-zA-Z0-9]+([._]?[""a-zA-Z0-9]+)*$")])
I can still create users with forbidden characters...
did you makemigrations?
everything looks correct
did you check if you can input a string thats actually correct?
Yes... It adds users regardless of their name.
I'll send over the Django view, and the html.
def register(request):
if request.method == "POST": # If the form is submitted, giving a POST request but there is a validation error...
form = registerform(request.POST) # The form will re-appear, with the info from POST request shown in fields.
if form.is_valid():
username = form.cleaned_data.get("username")
email = form.cleaned_data.get("email")
password = form.cleaned_data.get("password")
confirmed_password = form.cleaned_data.get("confirm_password")
if models.User.objects.filter(username=username).exists() is True:
messages.warning(request, "Username has already been taken")
elif models.User.objects.filter(email=email).exists() is True:
messages.warning(request, "Email already used to sign up.")
else:
user = models.User(username=username, email=email, hashed_password=confirmed_password)
user.save()
messages.success(request, "Your account has been created. Yay!")
return redirect('/register')
else:
form = registerform()
return render(request, 'users/register.html', {"form": form})
Well the HTML is just the form.
Btw, am I correct in saying if the Username goes against the RegexValidator - it will create a ValidationError?
Do you know if I can view the message of the ValidationError? That will help me troubleshoot it.
Btw, am I correct in saying if the Username goes against the RegexValidator - it will create a ValidationError?
@native tide https://docs.djangoproject.com/en/3.1/ref/validators/#writing-validators
Do you know if I can view the message of the ValidationError? That will help me troubleshoot it.
@native tide{{ form.username.errors }}
Thanks @versed python , for the first message, do you think I should just write my own Regex validator in that case?
I have never used inbuilt validators myself, but thats just because I never needed them. Custom validators have always worked for me. If you wanna write them, see link above.
{{ form.username.errors }} isn't showing me anything, so I don't think the validator is working. So yeah, I think I will write my own validator. Thanks @versed python 🙂
@native tide
{{ form.username.errors }}
@versed python This will generate alist, so you can loop using{% for error in form.username.errors %}
{{ form.username.errors }}isn't showing me anything, so I don't think the validator is working. So yeah, I think I will write my own validator. Thanks @versed python 🙂
@native tide I am not very sure about this, you might want to check how to output form errors in Django template lang.
Looks like I was incorrect https://stackoverflow.com/a/14647770/11667450 @native tide
Yeah... no errors being shown. Ok - I'll go ahead in trying to make my own regex validator.
I'll make a regex string such as "*$ ^%#" and loop over every character in their username, if any characters are in the regex string I'll raise a ValidationError and an error message
We'll see how it goes, thank you very much for your help 🙂
def CustomRegexValidator(string):
regex = ["$ @!#%^&*()-+[]{}\/:;',.|`~£"]
for characters in string:
if characters in regex:
raise ValidationError(message="Your username contains forbidden characters")
break
This is my validator
but it still doesn't work.
@quick cargo but wouldn't my custom validator still work for anything which contained forbidden characters such as $, etc?
look through the link i sent
or actually why are you even calling this a regex?
its just a string with what i assume is the characters that arnt allowed?
Yeah, I see. I can implement that but I don't think it's an issue with the actual validator but its implementation
Maybe it's not a regex. It checks if a passed string has fordbidden characters
i mean atm you're doing if char in list not if char in string
Ok I changed it, to a string.
you need to remove that [] wrapping the string
guys is there anyone who knows hoiw to uplaod images in flask webapp
Yeah that's what I did. I actually made a really really stupid and blatant mistake, which I won't talk about 🙂 Thank you for the help
anybody who has experience with Flask deployments behind nginx, and swagger, your advice here would be appreciated https://github.com/apryor6/flask_accepts/issues/91
@fickle fox create a POST endpoint that extracts the image file using flask.request.files, make a curl like curl localhost:8080/upload' -F 'file=@images_directory/pic.png'
With flask can I just use get for now as a base and then switch to post when I know a little more?
you can theoretically make a GET with a json body payload, so yes
note that they are primarily words for your (a human's) benefit, you can again theoretically (dont do this.) make an API entirely out of GET
but a POST has server semantics behind it that you'd be best off understanding first, the labels are only scary until you learn why they're there
hello i have a question
is there a counter code to count no of times a page has been reloaded
like it should end the cookies count if the url is changed and start over again
You could easily create a table for it
Flask newbie here, how soon should I go from doing things “locally” to working on an actual web page
Also is there a big process to go from one to the other?
As soon as you can. The more you try, the more you learn.
Should testing continue to be done locally? Can updating your flask python go directly to a webpage?
ok i have past a cookies test case, i can clear the first 4 but las one throws error
because the response is now "you visited site 4 times" instead of 1
here's app code
what should i do??
it's a simple site visit counter
I suppose I meant develop rather than test. I’m creating a webpage that someone else will using to create a database, currently using the local address to see my results/progress. That should be done on an actual webpage instead of local? Can I do my development locally until I am ready to push something periodically I n increments? @versed python
Yeah, version control is a thing. Idk if you know about it? git, github?
@plucky tapir Most things can be done locally. There is some stuff that can only be done on the server itself.
You should keep your server version synced with your local copy as much as possible.
What I mean by that is don't change your server files unless necessary--always just upload from local to change server files.
Hey does anyone know much about cookies with Django? I'm specifically wondering if all I use are the basic session cookies if I need to put a cookie notice on my website to comply with EU regulations.
@versed python just going to start using it, but I have the idea of what you’re saying regarding there being branches used for stages.
But sounds good. I was wondering if there was like a big difference from developing locally in comparison to a webpage, but it seems like you can just push your code directly to the server and it should be the same
branches are not used for stages @plucky tapir
am disappointed
You would create a branch if you are "forking" your project @plucky tapir
yep you should keep your actual working code on master branch and develop on development branch
that way even if you fuck up development branch, you still have a working master
Hm, I thought the point of git is that if you fuck up you just return to a previous revision, not needing a wholly separate branch for development.
i prefer that method since I don't have to deal with git resets and all, since they mess up commit history sometimes, and cause conflicts too
i just set the counter to 0 for setcookie
but your method is valid too yeah
Speaking of cookies, I need to figure out what to do about a cookie notice or if it's even necessary.
Does anyone know how critical it is to have a cookie notice when all you're using cookies for is managing sessions?
@native tide good job
So I don't get fined.
idk .... am not making anything that big to care
Well, you never know. Someone could try to fuck with you.
And if you're operating outside of the law, you're easy to fuck with.
ordinary coders never get in trouble, it's only for big corporations
But if the law applies to small websites, too, you should really try to be compliant.
ok
Someone could have an axe to grind, so giving them the ability to bury that axe in you is not a good idea.
whats javascript used for?
Any way to validate POST requests with flask?
I mean, my frontend is in react so it's fine but if someone sends a request using postman or the like, how do I validate that it doesn't have extra fields, wrong inputs etc?
from what I saw, flask_wtf and WTForms only work if you put {{ on your html }}
