#web-development
2 messages · Page 89 of 1
@opal fulcrum You should probably know a bit of HTML before jumping into Django, but you can learn both at the same time.
there are only 2 possibilities:
- your token is broken (meaning the source is bad)
- the library is buggy (doubt it)
@opal fulcrum If you want to build a nice website, you should know HTML, CSS, JS, and backend language and framework like Python/Django.
html is very easy to learn but as the other guy said difficult to master
@topaz widget ohh so it's a long learning curve i see
Yes, most definitely.
so you can easily learn django, and html parallelly
why did you say backend language and framework like django ... i thought django is backend
is there is something different between a framework and backend o.O
@topaz widget ohh so it's a long learning curve i see
@opal fulcrum just wait till you hear about django rest framework then
that backend handles logic for you
@versed python lol I haven't been masochistic enough to jump into that yet
DRF is pretty nice
I'm using it right now
I gotta say
building a RESTful API is hard
I started getting into it but backed off.
frontend is basically used to make pretty looking stuff
it's quite a different way of thinking
for the time being.
it's quite a different way of thinking
@vestal hound yeh it is
it's quite a different way of thinking
@vestal hound Yeah, exactly.
and recently I've been restructuring a lot of my API to be RESTful
the uniformity is nice
i know this is a weird question but how long as average can learn all django - HTML - CSS- js
but some operations are very difficult to express
and then I just discovered that the market is slowly shifting towards Graphql instead of Restapi
@vestal hound I was going to make a single-page application with DRF and Vue, but it was just too much when I tried to jump into it.
yeah, that's basically what I'm doing now for my startup
planning to launch in a couple of months
@vestal hound I was going to make a single-page application with DRF and Vue, but it was just too much when I tried to jump into it.
@topaz widget this is basically what I am doing rn
Can you say what the business model is?
understand if you want to keep downlow, though.
Can you say what the business model is?
@topaz widget what do you mean?
@versed python Then you're a little ahead of me on that front.
and then I just discovered that the market is slowly shifting towards Graphql instead of Restapi
@versed python GraphQL shares similarities with real REST
What is the business of your startup? (Understand if you don't want to say here)
i know this is a weird question but how long as average can learn all django - HTML - CSS- js
@opal fulcrum I'd say around 8 months brought me to where I am,since I started as an absolute beginner
@versed python you learned all that in 8 months wow
when you say "business model" I was thinking you meant like marketing strategy and stuff
i thought that would take me idk 3 years or something
3 years is a long time
no 3 years is a lot
@vestal hound No I meant what the business is about.
so an average 1 year is very good to learn all that
yeah but just the absolute basics of web development
private tutors are very common
so like an application to streamline the interaction between students and tutors
@opal fulcrum you will then have to dive into a frontend framework
Gotcha
incidentally, IMO
@versed python What front-end framework are you using?
the big frameworks are better
vuejs
so your 8 month was only for backend ?
like I'm using Angular/Django (with DRF) and it feels like if I had done React/Flask instead
Yeah, I like Vue best from what I've seen so far.
@opal fulcrum and very little frontend yeah
React is way too difficult for my brain to grasp
@vestal hound I heard Angular is kind of showing its age. Have you experienced this?
vue has the gentlest learning curve
You can definitely ease into Vue
@vestal hound I heard Angular is kind of showing its age. Have you experienced this?
@topaz widget I don't have the context or knowledge necessary to give the best answer
especially since it can be used directly in django templates
but I personally find it quite easy to use and I have not encountered any problems on the coding side?
hm ok
however, I must say that I am getting beaten up by the CSS
thanks guys i will be following this Corey guy tutorials for django .. can you recommend me a way to learn HTML as well ?
mostly because everything I've been learning is ad-hoc
though that's not exactly an Angular problem
@opal fulcrum Interneting is Hard is a very good website
I really like Observables
I've used Vue instead of Django tempaltes in places.
I've used Vue instead of Django tempaltes in places.
@topaz widget as of now my frontend and backed are completely separated, I'm not even using vanilla django anymore. switched to drf
ah
yeah, vanilla Django is the one that is showing its age, I think
So you're using Vuex and VueRouter then?
idk, django is pretty good to me
So you're using Vuex and VueRouter then?
@topaz widget i use a framework called nuxt built on top of vue, and they have nuxt router instead of vie router. so yeah that and vuex pretty much
I hear it's not as good as SQLAlchemy, but so far it does almost everything I need
there are some intermediate SQL things that I can't do in Django
but they're not hard necessities right now
Why nuxt instead of VueRouter?
yeah i dont even know sql that well, I still didn't find any need to learn it
Why nuxt instead of VueRouter?
@topaz widget look at nuxtjs.org this stuff is better explained there
Okay. How about authentication? How do you handle that?
Yeah, seemed like that was the hardest part.
I actually thought Vuex would have played a role in maintaining sessions. Is that the case or no? @versed python
lol
You might have some problems with that later tbh.
nah this is how I learn, just stumble through until I suddenly understand everything one day
I just mean not knowing how something works means you may not be using it quite right.
I do the same thing, though. Not judging.
well this strategy has worked out for me, so I'll be sticking with it
but I get what you mean though
Just a comment, not really a criticism.
yeah i understand
Hey its me again, I have 2 models customer and company. each company and customer has a onetoone realationship with User.
I am trying to do a profile pages for both. is there away for me to do @login_required(are u a customer or company)
kind of, yes.
each model have this is_customer = models.BooleanField(default=True)
but login has to do with the user model, not the other model.
You need to modify the user model if you want to set the user to a company or a customer.
and create a field for whether it's a company or a customer.
ok gotcha ahhhhh I just got this to work now I have to play with model again
Thanks man
Yeah, you need to subclass the default user model.
no problem
There are other ways to do it, but that's probably the best way.
Hey its me again, I have 2 models customer and company. each company and customer has a onetoone realationship with User.
I am trying to do a profile pages for both. is there away for me to do
@login_required(are u a customer or company)
@zinc hill what do you want to happen if the user is logged in but neither a customer nor a company?
lol i was thinking the same thing for admins
hmm I dont think they can logged in as that
Well, an admin will probably need to log in and be neither.
You can still accomplish that with subclassing.
maybe i will make something for admin as well
You can just set blank=True for the customer/company field, which will let it be blank.
then you just need to program the logic for that condition.
I assume he(?) wants a different page to display depending on whether the user is a company or a customer.
yeah
no, I mean
and im very very new
why a one to one relationship?
okay, how about you talk about what you wanna do
from a wider perspective?
Because he was using it wrong.
ok so the project is basically like ubereat
?
you have company and customer and driver
oh
so you have different types of users
yeah
Uber Eats
how about an integer field with user type?
yeah, but that's subclassing the user, right?
nope
just a field
alternatively
Django has groups built in
you can use those too
hm
yeah, but that's subclassing the user, right?
@topaz widget unless you mean the built in class
then yes
i was messing around with those and it got complicating
this is why i was using the 1to1
@vestal hound I think we mean the same thing. Subclassing the default user model.
or extending, yes.
yeah
I did that from the start so it didn’t occur to me
i was messing around with those and it got complicating
@zinc hill is this your first Python project?
it might be good for you to do some research on SQL and how it models relationships between real-world objects
you don’t need to know how to write complicated queries, but you should at least understand how one would model common relationships
because otherwise you’ll be fighting the ORM and probably losing
fighting the ORM and probably losing
XD
ok i will into that stuff
@zinc hill btw is English your first language?
nope
okay just curious
Guys isn't there an easy way of sending data to my website with CURL?
Like could I create a file like .rest?
And use that to post/get/pull/delete the info specified?
Or should I use Postman?
Yes, you can use curl, though you might find it a bit cumbersome for anything but the simplest of requests
I usually find cURL to be sufficient, but some of my friends use https://insomnia.rest/
yo anyone up?
Not that related to web-development but it is hindering a project, can anyone ping andromeda.miragespace.net?
There's a DNS prop issue. I can't fix that, but I'd like to change my name server to one that reaches it
actually, jk, I checked DNSmap again and it's fine again, but I can't reach it on some machines still...
Would anyone know the reason why?
I usually find cURL to be sufficient, but some of my friends use https://insomnia.rest/
@latent vessel Thanks I'll try that out!
yep
any web developer can help me design my website plz
@snow estuary yep dm me
Hii anyone can u test my site made php change and added advertisements
Foodymania will provide you the best recipes in the easiest ways possible we will provide you some amazing food and kitchen tips.
for index, _ in enumerate(range(100), 1):
with tempfile.NamedTemporaryFile('rb', suffix='.jpg') as file:
PostImage.objects.create(
post=random.choice(posts_list),
image=ImageFile(file) # from django.core.files.images import ImageFile
)
print('Image file created')
This is a django management command snippet that I am using to generate some data for my database
everything works as expected- (empty) image is being created, and being uploaded too.
But since tempfile.NamedTemporaryFile() opens a file /tmp/temporaryname.jpg, the images are uploaded to my webserver with the name tmp/temporaryname.jpg and hence an extra useless directory called tmp is being created in my MEDIA_ROOT
How can I prevent this?
# what I want
media/
- images/
- temporaryname.jpg
# what is being created
media/
- images/
- tmp/
- temporaryname.jpg
!d tempfile.NamedTemporaryFile
tempfile.NamedTemporaryFile(mode='w+b', buffering=-1, encoding=None, newline=None, suffix=None, prefix=None, dir=None, delete=True, *, errors=None)```
This function operates exactly as [`TemporaryFile()`](#tempfile.TemporaryFile "tempfile.TemporaryFile") does, except that the file is guaranteed to have a visible name in the file system (on Unix, the directory entry is not unlinked). That name can be retrieved from the `name` attribute of the returned file-like object. Whether the name can be used to open the file a second time, while the named temporary file is still open, varies across platforms (it can be so used on Unix; it cannot on Windows NT or later). If *delete* is true (the default), the file is deleted as soon as it is closed. The returned object is always a file-like object whose `file` attribute is the underlying true file object. This file-like object can be used in a [`with`](../reference/compound_stmts.html#with) statement, just like a normal file.
Raises an [auditing event](sys.html#auditing) `tempfile.mkstemp` with argument `fullpath`.
Changed in version 3.8: Added *errors* parameter.
What if you give an empty string to dir?
# what I want
media/
- images/
- temporaryname.jpg
# what is being created
media/
- images/
- app/ <----- instead of tmp i get app
- temporaryname.jpg
@jagged lark
I think that’s how django save files, but i might be wrong
I can access my application via flask run but not via uwsgi
[uwsgi]
wsgi-file = wsgi.py
#wsgi-file = run.py
callable = app
strict = true
socket = :5000
http = :8090
stats = :9191
master = true
processes = 4
threads = 2
chmod-socket = 660
vacuum = true
die-on-term = true
enable-threads = true
need-app = true
reload-mercy = 5
worker-reload-mercy = 5
> uwsgi ./wsgi.ini
[uWSGI] getting INI configuration from ./wsgi.ini
*** Starting uWSGI 2.0.18 (64bit) on [Tue Sep 15 17:36:10 2020] ***
compiled with version: 10.1.0 on 14 September 2020 07:20:01
os: Linux-5.4.52-1-MANJARO #1 SMP PREEMPT Thu Jul 16 16:07:11 UTC 2020
nodename: foo-manjaro
machine: x86_64
clock source: unix
pcre jit disabled
detected number of CPU cores: 8
current working directory: /home/foo/ticket_dashboard
detected binary path: /home/foo/.local/share/virtualenvs/ticket_dashboard-oWsjh6kM/bin/uwsgi
your processes number limit is 63584
your memory page size is 4096 bytes
detected max file descriptor number: 1024
lock engine: pthread robust mutexes
thunder lock: disabled (you can enable it with --thunder-lock)
*** RRDtool library available at 0x5615881bb590 ***
uwsgi socket 0 bound to TCP address :5000 fd 3
Python version: 3.8.3 (default, May 17 2020, 18:15:42) [GCC 10.1.0]
Python main interpreter initialized at 0x5615881d0550
python threads support enabled
your server socket listen backlog is limited to 100 connections
your mercy for graceful operations on workers is 5 seconds
mapped 416880 bytes (407 KB) for 8 cores
WSGI app 0 (mountpoint='') ready in 0 seconds on interpreter 0x5615881d0550 pid: 129218 (default app)
*** uWSGI is running in multiple interpreter mode ***
spawned uWSGI master process (pid: 129218)
spawned uWSGI worker 1 (pid: 129222, cores: 2)
spawned uWSGI worker 2 (pid: 129223, cores: 2)
spawned uWSGI worker 3 (pid: 129224, cores: 2)
spawned uWSGI worker 4 (pid: 129225, cores: 2)
*** Stats server enabled on :9191 fd: 15 ***
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(255), nullable=False)
email = db.Column(db.String(255), nullable=False)
password = db.Column(db.String(255), nullable=False)
class Profile(db.Model):
__tablename__ = 'profiles'
id = db.Column(db.Integer, primary_key=True)
profile_description = db.Column(db.String(500), nullable=True)
feedback_score = db.Column(db.String(50), nullable=True)
class Image(db.Model):
__tablename__ = 'images'
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.String(100), nullable=False)
product_id = db.Column(db.String(200), nullable=True)
profile_img = db.Column(db.String(200), nullable=True)
product_img_original_name = db.Column(db.String(100), nullable=False)
product_img = db.Column(db.String(200), nullable=True)
Since the user can create a product, I thought it was best to store all the images in one table, including the profile image. Or should I move profile image into the Profile table? What do you think?
of any other way I should setup these tables?
Ufff
Maybe make a an Abstract Image model, and derive ProfilePicture, ProductImage, etc. from it?
never heard of abstract model, I will look it up
I think that’s how django save files, but i might be wrong
@jagged lark so there's nothing I can do?
I’m not sure, but I think
@lethal orbit can you give a quick explanation as to what Abstract is? I don't seem to understand it
@past cipher first two questions is why you use __tablename__ and why you add an id .... Using the defaults should be fine in 99% of cases (as Django does give pk and id properties by default).
An Abstract model is essentially a mixin that lets you reuse code.
because I'm using Flask
OH!
and class name shouldn't be pural
where as table name should
so thats why i use tablename
yep
I just don't understand Abstract, I can't find a solid tutorial/walkthrough online
I havent worked with SQLAlchemy.... but normally, you would declare an Image mixin, with information about the file itself.
but why would I use abstract, when I am going to create a table called Images anyway
Then derive models from that.
class Image(db.Model):
__tablename__ = 'images'
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.String(100), nullable=False)
product_id = db.Column(db.String(200), nullable=True)
profile_img = db.Column(db.String(200), nullable=True)
product_img_original_name = db.Column(db.String(100), nullable=False)
product_img = db.Column(db.String(200), nullable=True)
Single-responsibility principle.
Why do you have a profile_img and product_img together?
How is a product tied to a user?
class Image(db.Model):
img = db.Column(db.String(200), nullable=False)
class ProfileImage(Image):
# inherits the `img` field from the Image class
user_id = db.Column(db.String(100), nullable=False)
class ProductImage(Image):
# also inheerits `img`
product_id = db.Column(db.String(200), False)
Then you can add as many product images as you want... and your models are independent.
Not sure how you would make an abstract model in SQLAlchemy though, as I don't work with it.
But having the product and profile images in the same model is a code smell.
but from your code above, isn't that just creating multiple tables
I'm new to SQL. I thought having all images in one table was best
Nah...
It just adds extra complexity, tbh.
You definitely shouldn't mix them in the same row.
You could have a img_type column in your table, so you can have an image row that is a profile_image, and another that is a product_image...
But mixins are the cleanest way.
Also, more tables means smaller tables, so if you need to query all profile pictures, you can do it more efficiently.
select * from profile_images; <-- selects from a smaller set
select * from images where profile_img != null; <-- selects a larger set, and has to do an extra filtering operation.
I'm new to SQL. I thought having all images in one table was best
@past cipher if you definitely have one image of each kind per user, then yes.
but I'm guessing that each user definitely has one profile image?
if so, that should probably be on the main user model.
however, each product has its own image, and multiple products can belong to one user, right?
that's called a one-to-many relationship
and suggests that products should be in their own table
one row per product
and they can be linked back to their owning user with a user_id column
You should also allow multiple images per product, IMO
How could I pass a value from the class based create view (overloaded) __init__ to the form __init__ ?
Right now my classbased create view is creating the form with form_class = MyCustomForm
You should also allow multiple images per product, IMO
@lethal orbit that would depend on their business logic
but yes, that's definitely a possibility
and would require a third table
I'm setting up flask uwsgi and nginx and I'm getting an error ValueError: handshake not done yet
Anyone know how to resolve this?
Hey hey
trying to use bs4... any idea what is causing this error?
raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 403: Forbidden```
this is my code
```py
from bs4 import BeautifulSoup
import urllib.parse, urllib.request, urllib.error
import ssl
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
print("Give me link...")
link = input(": ")
handle = urllib.request.urlopen(link, context=ctx).read()
soup = BeautifulSoup(handle, "html.parser")
tags = soup("a")
alltags = [tag for tag in tags]
alltags = "\n".join(alltags[:25])
with open("taglist.txt", "w") as f:
f.write(alltags)
@burnt night you're not allowed to access whatever youre accessing
oh damn...
HTTP Error 403: Forbidden You're not allowed to open the URL. Maybe you need credentials, maybe you need to add a user-agent header, etc.
Hard to say why without knowing the URL.
can someone explain: if usually people store static content on a server, how does one program their website around that
obviously I am not developing/writing code on the cloud?
Hi! I want to use bulma in my Django application. But I don't know how. For example if I used bootstrap all I need to do was assign a variable in settings for crispy forms and I'm done. But I don't know how to do it with bulma. There are packages out there but there are either poorly documented or idk if I should use that one. Can someone help?
Pls ping back when ur answering
Yes I know
I checked that but i don't think that supports crispy forms?
😔
they are two independent packages
Then what should I use for my forms?
Django application to add 'django-crispy-forms' layout objects for Bulma.io - python-discord/django-crispy-bulma
Oh I haven't seen that
It is archived though 
This project is an early work in progress. You should not use this package yet, as it is poorly documented and is missing many important features. We'll remove this header when it's ready to use.
😔
soo
static content
and deploying to server
does one need to code on the server to make this work? what is best practices
Can you elaborate on your question
so most people have told me that serving content like pdfs is best done by allocating space on your server
and placing the content there
and in your code, pointing to that location which contains the content
what is confusing me, is how one is supposed to build out their website
and simultaneously have it point to the media content
since they are developing locally in their IDE and only then pushing it to cloud after.
like I need to build out some pages that contain PDFs
how can i get all html from a page with bs4?
should be in the docs, it's definitely a function of bs4
because you can do that with curl requests
I'm reading thru the docs right now...
i see that the soup object itself has everything, but i also get the css and the script
im not certain sir, good luck
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u202a' in position 35877: character maps to <undefined>```
how can I fix this?
i tried .read().decode()
and just regular .read()
handle = urllib.request.urlopen(link, context=ctx).read().decode()
soup = BeautifulSoup(handle, "html.parser")
with open("something.txt", "w") as f:
f.write(f"{handle}")
print("done")```
@burnt night This can happen sometimes if youre writing a website which does not have utf-8 characters.
maybe the site youre using is in a different language? or uses emojis?
I don't have any experience working with bs4, but that was the first thing that cam to mind
why don't you try and see with some other website? maybe the problem is just with this one?
i did
i tried it with youtube and google sites, and i got the same error...
but i wanted it for a specifc site so that is an L
Well if it didn't work for youtube etc, there's something you must be doing wrong
try and see where it is wrong
maybe follow the tutorial you followed again?
So I am getting data from an api and trying to export it to excel, but my to_excel function only uses the result of my most recent get_page function...
I might have to hit someone up on fiverr for help on this, but I thought that I would try here out first. I have problem with my function. I want to be able to use the result of my first fuction in my new function multiple times, but I keep overwriting the file I want to create. Does this sound like a difficult fix?
import json
import pandas as pd
from pandas.io.json import json_normalize
def get_page(url):
global response
payload = {}
headers = {
'Authorization': 'Bearer #####
}
response = requests.request("GET", url, headers=headers, data = payload)
return response.text.encode('utf8')
(get_page("https://us.api.knowbe4.com/v1/groups"))
(get_page("https://us.api.knowbe4.com/v1/users"))
def to_excel(responseName):
responseName = response.text.encode('utf8')
dataName = json.loads(responseName)
data2 = json_normalize(dataName)
data2.to_csv('Project.csv', mode='a')
return responseName
to_excel(response.text.encode('utf8'))```
Hi, if your function only returns last page maybe you need to implement for loop and iterate? and save each step?
@maiden kraken Is this comment directed to my code?
@last sable yes, but I am beginner in python so you dont have to listen to me 🙂
(hint: listen to @maiden kraken)
It sounds like you know more than me!
of course you have to worry about overwriting your file, ideally you want to 'append' not save over
some time ago I was using openpyxl to mess with excel, maybe now there is a better option
So are you saying to put the function in a for loop?
So im trying to make my bot add a reaction to the message the bot sends but i can only ever get it to send emojis by themselves, not as reactions
@true python umm its web development channel
go to #discord-bots
well... I would first debug this, try what your function returns. If it returns specific page (last) and you have multiple pages then you need to iterate through it
It returns the most recent API call (i.e. get_data())
something is strange here, you write you want to use your first function inside another, but you are not using it at all?
I am using the response object created by the most recent function
you maybe meant this responseName = getpage(url)?
sorry I think that's beyond my skills right now
hey guys, which framework would you advise to build a graphql backend ?
I thought of django but i saw that fastapi also support it
Django with ariadne work great, @strange briar
Can't speak for fastapi, as I never tried it.
im tyring to follow this
however
im trying to serve a pdf
and i place it in static/pdf
i tried to do a
{{ url_for('static', filename='pdf/filename.pdf') }} inside of the html
ive tried every combination I can think of
and it's either trying to print out the filepath
or just not serving anything
Does anyone know how to use ionicons in a flask application?
I have a template that uses ionicons but i dont know how to install them properly. I added the ionicons.js and the ionicons.css but it does not work like it should
any suggestions?
@swift sky try to use the send_file() method: https://pythonprogramming.net/flask-send-file-tutorial/
Python Programming tutorials from beginner to advanced on a massive variety of topics. All video and text tutorials are free.
it comes with flask, you just need to import it
how to use the gmail's api plz ?
i have early finish that https://developers.google.com/gmail/api/quickstart/python
how to use the gmail's api plz ?
@light flame are you using django?
Sorry can't help you then
and what is django ?
The web framework for perfectionists with deadlines.👀
O.K
Flask is the easiest to start with
I think they just need to commuinicate with gmail api, they aren't looking for any integration into a webapp
@light flame I cannot explain it better, you have docs on linked page. You need to authenticate to gmail and also you have to give access to less secure apps
Does webscraping count as webdev or should I take my question elsewhere? Bs4
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
any web dev can help me design my html pages plz
Ok I'm getting this error when I'm trying to send an email through Django -
SMTPAuthenticationError at /contact/
(530, b'Invalid username or password')
EMAIL_HOST = 'smtp-relay.sendinblue.com'
EMAIL_HOST_USER = '<tejasm01@gmail.com>'
EMAIL_HOST_PASSWORD = 'xxxxxxxxxxxxxxx'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
Can anyone help
Hey, I'm having some issues with pytest & flask-login
When I run my test, I can login my user, but after I make a request with the test client (client.get('/someurl')), current_user reverts back to the AnonymousUser within the same context manager 🤔
Snipped test in here: https://pastebin.com/Q8tQWVcF
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
I've seen examples that use the test client to post a form in order to login, but I dont think I can do that; my site authenticates against Azure AD with msal; hence forcing a login with flask_login.login_user in the test. I did have an if statement in my authentication route to check the current app config for 'testing' flag which just passed through the auth without hitting msal, but that seems like pretty poor security practice to me
Do i NEED a backend to handle POST/GET requests from forms?
thats the purpose of them
Do i NEED a backend to handle POST/GET requests from forms?
@burnt night well, if you didn't have a backend, where would the requests go?
i just meant if they had to be attached like with flask etc
or if they could be separate
what do you mean "attached"?
okay I'm not sure if this is the best place to ask since it's more deployment than development, but...anyone ever got a 502 from a deployed Django app on GCP, but logs are empty?
not sure if something is wrong with my gcloud because logs are literally showing nothing
hey guys
how would i export an array that I already created in javascript
I tried this
and got this error
I have to go soon
so if you have a solution and I'm not here, just ping me and I will take a look tomorrow
@native tide try export var custom_blacklist; also, how did you take that cool screenshot? is that a theme?
what do you mean "attached"?
@vestal hound i mean like... yk how you'd normally have them in the same folder, and they'll be like in the static folder and use that with flask etc?
i was wondering if it can be done without that...
cause i want to send an email right, was just wondering if i needed to have it set up
Does anyone know if there is a method to paginate items that aren't being stored in a database or are part of a model? Im using this route below to make an api call and then passing the response object directly to my jinja template and creating bootstrap cards for each item in the response object. This data updates daily so I dont want to save it in a db. I have about 100 cards on the page, so it'd be nice to be able to paginate this info into 20 per page. Everything I've seen however seems to show pagination with queried items. My flask route is below
@app.route('/search/member/<member_id>')
def get_member_info(member_id):
"""Retrieve individual government official data on link click"""
res_object = []
offset = 0
while offset <= 60:
res = requests.get(
f"{MEMBER_VOTE_POSITION_API}{member_id}/votes.json?offset={offset}", headers={'X-API-Key': key})
data = res.json()
res_object.append(data)
offset += 20
members_data = res_object
# page = request.args.get(get_page_parameter(), type=int, default=1)
# page = request.args.get('page', 0, type=int)
# page_size = 20
return render_template('search/officials_voting.html',
members_data=members_data,
member_id=member_id
)
And my jinja template where I'm creating the cards for each item.
{% for record in members_data %}
{% for item in record['results'][0]['votes'] %}
<div class="row justify-content-center mt-3">
<div class="card bg-white w-75 my-4">
<div class="card-header font-weight-bold">
<a href="/search/bill/{{item['bill']['bill_id']}}">{{item['bill']['bill_id']}}</a>
</div>
<div class="card-body bg-info">
<h5 class="card-title">Bill info - <span class="text-primary">{{item['bill']['title']}}</span></h5>
<p class="card-text"><strong>Vote description: </strong>{{item['description']}}</p>
<p class="card-text"><strong>Date of vote: </strong>{{item['date']}}</p>
<p class="card-text"><strong>Vote result: </strong>{{item['result']}}</p>
<p class="card-text"><strong>Latest action: </strong>{{item['bill']['latest_action']}}</p>
<p class="card-text"><strong>Voting position: </strong><strong><u>{{item['position']}}</u></strong></p>
</div>
</div>
</div>
{% endfor %}
{% endfor %}
Hi guys, im making the django tutorial part 3 using psql as my database, i just wrote that view, and http://localhost:8000/polls/ shows just a 404, the console show no error, what am i missing here?
Hi I wanted to scrape some Google maps for testing purpose, unlike static pages I believe google map has a wrapper of some sort. Because if I manually type the whole link with page=2 on the address bar it's going to the next page, however when my scrapper pases the link it just reads the same page again. I am using beautiful soup only for this. Please ping me if you know the solution
you are doing nothing wrong @solemn igloo . Did you start the development server? If yes, can you tell us what the output in the terminal was?
@versed python
@solemn igloo show me your polls/urls.py
Hi guys, im making the django tutorial part 3 using psql as my database, i just wrote that view, and http://localhost:8000/polls/ shows just a 404, the console show no error, what am i missing here?
@solemn igloo why did you name ur functionindex?
name the function get which translates to GET request view
and
as_view is a method
it missed the ()
^
@marsh canyon so, just rename the function and ad the "()" to the as_view function.
like that?
aand
ur get method is a method inside the calss
class*
so u need the self param too in the starting
or you can convert ur method into a staticmethod by adding @staticmethod decorator
@solemn igloo
also, using render() will be cleaner imo instead of HttpResponse
I suppose since they are following the official docs, the render method hasn't been introduced uptil tutorial 3
so they will learn it soon enough
oh okay 👍
Quick question
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="post" method="POST">
{° csrf_token %}
{{ form }}
<button type="submit">Submit</button>
</form>
</body>
</html>
this gives me error when I try to submit
"GET /post?name=
not found /post
Why is it still doing get when I declared it as post
hey guys can anyone tell me what are his thoughts about fastapi ?
whose is "his"?
@opaque sail remove post from action
I did
now it is only in method still does not work
[16/Sep/2020 09:09:01] "GET /post?name=Test&email=a%40b.c&category=question&subject=&body=hey HTTP/1.1" 404 2180
Not Found: /post
This is what I get
{% in csrf
changed that as well
still does not work
<body>
<form method='post'>
{% csrf_token %}
{{ form }}
<button type="submit">Submit</button>
</form>
This is my contact from views
def contact(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
email = form.cleaned_data['email']
print(name, email)
form = ContactForm()
return render(request, 'form.html', {'form': form})
class ContactForm(forms.Form):
name = forms.CharField(max_length=40)
email = forms.EmailField(label="E-Mail")
category = forms.ChoiceField(choices=[('question', 'Question'), ('other', 'Other')])
subject = forms.CharField(required=False, max_length=30)
body = forms.CharField(widget=forms.Textarea)
ok imma gonna try holup
but it doesn't affect i think
yeah, it shouldn't make a difference
[16/Sep/2020 09:16:44] "GET /?csrfmiddlewaretoken=n7V4B7sHoQOSCJtjeaCSK6BuUIyWgxxvHPOSbVc9pKbEkR7BbZs6YkrDuW7nvgS4&name=dasd&email=a%40b.c&category=question&subject=asd&body=asd HTTP/1.1" 200 1058
just saying
are you getting csrf error in web page
what is showing in web page after form submission
empty form
now it does not give me error but it does not print name and email in form
it just happened like magic
wtf
this is supposed to be some easy stuff im completely lost in this form thingy jeezus
name and email will print in terminal
will not 🙂
[16/Sep/2020 09:26:32] "POST / HTTP/1.1" 200 1072
[16/Sep/2020 09:26:49] "POST / HTTP/1.1" 200 1072
at least it is a post method
u did write print inside views
yes
Ok
This is simple stuff why is not working is beyond me 😄
may be the changes are not reflected instantly in the web browser it happens to me sometimes
i restarted the server and still no print in terminal
it is a post method tho, so I kinda made it work somehow
Hey guys how can we create a form to input a directory and store it in project media directory.?
anyone that uses django?
A lot of us do, you can just ask your question right away, no need to ask to ask
i ask because nobody answers my questions 🙂 . So, i have this urls.py that contains multple apps with different views. I m trying to call those views like that:
path('', cos.views.home, name="HOME")
but I get an Attribute error that my module has no views.
create a view
create a function inside it
i don t understand :))
# this is the home function
def home(req):
products = Product.objects.all()
return render(req, 'cos/home.html', {'products': products})
what function are you talking about
did u import views in urls
yes
or not
i did it like that
import cos
import noutati
because i have multiple apps
if i do
from cos import views
it will not see the views from the another app
try creating urls for app and call from there
how do i do that
hmm i guess i will use one app to do all the things
i only need one path
from that another app
create urls.py inside app
@zealous moth sure bud but how do i import it in the main urls
like the admin urls is imported
url(r'^',include('appname.urls',namespace='given_namespace'))
you can search in google
import noutati
in urlpatterns:
path('noutati/', noutati.urls , name = "vezi_noutati")
like that?
okay
yes
not working
path('noutati/', noutati.urls , name = "vezi_noutati"),
AttributeError: module 'noutati' has no attribute 'urls'
it is using regex expression but for path() i dont know how to call urls
and my urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('', views.vezinoutati, name="Noutati")
]
django is really a pain in the ass
use include() func
ok what the fuck happened
Traceback (most recent call last):
File "manage.py", line 22, in <module>
main()
File "manage.py", line 13, in main
raise ImportError(
ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?
oh i m an idiot
path('noutati/', include('appname.urls'))
forgot to activate virtualenv
nice
include not defined
How can I get resources loaded in the web-page with selenium (F12->Network->loaded resources) ?
Hello guys
Anyone good at designing website?
Need some guidance
it's URGENT!
@native tide try
export var custom_blacklist;also, how did you take that cool screenshot? is that a theme?
@versed python I will try it when I am done with school. That is the atom editor's theme
This one is mixed for every Python web library/framework, that's why I asked if there's a dedicated Django channel :/
ohh ok ok, there isn't, this is the only one...
https://discord.gg/5DBJAc @hearty ingot
cool thanks
My Django messages aren't showing up
messages.success(request, 'Email Sent')
return redirect('contact')
are you including them in ur templates?
Templates in settings.py or html templates?
html
I haven't included anything in my html templates relating to message
anyone good with using the bootstrap framework mind helping a pleb out a bit?
I know some bootstrap
I am trying to format my page to have a navbar at the top, and a 3 column page underneath that. The left column is going to be kind of another navbar with some hyper links
I can't seem to get a column working on the left side
it keeps trying to stack ontop of my middle column
okay I will try
@marsh canyon Uh my message appears at the top of the navbar and with no colour
that depends on how u style it, lol
place it whereever u want
just like a html thing
Isn't it already styled
na
hmm, that didn't work. I also am using .nav .flex-column to make it vertical, but it isn't doing that either 🤔
@hallow jacinth Do display:flex and flex-direction:column on the parent element only
Also if you want them side by side you need to do flex-direction: row
@hallow jacinth put it in a separate div and it will be column wise, nothing else
display: block
how ccan i get the sentence below the picture, i tried with flexbox but doesnt seems to work
its for mobile view
Im currently using the following filter with DRF:
But when i filter it will be always using an AND condition how can i change this schema to support OR conditons?
class SystemFilter(djfilters.FilterSet):
id_v = djfilters.filters.Filter(field_name='id', lookup_expr='icontains')
system= djfilters.filters.Filter(field_name='system', lookup_expr='icontains')
deputy = djfilters.filters.Filter(field_name='deputy, lookup_expr='icontains')
deputy_2 = djfilters.filters.Filter(field_name='deputy_2', lookup_expr='icontains')
class Meta:
model = System
fields = ['id_v', 'system', 'deputy', 'deputy_2']
class SystemAPIViewSet(viewsets.ModelViewSet):
queryset = System.objects.all()
permission_classes = [IsAdminOrReadOnly]
serializer_class = SystemSerializer
pagination_class = DynamicPageSize
filter_backends = [django_filters.rest_framework.DjangoFilterBackend, filters.OrderingFilter]
filterset_class = SystemFilte
@wanton ridge Did you try flex-direction:column?
@twilit dagger yes didnt work
Maybe you're doing it on the wrong element
It should be the parent element of both pic and text
yes i did it too but no
sometimes it helps if you put flex:none on the picture and text
but display:flex on the parent
here is my code
put it on picture1
ah ty mate@twilit dagger
when creating a settings page, would it be best to make a new model for user settings or include n user model?
I am thinking new model
so that user model doesn't get too inflated
what do you mean user settings?
But yes typically there is a new model Profile made along with User
And the Profile model handles pfp and bios and stuff
ok ill do that. right now my user model holds the bio and some things similar
who can help me with flask?
who can help me with flask?
@native tide https://dontasktoask.com/
Hey guys i have a problem ☹ as you see my output photo i can create model but i cant use auth.user’s values. I want to create external values but for example i want to use into auth.user name , last_name, last_login values..
class student(models.Model):
authority = models.ForeignKey(Group,on_delete=models.CASCADE,verbose_name="Yetki Tipi")
avatar = models.ImageField(upload_to = 'media/profile_image', blank=True,verbose_name="Fotoğraf")
name = models.CharField(default='',max_length = 50,verbose_name = "Adı")
surname = models.CharField(default='',max_length = 50,verbose_name = "Soyadı")
birthday = models.DateField(blank=True, null=True,verbose_name = "Doğum Tarihi")
email = models.EmailField(default='',verbose_name = "E-Posta")
phone = models.CharField(default=0,max_length=11,verbose_name = "Telefon Numarası")
parent_phone = models.CharField(default=0,max_length=11,verbose_name = "Veli Telefon Numarası")
gender_choice = (
('Erkek', 'Erkek'),
('Kadın', 'Kadın'),)
gender = models.CharField(max_length = 30,blank=True, null=True,choices = gender_choice,verbose_name = "Cinsiyet")
created_date = models.DateTimeField(auto_now_add=True,verbose_name="Kayıt Tarihi")
def __str__(self):
return self.name ```
You haven't added a models.ForeignKey to User, and also don't store the users last_name etc in this Student model. That's why youy can't access these properties.
@tacit comet
Two ways to solve this:
- add
first_name = models.CharField()etc toStudent. I don't recommend this method.
- Add a
user = models.ForeignKey('auth.User', on_delete=models.CASCADE, related_name='user')to yourStudentmodel.
Then you can access these attributes via Student.objects.get(pk=1).user.first_name etc. Like that.
No idea if anyone gonna find this useful, but I created something to help with setting up Flask for development. I had the trouble of having to manually setup db, models, forms, login etc. So decided to create a quick script that does it in 30 seconds.
Then you can access these attributes via
Student.objects.get(pk=1).user.first_nameetc. Like that.
@versed python how can i show admin panel this without click edit button
in admin.py ?
that is where ur __str__ method comes in
@tacit comet I am not really experienced with django admin. This can help https://docs.djangoproject.com/en/3.1/ref/contrib/admin/
@tacit comet I am not really experienced with django admin. This can help https://docs.djangoproject.com/en/3.1/ref/contrib/admin/
@versed python 🙂
wait
you want to change the representation of model instance displayed in the admin?
the page where it lists all the instances?
No idea if anyone gonna find this useful, but I created something to help with setting up Flask for development. I had the trouble of having to manually setup db, models, forms, login etc. So decided to create a quick script that does it in 30 seconds.
@past cipher neat... but any reason you didn't use https://github.com/cookiecutter/cookiecutter ?
i added models name surname as you see but i want to use auth.user 's first_name , last_name methods
ur prolly looking at a custom user admin
from django.contrib.auth.admin import UserAdmin
find this in the docs
@past cipher neat... but any reason you didn't use https://github.com/cookiecutter/cookiecutter ?
@lethal orbit I had never heard of it before
Oh. It's a pretty great tool to do exactly that 🙂
also good to add to my github for when i do eventually start looking for work in a year or so
I'm sure there are flask cookiecutters out there already.
yh probably xD
But you can always write your own. I have one for my stack...
Not quite thorough, because I don't start new projects that often.
I have a couple of jobs on the go, and I hate rewriting code that I've already used, usually takes me at least 30 minutes, especially when creating auth pages etc
thanks for the SQL help yesterday btw, I had to dash so didn't say thanks
Hello, I know it may not be related completely to web dev but in SQL I'm trying to SELECT the 2nd highest element in a CASE WHEN clause. I don't know how to do it. Anyone has an idea ?
has anybody ever done a salesforce integration to pull data out regularly? seems like one good approach would be cron jobbing a script that uses simple-salesforce to SOQL all data in some date range. has anybody done that/something similar and have an opinion?
thanks man.
I am using flask.
I want to have a variable in my base template (parent of all the others) that will always be set, so that I do not have to render_template("example.html", variable=variable)
every time i render a template. Am I able to set a default variable somehow?
@ me when responding, please.
I can't connect to my flask server from another computer via LAN unless I specify host='0.0.0.0'. Does anyone know why? Does flask do some sort of port forwarding magic?
Guys, can you suggest me a good IDE for nodejs which will run smooth in 4gb ram/lower devices
is vim free?
yes
good luck lol
anyone familiar with flask and specifically flask_sqlalchemy?
anyone familiar with flask and specifically flask_sqlalchemy?
@hearty birch https://dontasktoask.com/
hey guys
is this the right syntax to index a column with django ?
email = models.EmailField(unique=True, db_index=True)
I am past the basics and I want to advance but I also dont want to get ahead of myself, but I also dont want to end up making projects from the things that I have done 20 times before, any recommendations?
email = models.EmailField(unique=True, db_index=True)
@strange briar Seems right
I can't connect to my flask server from another computer via LAN unless I specify
host='0.0.0.0'. Does anyone know why? Does flask do some sort of port forwarding magic?
@tight pilot Not flask, 0.0.0.0 and :: means to listen to every available interface, more in https://serverfault.com/questions/21657/semantics-of-and-0-0-0-0-in-dual-stack-oses/39561#39561
I am using flask.
I want to have a variable in my base template (parent of all the others) that will always be set, so that I do not have to
render_template("example.html", variable=variable)
every time i render a template. Am I able to set a default variable somehow?@ me when responding, please.
@topaz finch https://flask.palletsprojects.com/en/0.12.x/templating/#context-processors
Hi friends
I'm trying to deploy my flask app on heroku ... but I get such an error like this :
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="utf-8">
<title>Application Error</title>
<style media="screen"
And when I check logs , I see this :
2020-09-16T18:06:04.000000+00:00 app[api]: Build succeeded
2020-09-16T18:06:04.112017+00:00 heroku[web.1]: State changed from starting to up
2020-09-16T18:06:19.687897+00:00 heroku[web.1]: Restarting
2020-09-16T18:06:19.690781+00:00 heroku[web.1]: State changed from up to starting
2020-09-16T18:06:20.754799+00:00 heroku[web.1]: Stopping all processes with SIGTERM
2020-09-16T18:06:20.786718+00:00 app[web.1]: [2020-09-16 18:06:20 +0000] [13] [INFO] Worker exiting (pid: 13)
2020-09-16T18:06:20.786741+00:00 app[web.1]: [2020-09-16 18:06:20 +0000] [14] [INFO] Worker exiting (pid: 14)
2020-09-16T18:06:20.787149+00:00 app[web.1]: [2020-09-16 18:06:20 +0000] [4] [INFO] Handling signal: term
2020-09-16T18:06:20.988269+00:00 app[web.1]: [2020-09-16 18:06:20 +0000] [4] [INFO] Shutting down: Master
2020-09-16T18:06:21.577505+00:00 heroku[web.1]: Process exited with status 0
2020-09-16T18:06:23.713913+00:00 heroku[web.1]: Starting process with command gunicorn run:app --preload
2020-09-16T18:06:28.686751+00:00 app[web.1]: [2020-09-16 18:06:28 +0000] [4] [INFO] Starting gunicorn 20.0.4
2020-09-16T18:06:28.688185+00:00 app[web.1]: [2020-09-16 18:06:28 +0000] [4] [INFO] Listening at: http://0.0.0.0:11808/ (4)
State changed from starting to up
2020-09-16T18:08:02.420945+00:00 heroku[router]: at=error code=H12 desc="Request timeout" method=POST path="/api/auth/admin/signup" host=agile-basin-93374.herokuapp.com request_id=fadb7827-cc2e-460d-98ae-d22efa3614dd fwd="2.179.42.45" dyno=web.1 connect=0ms service=30001ms status=503 bytes=0 protocol=https
could anyone help me?
https://dpaste.com/DFSY5RWMT I m getting management form error despite of putting {{abc.management_form}}
plz help
Sort of strange but my hover classes don't work in Heroku
@twilit dagger you sure heroku is actually serving the css file if you have a seperate file for that
@twilit dagger whats the full class list?
This is all -
.navbar-nav .heading{
color: white;
}
.navbar-nav .heading:hover{
color: #444444;
}
.navbar-nav .header-btn:hover{
color: #333333!important;
}
.header-btn:hover{
color: #333333!important;
}
"btn btn-outline-light float-right text-light header-btn btn-lg"
I sent CSS so it makes sense
This is with bootstrap
you know you havent defined the base css for it first right?
cant apply a hover varient to a css element that doesnt exist 🙃
what are you saying
everything todo with the button you have as hover varients
<div class = "text-right float-right">
<a href = "{% url 'contact' %}"type = "button" class = "btn btn-outline-light float-right text-light header-btn btn-lg">
Contact</a>
</div>
Doesn't bootstrap handle that
no idea
it works on localhost just not on heroku
whitenoise
does any of the css work
that is a yikes tbh
i dont know heroku so i cant really help you with much more of that im afraid
So im looking for some feedback on a router im making and wondering if others might find it useful.
The general idea is to make it easier for you to layout your applications with fewer global varibles using true class instance views regardless of the framework.
Example of a view file:
# ./views/my_view.py
import router
from sanic import Sanic
from sanic.websocket import WebSocketConnection
from sanic import response
from sanic.request import Request
class MyEndpoint(router.Blueprint):
def __init__(self, web_app: Sanic):
self.app = web_app
@router.websocket("/")
async def my_func(self, ws: WebSocketConnection):
pass
@router.endpoint("/hello")
async def hello(self, request: Request):
return response.text("Hello world")
def setup(web_app):
web_app.add_blueprint(MyEndpoint(web_app))
Example main.py
# ./main.py
import typing as t
from sanic import Sanic
from sanic.websocket import WebSocketProtocol
from router import Router, Endpoint, Websocket
app_files = [
"views.my_view"
]
app = Sanic(__name__)
def submit_route(_, endpoint: t.Union[Endpoint, Websocket]):
if isinstance(endpoint, Endpoint):
app.add_route(handler=endpoint, uri=endpoint.route, methods=endpoint.methods)
elif isinstance(endpoint, Websocket):
app.add_websocket_route(handler=endpoint, uri=endpoint.route)
router = Router(app, app_files, submit_route)
if __name__ == '__main__':
app.run("127.0.0.1", port=8000, protocol=WebSocketProtocol)
In this example im using Sanic but this will work with any ASGI or WSGI framework, using a simple callback for you to tailer your route setting to the framework's design.
This should help anyone stuggling with laying out their apps with lots of global varibles gain a bit more control over their layout.
Please let me know of any feedback you have for this and if you think it would be useful to make public 🙂
hey if anyone is familiar with django
and can give me a hand with a filter system
pleaseeeee
Post your code
Hello there
So I have an SSO login at my office...I can direct to it and get the key and refresh key back...how does flask separate that info from the next person loggint in 5 seconds later?
can someone help me convert python script to exe file
flask is easy and lightweight
Nice thank you though. I wasn't aware of this I always thought they were created though html/css or javascript
Vue and either Flask or FastAPI
is it possible to do front end in django or flask?
Yes but it’s not industry standard
uggh that's why I hate the industry
why can't it just accept vanilla django
now I am having to learn all this Javascript shit
Because More responsive
ik the reason why it's industry standard. doesn't mean i like it
Sure but there is damn good reason for it
i know it. I'm using Vuejs now, and can see how websites look better right out of the box
I guess it's kinda a tradeoff. You either choose beauty with more time spent or, ugliness but with less time spent
hi
just trying to add a filter
for all the different atributtes from a model
and all the atributtes have different kind of values
some are boolean, some are charfield, some are intFields
etc
so every filter has to be unique
and I don't know how to join them
if someone has a clue or an example to share
:c
@valid sandal django or flask? Share your model structure here please.
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
!code
Discord has support for Markdown, which allows you to post code with full syntax highlighting. Please use these whenever you paste code, as this helps improve the legibility and makes it easier for us to help you.
To do this, use the following method:
```python
print('Hello world!')
```
Note:
• These are backticks, not quotes. Backticks can usually be found on the tilde key.
• You can also use py as the language instead of python
• The language must be on the first line next to the backticks with no space between them
This will result in the following:
print('Hello world!')
@valid sandal
Don't you find it difficult to write code both in English and Spanish?
spanglish ftw
lol that sounds like a dog
it's shared code with my team, so I have to do it
Does django help
Not with that attitude
huh
Can you give an example?
this is a filter from another proyect
where I only apply a simple filter by a category called "rubros"
Looks like this is what you want https://docs.djangoproject.com/en/3.1/topics/db/queries/#complex-lookups-with-q-objects
it does not run all of the code for each request
it does run a bit to check if there is a request
but the actual request handling happens once
guys who is better change something in admin panel or in database?
heres the answer your going to hate
"it depends"
if your going to be doing it a lot maybe its easier to do it in the admin panal
guys who is better change something in admin panel or in database?
@mystic wyvern If you mean Django, the admin panel should not be used by too many users. It's meant specifically for administrators, not end-users.
if its going to be rare and only you know how to do it then maybe its not worth the effort and u can just do it in the database
If you mean a one-time change to your models, nothing wrong with using admin
ok guys thx
Hey guys i created a new directory inside media directory from views.py file now how can i cd to the new created directory..
Wdym @zealous moth ?
??
I’m pretty sure that’s against their ToS
Wdym @zealous moth ?
@versed python Ok i got it...😆
I’m pretty sure that’s against their ToS
@jagged lark Who was this for?
For @zealous moth, about the tiktok ToS
@jagged lark idk
You guys still have TikTok?!?!
Nope i dont use that shit😆
whys the django did not apply the changes instantly sometimes. I did restart the server 3-4 time but the changes are not taking place
hi everybody 😊,
my english is bad so please be kind.
i use python since 1 month, my background in web development 5 month in php.
i win a stage and the begin of diffuclt is here ! my brain 🧠 have no connexion with the unit-test ( pytest)
perhaps some of you have a good hints or tips to helps me ! i need a success small one but one 😊😊😊
thanks
ps: i work with the framework piramid ! python3
perhaps some of you have a good hints or tips to helps me ! i need a success small one but one 😊😊😊
I find using functional programming paradigms makes writing unit tests easier. Don't try to keep too much logic tied to your data models, but write logic in small, easily testable functions as much as possible. As a bonus, you can easily reuse those functions across different modules and models.
Also, check out #unit-testing , and read as much as you can about the topic. I recommend these 2 books, even though they are not related to pyramid in any way:
- https://pragprog.com/titles/bopytest/python-testing-with-pytest/
- https://www.obeythetestinggoat.com/ (free to read online, but I am not a fan of selenium).
'function' object has no attribute 'objects'???
Help pls, if I have an app that does something that takes like ten seconds to work hosted on heroku, does that mean each user who sends my app a request has to wait ten seconds or do they join a queue and have to wait for ten seconds*the number of users ahead of them? Or does it simply crash?
Sorry if the question doesn't make sense
Probably the first especially if your app has a lot of good looking stuff
An easy way to check is by trying to access the website through your pc, laptop and a few phones from your family members @high jacinth
@IgnisDa I'll do just that actually
oof
What are you doing that takes 10 seconds @high jacinth ? Why not pre-calculate it?
No, doff
@lethal orbit I'm webscraping and wrapping the result up in an epub. I also wanted to know how heroku would deal with blocking code if there was any
Maybe you should cache your result then
Of you aren't using any *wgi system, they will just end up on a queue, yeah
If it is one file, you are probably better off indexing it.
I'm not scraping the same thing repeatedly. What's *wgi??
If you are letting people pass a URL, then it is definitely more complicated.
If it is a set of epubs, you probably also would want to process them all and index them.
They are tools made to dispatch the requests to many instance of your server
@lethal orbit I'm not keeping any epubs, I just want to consume the url then spit out an epub
@jagged lark pls give me hint
And by that I mean direction to documentation. Do I just google wgi?
I'm not sure if that's possible with heroku
Oh. 😢
@lethal orbit thanks 😊
because fucntion object does not have attribute objects.
you are probably looking for a model object
and got something else
if we are talking about django of course
I could perhaps help you a bit more if you shared the snippet that triggered the error
look i write this in my views
def new_topic(request,boerd_id):
board=get_object_or_404(Board,pk=boerd_id)
if request.method =='POST':
mes =request.POST['message']
sub= request.POST['s']
user=User.objects.first()
Topic = topic.objects.create ( subject=sub,
created_by=user
)
the issue is with topic
are you importing it correctly?
and is it a class that inherits from models.Model?
yeh i do all of this
and i import it and i inherits from models.Model
look class topic(models.Model):
in drf how to pass a non model field of any type and get it back in response ?
i think u mean SerializerMethodField() @woeful swan
Django, API, REST, Serializer fields
i tried that but after .is_valid() call it is not present in the validated_data
do you read-only set on those fields by any chance?
nvm
SerializerMethodField() is by default read only
then
u can define fields in the serializer
custom fields
just outside ur Meta class
for now
class QuerySerializer(serializers.ModelSerializer):
# q = serializers.CharField(required=True, max_length=512)
extra_params = serializers.SerializerMethodField()
q = serializers.SerializerMethodField()
def validate_q(self, value):
return value
def get_extra_params(self, *args, **kwargs):
print(self.initial_data, 'extra params')
return self.initial_data.get('extra_params')
def get_q(self, *args, **kwargs):
return self.initial_data.get('q')
class Meta:
model = SessionInfo
fields = ('q', 'bot_id', 'session_id', 'extra_params')
# extra_kwargs = {
# 'bot_id': {'write_only': False},
# # 'q': {'write_onlyr: False},
# }
class QueryResponseSerializer(serializers.Serializer):
session_id = serializers.CharField()
response = serializers.ListField()
status = serializers.DictField(required=False)
extra_params = serializers.SerializerMethodField()
def get_extra_params(self, *args, **kwargs):
return self.initial_data.get('extra_params')
class QueryApiView(views.APIView):
def post(self, request, *args, **kwargs):
# print(request.data, 'berfoer')
## session validation
try:
session_obj = SessionInfo.objects.get(session_id=request.data.get('session_id'),
bot_id=request.data.get('bot_id'))
except SessionInfo.DoesNotExist:
return Response({'error': 'session does not exists for given bot'}, status.HTTP_404_NOT_FOUND)
# serializer with instance
serializer = QuerySerializer(instance=session_obj, data=request.data)
print(serializer.initial_data, 'initial')
# checking validation
if serializer.is_valid(raise_exception=True):
print(serializer.validated_data, 'validated')
# fetching response
resp = bot_response(serializer)
finalize_data = {
'session_id': serializer.validated_data.get('session_id'),
'response': resp,
'extra_params': serializer.initial_data.get('extra_params')
}
serializer_output = QueryResponseSerializer(data=finalize_data)
if serializer_output.is_valid():
serializer.save()
return Response(serializer_output.data, status.HTTP_200_OK)
return Response(serializer_output.errors, status.HTTP_400_BAD_REQUEST)
return Response(serializer.errors, status.HTTP_400_BAD_REQUEST)
using this
i just want the extraparams in request and return as it is while saving the data
what are you passing in
i am very new to drf so it is confusing me?
{
"session_id": "SUq50ChnZjRiZ5rb",
"bot_id": "MGZI6EE3",
"q":"hiii",
"extra_params": {
"amit": "bisht"
}
}```
ok
on more question. how can i accept any type of data . not just char from that field
?
well you can use a charfield and take in whatever you want and later parse it
there is even Json field
and u can pass anything with the json
but it has to be string right?
mostly, yes
i want it to accept int, list, dict and str
its good have a data type assinged, to not confused the API user
then make 4 fields for those
well setting as charfield worked now. I don't know why it was not working before?
u use SerializerMethodField() before, right?
then make 4 fields for those
@marsh canyon i mean extraparams can be of any of those type?
u use SerializerMethodField() before, right?
@marsh canyon no first i used charfield, but it was giving error so after researching i used SerializerMethodField but that was not coming in validated data.
like path/?name=iceman
here name is a param and the value is iceman
you can get these by doing either request.GET or request.get_params -> these 2 are query dicts
no non no . extra_params is just a key name. it can be optional data. which api user can pass and will be returned same in response
{
"session_id": "SUq50ChnZjRiZ5rb",
"response": [
{
"sender": "SUq50ChnZjRiZ5rb",
"message": null
}
],
"extra_params": "amit"
}```
response sample
so maybe a dict will be good for extra params
yeah i have considered that
or just have explict names for all the extra params
in dict field there is child argument
i mean havea field for each extra param
what does it checks
i mean havea field for each extra param
@marsh canyon i understand
BTW thanks man for helping
the child arg is to set the data type for values
the keys are assumed to be string
Django, API, REST, Serializer fields
docs
oki
👍 👍 👍
lemme know how it goes, cuz i have never used DictField
sure. i am just now rewriting a single serializer for this. two are confusing me.
oki
{
"session_id": "SUq50ChnZjRiZ5rb",
"bot_id": "MGZI6EE3",
"q":"hiii",
"extra_params": {
"amit": "bisht",
"roman": 34,
"texas": {
"smash": "yes"
}
}
}
{
"session_id": "SUq50ChnZjRiZ5rb",
"response": [
{
"sender": "SUq50ChnZjRiZ5rb",
"message": null
}
],
"extra_params": {
"amit": "bisht",
"roman": 34,
"texas": {
"smash": "yes"
}
}
}```
yeah it worked man
cool 👍
i guess the default is charField
oh nvm, if you dont provide one, then it will not bother checking
ok
@zinc hill maybe post ur question down here again, just so its noticed
ok thanks
view.py
class RestaurantLoginView(LoginView):
template_name = 'accounts/restaurant/login.html'
def get_success_url(self):
url = 'company_profile'
return super().get_success_url()
how do i redirect to something else instead of LOGIN_REDIRECT_URL
right
so instead of returning the Super() implementation, you can return url instead
lemme check what format the url is in
you have to set url to the full path
and not the url name
or you can import resolve_url from django.shortcuts and pass in the url name to resolve_url to generate the url for you
yeah I tried setting the url = 'company/profile/' and return url but it keep adding on to the path
use resolve_url
ok I will look into that
from django.shortcuts import resolve_url
return resolve_url(<your url name>)
this is how django does it internally
django uses resolve_url
this is the source code
Vs
awesome
if you hold ctrl and hover over LoginView
it should be highlighted, when you click it, it will take u to the source code
yeah I saw that and I didnt think to replace the "settings.login_...." to something else
settings.login.. is just the url name, if you remember
I was trying to think of something stupid like setting settings.login.... to something my url instead...
instead of just replacing that smh
its fine, you know now
thanks alot
👍
thats enoguh for today smh
django does burn ur energy fast 😬
yep got stuck for so long today because I realised that I didnt need AbstractUser so I delete the database and makemigration, but it keep saying auth table doesnt exist
u need to migrate
turns out one of the terminal was open and was in manage.py shell
yeah I did
once I quit the shell... and do the migration again than it work
also, you need to reconfigure the auth model in settings
that was 2hrs of googling wasted
aaight thanks again for helping me out
have a great night
u too
@marsh canyon you there
Got AttributeError when attempting to get a value for field extra_params on serializer InitSerializer.
The serializer field might be named incorrectly and not match any attribute or key on the SessionInfo instance.
Original exception text was: 'SessionInfo' object has no attribute 'extra_params'.
getting error. but model is saving data
in DRF
Is there a way to exclude an attribute from being serialized by json.dump?
Cannot assign "<Board: 1>": "post.topic" must be a "topic" instance.
what this is?
Is there a way to use something like:
rating_dict = sorted(rating_dict, key=rating_dict.get, reverse=True)
but for larger querysets? Especially when scaling. It's taking like 4-5 seconds so far for 500 entries.
I'm essentially needing to sort a user directory by rating, which is devised by a method on the user object that does some stuff to determine the rating.
I considered just having a rating field on the user, and updating it whenever the user does "something", but that makes it less accurate over time.
why do i get this error and how do i fix it? please ping me in reply