#web-development
2 messages ยท Page 182 of 1
the file in which the error occurs
I am not able to access the admin page. Im getting a 500 status code while accessing /admin
i cant debug which file is the error source
Figured I would jump in, working at last:
<div class="image-container">
<div class="card image-card justify-content-center">
<h1 class="text-center">Data Manipulation</h1>
</div>
</div>
.image-container {
width: 100%;
height: 400px;
position: relative;
background-image: url(images/other/home_encryption.png);
background-repeat: no-repeat;
background-size: cover;
}
.image-card {
position: absolute;
top: calc(50% - 20px);
left: calc(50% - 200px);
width: 24rem
}
ERROR: Command errored out with exit status 1: command: /data/data/com.termux/files/usr/bin/python3 -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/data/data/com.termux/files/usr/tmp/pip-install-or7kne1o/pymongo_4c8372d8aea5484bb4685e01b49d414a/setup.py'"'"'; __file__='"'"'/data/data/com.termux/files/usr/tmp/pip-install-or7kne1o/pymongo_4c8372d8aea5484bb4685e01b49d414a/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /data/data/com.termux/files/usr/tmp/pip-pip-egg-info-7k2g2h4c cwd: /data/data/com.termux/files/usr/tmp/pip-install-or7kne1o/pymongo_4c8372d8aea5484bb4685e01b49d414a/ Complete output (11 lines): Traceback (most recent call last): ). Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.
When i download django this happens
Using pip
Wtf...
Maybe this will help point you in the right direction... https://stackoverflow.com/questions/11618898/pg-config-executable-not-found
Doesn't help....
Wow...that was a fast conclusion ๐
Yes.... cuz the problems are different, and i tried the solution
I can't even download brew
Typically, when I get error messages like it can take me time to get to the bottom of cause. Following the trail typically takes more than minute of looking at a post. Unless of course you've done all that, in which case, it's a great idea to include what you've tried with your question
im following a tutorial
and when i want to migrate i get this
You are trying to add a non-nullable field 'user' to post without a default
Can you post the model.py file for the app? Django or Flask?
but the tutorials code and mine is the same which is =>
class Post(models.Model):
# filters posts so only published posts are avaible in the home screen .
class PostObjects(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(status = "posted")
options = (
('draft' , 'Draft'),
('posted' , 'Posted'),
)
clique = models.ForeignKey(Clique, on_delete=models.PROTECT, default=1)
content = models.TextField(max_length=400,null=True, blank=True)
caption = models.CharField(max_length=400,null=True, blank=True)
posted = models.DateTimeField(default=timezone.now)
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='clique_posts',blank=True)
status = models.CharField(max_length=12, choices=options, default='posted')
objects = models.Manager() # default manager
postobjects = PostObjects() # custom manager
If you add null=True to the user field that error message should go.
You've got blank=True and need null=True.
Also, use back quotes for pasting code
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='clique_posts', null=True, blank=True)```
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
If you cannot download something else it seems like you might have bigger problems with the virtual environment, the install of Python, the version of Django.
i get this when i want to migrate django.db.utils.ProgrammingError: relation "Occupy_post" already exists
Side note, I've started following tutorials in the past and then dropped them like a burning piece of charcoal when they led to errors.
If you're code is a duplicate of theirs and their model had blank=True without null=True...I'm sorry, but that's a bit of a serious miss.
My recommendation...Corey Schafer...His series on Django on YT is free and outstanding.
I'm 20k lines of code later and have a great Django web app. All from the start with Corey
That's a red flag for me.
preciate it
You're welcome.
I feel ya. I get wanting to finish the tutorial. But not all teachers are equal
Wdym by install of python and virtual environment
Back in the early days I started getting some weird errors. After looking at things it appeared I had managed to mess up my python setup. I literally wiped Python and evertything to do with it. I then started again. Fresh install, creating a virtual environment for every project. That way I now keep all projects independent.
When I started with Python I didn't get how important that was.
How do i wipe everything completely
What OS are you using? Windows? Mac? Linux?
Linux
That's not my bag. I'd google, remove Python and rebuild on Linux.
Side note, as a programmer you're going to need to take questions like "How do I....?" and start from the premise that you will need to research the answer.
For me, programming is 50% problem solving, 40% research, 10% coding ๐
Good luck. The good news...when you do start with a fresh environment it should be better.
Also, research about creating and using virtual environment in Python
help me ):
i want help in python django
my css files images are not working
helppppp pls
i m asking for help from 1 hour
):
i deployed my django app in heroku
html file images r working
help plz :/
Hi @distant panther it sounds like it's your static files yes?
did you do the collectstatic command?
https://i.imgur.com/HmjcNnj.png i am learning webdev so i started making html and js file but when i open my browser it does not load the console correctly with the given file. https://i.imgur.com/Y1RZYAK.png
whats the best app to use to help write mobile app
How do I add nodejs to a dockerized django app?
On line 13 and 14 remove webdev/
The path is relative to cwd
why ??
can u explain a bit more please
The browser searches for the file in the current working directory. Since there is no webdev folder in that directory (the directory itself is called webdev), you get an error
how about putting into another container ๐
and just exposing it to your dockerized django app
multi containerization
https://howchoo.com/media/ym/m2/zm/docker-secrets.jpeg
thanks
Also you have used the script tag incorrectly
how can I find people to work with me on a game website?
Look up a tutorial on basic html
How do I use the django template tags to iterate only over dictionary keys that begin with a certain string? I have a context with lots of keys, but I only want to load 'Column1', 'Column2', etc..
Filter them out in the view, keep templates clean
@versed python I see. I will try that!
Posting about it on relevant subreddits help
i still get the same error
is it becos of the same script tag ??
ok sir ๐ thanks for guiding
slight issue with urls here.
@inland oak so i plan on using jest as a testing service for the front end
and i only need node for jest
my urls simply append to the current url, instead of appending to localhost/
why does this happen?
Show some code
i guess i have to use it like this
<script>
src= "js1.js"
</script>
I would personally do that via docker compose or kubernetes
Err, wrong reply
@flat temple ^
Lmao you scared me
What are you trying to do?
What is the best way to acces static files in Django views.py (from objects especially)?
yes.
urlpatterns = [
path('', views.home, name='home'),
path('register', views.register, 'register'),
path('login', views.login, name='login'),
path('all-stocks', views.all_stocks, name='all-stocks'),
path('stocks/<str:symbol>/buy', views.buy, name='buy'),
path('stocks/<str:symbol>/sell', views.sell, name='sell'),
path('stocks/<str:symbol>/', views.stockinfo, name='stockinfo'),
path('portfolio', views.portfolio, name='portfolio'),
]
url patterns look like this
but when im here: http://127.0.0.1:8000/stocks/INFY/sell, and I click on portfolio, it goes to http://127.0.0.1:8000/stocks/INFY/portfolio, which doesnt exist..instead of 127.0.0.1/portfolio
<h4> <a href="portfolio">Portfolio</a> </h4>, this is portfolio link
This is wrong
how?
trying to use jest testing on my django front-end app
Is that even possible?
idk
Afaik jest is usee for unit tests
Its not possible
Look into cypress if you want to write e2e tests
Selenium if you prefer python
Ahh then your framework must have jest integration
thanks it worked!
First you need to define what exactly you want to test
Do you know that Jest can work with Webix?
If you know that, then you can set up Docker for it
I do not know
@versed python in href, if I give a path, shouldnt it go directly there instead of appending to current url?
Well, I'd first recommend testing that outside of Docker
And then, if it works, you can add it into a Docker setup
it seems like it can work with mocha
based on this github
No that's not how a href works
mocha is a good alternative
so, say im at localhost/A. and I click on href="B"----will it go to localhost/A/B ?
what if I wanna go to localhost/B?
Err, I think Jest can work even with static HTML, but I'm not sure
So you should be able to use it with this Webix
perfect
I'm not sure though, so I'd advise you to try it out before you set it up in Docker
it seems like it can
Ok, so if it's just for local testing, Docker compose should do.
You can set up a Node.js image and a Python image to run both Django and Node in separate containers
But the Node container can go to the Django container's page and run Jest on it
ok, and thats gonna be on the yml file?
In a docker-compose.yml, yes
are you using compose in production?
Could you show me your project structure real quick so that I can show you can example?
Also, do you already have a Dockerfile for django?
yea iu can walk you through the project
All I really need to see is the project structure
And your Django Dockerfile
href="/B"
Absolute vs relative paths
no idea if this is webdev or not but tryna get a flask server running as wsgi and using live reload but cant seem to find any coherent examples or docs so if anyone has experience either or then some help would be appreciated
I can help but i also need help lol
Hello! My django model object is returning False when i try to get it's id as such: chatroom.id Does anyone know why it would do this? I saved the object right before using chatroom.save().
Dragon where are you running this app?
just running it thru a batch file that sets the app the env then runs it in a folder on my desktop
so thats pretty broad i guess giving you documentation of how to run a flask app would be what you need but your not a newb :/
so idk how much help it would be
its mainly the wsgi part im struggling with
thats whats preventing me from setting up the livereload by the looks of stuff
Just run the flask app
I would do live reload with a systemd service
That reboots the flask app when it fails.
it needs to be constantly updating the web content as im trying to set up a live counter
Flask would render different data depending on the state of the data in your flask app
i have the server being served but its not auto updating i still have to manually refresh the page
Oh! Lol thats a completely different thing
You need websockets
or pinging requests to auto update your page
There are actually 3 ways to go about it; But.. I recommend websockets.
well thats what livereload is supposed to do but so far it aint working
Did you try this answer on livereload?
probably for for testings sake one more wont hurt
didnt update the value until refreshed
might be how im running it
if i just run the main file and not using a flask command
but then i get module not installed errors cuz my pc be broke like that
yeah if u do flask run command it uses a different env
i cant run on host system cuz my python doesnt detect installed modules and cant run on cloud cuz the ips dont allow connections
I think you cant run it manually with the main.py file because you aren't pip installing on that command...
If you are running python for example use:
python -m pip install livereload
i have everything installed already
python just thinks i dont
from flask import Flask
import urllib,json,os
from mcstatus import MinecraftServer
from livereload import Server
app = Flask(__name__)
@app.route('/')
def main():
server = MinecraftServer.lookup("51.222.134.183:2011")
status = server.status()
result=("{0} ".format(status.players.online))
return(f"server has {result}/100 online")
if __name__ == '__main__':
main()
thats the flask code
without trying to add a livereload server
what it looks like i need to do is include the routes somewhere else and import
nope didnt work
Anyone would be able to help set up traefik with wildcard domains and auto ssl certificates? ๐
How could I create a function in the django backend, and then have the ability to use it in my react frontend build, that I deployed into django.
So, I know that to get something from the database, I would have to create an api view through DRF, and then in the frontend I would just refer to the url of the apiview
But how do I do the same thing with functions
For example if I wanted to implement logging in from a social media like facebook, and I wanted to fetch their username, to store in the database, so that the user can be controlled, remembered, etc., but I would have to display the function on the actual website, so I would have to refer to the function from the backend on my frontend
This is usually handled via nginx I believe.
I used to use a DigitalOcean Django Nginx Gunicorn tutorial for my initial setup.
That might work for flask if you know how to just do it in a flask environment, but it will help you get the server aspects running at least.
You just point the front-end route/url to go to the function you want.
That's basically the same thing as creating a REST api. You point the url at a specific view via its url, and it does whatever you're trying to do.
oh right, thank you
Hello guys, I wanna ask is MySQL good with Django, cuz a friend says its not the best choice
so what do you think?
I think PostgreSQL is the more common SQL db to use.
I thought MySQL is really only used primarily with C-based stacks or windows servers.
that mean I have to switch to PostgreSQL, right ?
You don't have to. I would use the best DB for your needs. But if it's a linux server, then PostgreSQL will be a better fit.
You can also use Postgres on windows, so you don't have to worry about later going to production on a linux server if you code on windows.
@dense slate thank you for help
figured out how to not only fix my issue but also add a html interface and use javascript to take live updates and set values instead of piping python directly in flask
okay so https://pastebin.com/ean4HkGN
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.
this is my whole code
the issue is that i cant seem to send face_detection my image paths
and this is really blowing me up.. been with it from 2 days and cant figure out shit and turned to discord today for help. Ive to submit it tomorrow and i cant seem to get a hang of it
@native tide ^
anyone who could help would be heavenly appreciated. thank you
What's the best Django tutorial (either video or text (except docs)) in your opinion?
this is the error that im getting tho
DjangoGirls tutorial is really good.
So first of all, that image path doesn't look right.
yes exactly. what should i do with that
thanks, will check it out
ok so the thing is that my detect_face function is working extremely fine as i ran it on console. when i integrated it with flask it started messing up
That error is basically saying it can't find your image.
So either the path isn't right or a setting in your code pointing to a particular directory isn't right.
yes yes @dense slate you are exactly right. The thing is i know that the path is the issue, the problem is that i dont know how to fix it
i rewrote some things wait
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.
@dense slate take a look please
I'm looking at that.
thanks a lot for trying to help man! Been stuck on it from quite a while now and its 3 30 am here xD
So look at all the paths and make sure they are correct. I don't know what they should be, but d:/ isn't correct syntax.
So I'm not sure how that worked before.
d:/ is my folder, the program never reaches there.. it pushes an error before it goes there
Someone please help we with this https://stackoverflow.com/questions/68809244/i-cant-upload-images-from-react-to-django-backend
omg๐ซ
@dense slate it just saves the img_cropped there
OH nooo.. thats not the problem at all.. It uses forward slash when it comes to paths here.. I Honestly dont know why.. Here take a look at this code which is just 'detect_face' and it would work absolutely fine
Hrm, ok.
so why does the path change from forward slash to backward slash later in the path?
I've never seen that, so that might just be my ignorance.
@dense slate https://pastebin.com/asr2S7EY
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.
Not to mention a double slash.
See, here you have forward slashes
C:/Users/HP/Desktop/models/frame_{j}_face.jpg'
idk man i really have no clue
Ok anyways
oh look those are the image paths.. see the img_cropped part.. there its the same way im doing it
I really don't know otherwise. That feels like the issue to me.
tell me exactly what to do and ill fix it
as you can look in the working code of detect_face it says exactly to use forward slash, im also using forward slashes in my program.. where's the issue
where are you telling it to use the WIN_...Pro.jpg?
@dense slate list.append(os.path.join(app.config['UPLOAD_FOLDER'], filename))
so basically it just saves it on a server if i dont put my own upload_folder in there and then i append it in list
But that's not in this code
ummm it is
in this one
Oh gotcha, sorry looking the wrong one.
not a problem man youre the only one trying to help me since 14 hours. Im thankful right now lol
youre the only one who showed up since i last msged in places since 14 hrs*
what does os.getcwd return?
I'm just trying to figure out where the path is getting corrupted
yes so i dont know let me see?
you need to figure out all the things adding aspects of the path and nail down where it's giving you bad info
very likely that flask is pointing at something you're not expecting it to, or alters the path you anticipate, so you need to figure out where that is.
i havent used os.getcwd and dont know what its doing.
yes @dense slate ive been trying my ass off to do that lol. this should work fine instead its not
ok, but list.append(os.path.join(app.config['UPLOAD_FOLDER'], filename)) uses whatever os.getcwd returns, right?
and you don't know what that is
can you make it like something = list.append....etc. and print it?
see what you're actually getting
on it boss
or maybe just print os.path.join(app.config['UPLOAD_FOLDER'])
that was the earliest code remember? here is the new error is almost the same form
wait sending ss
@dense slate
aha, so first of all the slashes did change, and now you have two \ at the beginning and between the path and the image name.
What did you do that changed it?
Same code but different error?
no the error was for the VVEEERRRYY initial code
this one
You need to show current code with current errors otherwise it's impossible to correctly debug stuff.
You've got the idea of how to start searching out what is now causing an extra / in those two places.
Remove those and, if the path is accurate, it will work.
Like why do you have \ instead of / in the path if it is the same code. You had to change something.
Hi, can someone with Flask experience please check out #help-cookie ? Thank you!
Ok @dense slate give me exactly five mins i havent eaten in many hrs i just need to get something and then ill be righy back with you
I have to step away as well. Good luck!
Hey guys when your mocking up a website, just basic we'll say a navbar and then a main content pane. Do you wrap flexboxes in grid boxes to get the scability to mobile? If this is a stupid question my bad.
For the thousandth time, I really need assistance with this https://stackoverflow.com/questions/68809244/i-cant-upload-images-from-react-to-django-backend
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.
๐ซ๐ฉ
Dont know django or react enough to help you, good luck friend
What I can't believe is that I found no one from stackoverflow to help me yet
this is crazy
This sounds like a question for a Discord focused on React.
https://discord.gg/KJQ83BCT
Once I get through phase 1A of my web project I'll be onto React to build a diagramming app for this web app. But for now, I'm green when it comes to React.
def registration(request):
registered = False
if request.method == "POST":
user_form = UserForm(data=request.POST)
profile_form = UserProfileInfoForms(data=request.POST)
if user_form.is_valid() and profile_form.is_valid():
user = user_form.save()
user.set_password(user.password)
user.save()
profile = profile_form.save(commit=False)
profile.user = user
if 'profile_pic' in request.FILES:
profile.profile_pic = request.FILES['profile_pic']
profile.save()
registered = True
else:
print(user_form.errors, profile_form.errors)
else:
user_form = UserForm()
profile_form = UserProfileInfoForms()
return render(
request, 'templates/registration.html', {
'user_form': user_form,
'profile_form': profile_form,
'registered': registered
})
if request.method == "POST":
user_name = request.POST.get('username')
pass_word = request.POST.get('password')
user = authenticate(username=user_name, password=pass_word)
if user:
if user.is_active:
login(request, user)
return HttpResponseRedirect(reverse('index'))
else:
return HttpResponse('Account not Active')
else:
print("someone tried to login and failed")
print('username:{} and password :{}'.format(user_name, pass_word))
return HttpResponse("invalid login details supplied")
else:
return render(request, 'templates/login.html')
i created a register form to register users and a login form, registering a user is working fine but when i try to logging in with the user that i created i get invalid login details
ps. when i try to log in with the admin superuser it is working fine
after looking further into it i tried to print out the 'user ' variable and it prints out "none"
Can you also show models.py for the app as well
The user and profile tables from models.py would be enough
from django.contrib.auth.models import User
from django.db.models.deletion import CASCADE
# Create your models here.
class UserProfileInfo(models.Model):
user = models.OneToOneField(User, on_delete=CASCADE)
portfolio_site = models.URLField(blank=True)
profile_pic = models.ImageField(upload_to='profile_pics', blank=True)
def __str__(self):
return self.user.username
I would like to develop a widget that can embedded into a site like Weebly. Does anyone know if this is possible?
Bruhhh u know what i found the problem
I need to install mongodb database first
Finallyy argghhhhhhh
i think the somwthing is wrong with the authenticate() method, maybe the parameters
Hello Guys,
Does Github webpage deployment support SASS?
I am trying to fetch data from a public api and store an object in my custom created models, i.e. my database. I am able to display the api data on an html page but is there a way to store it into database directly?
Which DB are you using?
Django sqlite
class MyModel: ..... ....
Suppose its a class model where you want to store your API json data.
Now you have to make an object in API View
you may be did it in API View
obj = MyModel(a=1,b=2...)
obj.c=12;
obj.save()
that's it.
So I should be able to assign the values from the Api to the model in the views itself?
Upon creating the object and pulling from the json
I'll give it a try thanks
i suggest using some more creative fonts and a different color scheme
yes, you can
Flask for example is web framework to do this
Ok...thanks
no
That's the first thing to check them
k
btw yes that's my static file
i have css folder inside it and then img folder
images in html file is working
but i used bgimage in css file
that is not working
);
I am trying to make Online video learning platform(like Udemy). So what is the best way to store videos?
s3 storage
that's great option but there some problem with funds
large storage is not free bro
yeah I know, but this clients sucks
so is there any platform which can be used for development purpose but later it can scale ?
I get why you chose the white, orange and blue (I see the connection with the Indian Flag). However, the neon green is a bit harsh in contrast. I would change the neon green buttons to perhaps be the orange for the Quiz banner, and shift the banner to be the background blue. I'd also change the colour of the question-font to match the blue background. This would honour your intention of aligning the colours of the Indian Flag, but would bring you to just those three colours. A tri-colour palette would actually have potential. The neon-green is murdering the visual experience AS-IS.
Search through google fonts for alternatives. There has to be a font that will have more of an Indian feel to it. If you're going with the colours of the Indian flag, pick a font that fits in. Times New Roman may be colonial, but the Brits have been gone for a long time. ๐
I would also lose the light-grey drop-shadow behind the question bubble, and tighten the radius as well.
You might want to look into css. You could align those four answer buttons with flex-box and have a lovely grid to make things look super crisp. If you're new to css then look at a Framework such as Bootstrap/Tailwinds.
And keep the hover-over of white for the buttons. No matter what button colour you go with, that's actually working as-is.
๐ Classic! Glad it worked out
I have 2 different model in django and I want to see data of model 2 using model 1 id how this can possible ?
Anyone good with Jinja2?
<div class="container content">
{% block content %}{% endblock %}
{% if self.content() == none %} {% include "other/soon.html" %} {% endif %}
So I load the content block, but I am trying to have it so if the content block is empty, it includes the specified html.
@csrf_exempt
def signup(request):
if request.method=='POST':
try:
data=JSONParser().parse(request)
form=RegisterForm(data.POST)
if form.is_valid():
form.save()
token = Token(user=form)
return JsonResponse({'token':str(token)},status=201)
except IntegrityError:
return JsonResponse({'error':'That username has already been taken. Please choose a new username'}, status=400)````
<title>ParseError
at /api/signup/</title>``` in post man
Hey Aryan, anychance you know about Jinja2?
im trying to create sign up functionality by django rest framework
umm ik it was a flask user before and jinja in flask and django is same so plz show me
I shared above, I am trying to say if the content block is empty, include a html page.
btw what's ur output rn
i noticed 1 thing here u ended block at the beggening
At the moment content block empty never evaluates as true
Also the content block is empty because it is filled on each page template, here is an example:
{% extends "layout.html" %}
{% block content %}
{% endblock content %}
That is the about page, where the content block should evaluate as empty
<div class="container content">
{% block content %}
{% if self.content() == none %}
{% include "other/soon.html" %}
{% else %}
<p> idk</p>
{% endif %}
{% endblock %}
```here i just showed a example 2 things to notice 1st put everything between block content and endblock content 2nd put endif in list after the else
hi any html snippet copy site
hmm best is tailwindcomponents , copy the cdn from tailwind css site + from the same cdn u can copy from tailblocks also
alright ty
umm
@lavish ferry
like this the if still doesn't evaluate as true:
<div class="container content">
{% block content %}
{% if self.content() is none %}
{% include "other/soon.html" %}
{% endif %}
{% endblock %}
When loading this page:
{% extends "layout.html" %}
{% block content %}
{% endblock content %}
ohh
I also tried == none
so u want if self.content() is none
and empty
can u know
i**
can i know what is self.content here
r u using backend?
can i see ur view for this (views.py func for this page)
So this is in the layout.html (for every page)
<div class="container content">
{% block content %}
{% if self.content() is none %}
{% include "other/soon.html" %}
{% endif %}
{% endblock %}
Then depending on the page I am loading, I extend the layout.html with the necessary html for that specific page. Take the about page, where I extend it with no HTML:
{% extends "layout.html" %}
{% block content %}
{% endblock content %}
I want some kind of expression such that if the block 'content' contains nothing, I include some HTML.
{% if self.content() is none %}
btw this is 101% incorrect
u just here need to type variable name
like u know backend? @lavish ferry
This is in Flask, though I just want to know what Jinja expression will work for this if it could?
This still evaluates as false always:
<div class="container content">
{% block content %}
{% if content is empty %}
{% include "other/soon.html" %}
{% endif %}
{% endblock %}
Happy to see an example
this works
u just need to write variable name
not self.content() == none
only see those 2 line which i holded from mouse
just write variable name
web framework handles this for us
I still don't get what the if statement expression should be?
show me ur query that flask code for this function(page)
@app.route("/about")
def about():
return render_template('other/about.html', title="About")
Renders this:
{% extends "layout.html" %}
{% block content %}
{% endblock content %}
Which extends the layout html, where this is:
<div class="container content">
{% block content %}
{% if content is empty %}
{% include "other/soon.html" %}
{% endif %}
{% endblock %}
where's the query what u want to fetch from the database here
The what? I don't have a database.
All I am trying to do, is if the person goes to a page which has a route I have defined, though I haven't added any content for that page, the page defaults to containing some html content that says I am not done yet.
umm just write that in ur html and why would u do that by jinja ;-;;--;-;
if else for and all are used while we work with databases
Surely I can somehow check if a content block is empty?
<div class="container content">
<--Your extends-->
{% block content %}
<--content-->
{% endblock %}```
just add random stuff to check like xyz and all or to let it be empty
<div class="container content">
{% block content %}
{% endblock %}```
done
lol
do not add anything
start and end it
same u have done in ur base.html or layout.html
That makes no sense.
Yes I have used Jinja2 plenty already
Your response to me asking if Jinja2 has a method to check if a content block is empty is what makes no sense.
This is the closest I found in all my Googling
https://stackoverflow.com/questions/18720899/how-can-i-determine-if-a-jinja2-template-block-is-empty
Yet no matter how I try implement this massively upvoted answer, it refuses to work as well.
If I do this:
<div class="container content">
{% block content %}
{% endblock %}
{% if self.content() %}
{% include "other/soon.html" %}
{% endif %}
It always evaluates as true
<div class="container content">
{% block content %}
{% endblock %}
{% if not self.content() | trim %}
{% include "other/soon.html" %}
{% endif %}
This works with the desired result
About time
Iโm building a little web app w flask rn and Iโm trying to learn how to use databases: Is it worth learning SQLAlchemy or should I just start learning MySQL?
A basic sql knowledge will take you a long way. Moreover its very easy, should take you just a weekend.
Oooh got it thanks. So that means I should learn MySQL since it uses raw sql rather than SQLAlchemy right
Guys if i'm using mongodb for django i have to setup the user thing and user authentication using mongodb right? The default user database cannot be used right
Can anyone help guide me on how to use django in vs code?
No i mean first learn sql then go to sql alchemy
They're both easy so won't be much of a hassle
Search youtube there are plenty of tutorials
alright also have been trying to activate a virtual environment in vs code for about 20 minutes now do you know how you are meant to do it by any chance?
Thanks for your help!
what os are you on?
Windows
does python work in your terminal?
yes
cool, so open the terminal in vs code in your project
then type:
python -m venv virtualenv
ok I will try that
after it's done, you activate the virtual environment by this command:
virtualenv/scripts/activate
if this works correctly, you will see something like (virtualenv) in your terminal
wait ill dm you it shows some error
i disabled DMs
Sounds like it is an easy fix then. Just a question of how to enable it.
You are an administrator on the computer right?
yea
just copy paste the first few lines on google
its a pretty common problem
Set-ExecutionPolicy RemoteSigned
youll find the solution
running powershell as admin and run that
Ignis you are correct by why shit on a discussion where they are already being helped
just trying to help man, no need to be rude XD
giving me another error
open powershell as admin first for it to work
ok
I don't think it was worded in a rude way at all. Though you don't really help someone by telling them to help themselves. For all we know they have already tried that for an hour or two.
yeah all cool, i wont do that then
I have opened powershell
as admin'
try that command i sent
thats what I get
A
but nothing happened
cool, now try activating the virtualenv again
cool
Thank you for helping me!
Do I have to that every time I want to activate a venv then?
Thanks for the lesson as well Droid! I was wondering how to do this. Is VSCode smart and remembers virtual environments for projects? Or do you need to activate each time.
Lol
the python extension by microsoft sometimes activates the virtual environment automatically if it detects it, but that's not always the case, so you'll probably have to activate it manually,
just run /virtualenv/scripts/activate etc, or you can create a script to do this for you and just run that
Alright, Thanks again for your help I appreciate it.
np
Do you know how to clone a github doc on vs code as well?
.. plz
'
or you can just use your terminal, if you have git installed, and type: git clone url
I dont have those options?
maybe your account not set up, i'm not sure
alright thanks
https://www.jcchouinard.com/install-git-in-vscode/ maybe this might be helpful
Cool, thanks
I was able to set it up and it now works, thanks for your help once again!
@csrf_exempt
def signup(request):
if request.method=='POST':
try:
data=JSONParser().parse(request)
form=RegisterForm(data.POST)
if form.is_valid():
form.save()
token = Token(user=form)
return JsonResponse({'token':str(token)},status=201)
except IntegrityError:
return JsonResponse({'error':'That username has already been taken. Please choose a new username'}, status=400)```
@dusk portal You've been here long enough to know to ask better questions about what problem you're having.
Yes
I'm here from
When I started to code
And promised myself that I will help everyone and will take help from everyone by teasing and being weird idc
But I will take help and give help to everyone
seriously, what's the difference between get and post requests if I can just replace the post function in my python code with headers and body with a get and it still works in Postman?
Are u working with rest api's?
yup
they say that get is to "get" data from the server while post is to update data but I see my code works with either of those functions.
so why do they even exist separately?
Umm nice question and I have a better answer
@random finch
Ohk u r here I'm answering
Just forget about APIs and all for a sec
Thats like saying why don't we get rid of the word "run" since its just "walk" but faster? So POST exists to make it easier to work with apis. Get rid of all the extra headers you talked about. Btw you can create your own verbs.
Now imagine u are in a website with a button named contact
When u click on that u receive the html code and response that is get request as name tells get
Which gets the data
And then u see a form there and then u fill it in left bottom corner u will se something and the page reloads as it sends the post request
So when we visit any site by our chrome or default browser it sends a get request to get the page and then if u fill any field it sends the post request
So the reason we use postman and all is in that we have to open the page in POST request but our browser opens in get request and error comes there
@random finch
One more good example is imagine u r making a simple contact page u write def contact and if request.method == POST
Before the if loop iteration u have to pass any render(html page) else it shows No response /Null
So if it renders the page then as our form uses the function method name and all the things so form sends the post req and form in submitted else in api u don't render any page or any response outside the loop
All my exp about this packed
For u
I'm still confused @dusk portal but appreciate the effort. Are you saying browsers can't handle post requests?
Yes when u submit form it handles post request browser handle get requests
If the POST request does not have any headers or body, wouldn't the browser be able to handle it?
Like. R u saying method =POST and action
If not nope it cannot it will throw error
I was having same problems
Just work
Just work
See JustDjango ytber playlist and one more guy have some 12-13 vids see that and Udemy course
I'm just developing basic REST APIs at the moment, nothing like site building or anything
The reason why the get and post are seperate is get shouldn't affect the data on the database.
And yes we can use get for all operation instead of post. But generally we shouldn't use get for the which can be done by post. In certain cases u might want to block some requests like post or delete in such cases if you have used get then you have to write logics manually to block some of the requests.
Or if u have used post then it is very easy to block post requests.
IT'S LIKE ROAD RULES, WE CAN GO LEFT SIDE OR RIGHT SIDE OF LANE WITHOUT FOLLOWING RULES BUT IF WE FOLLOW GENERAL RULE OUR LIFE IS EASIER TO SOLVE PROBLEMS
So to sum it all up, when to use GET and POST are just defined based on conventions, but in theory, we could write code and assign either of it to call the code right?
Hi there, wondering if someone could help me (can post relevent code when asked, im not entirely sure which parts are relevent). im working with django atm, trying to use {% block <name> %}. whenever i do, i get server error 500. it works if i just write plain html, but when trying to include django stuff, it errors
Yes, but you shouldn't as the app might have a chance to be hacked due to the network layer logics
What error you are seeing?
just fixed it, turns out im stupid as hell, wrote extend instead of extends and end block instead of endblock
Sry, probably just me being a noob, but why can't I webscrape <table class="accuracy_stats" ?
I am using py soup_text.find_all('table', attrs={'class':'accuracy__stats'}) To search, and it doesn't find anything ๐
probably dynamic data, just a guess
Huh, for context I am trying to get the Player Accuracy stats from a website. Anyways, any suggestions on how could I still get the data I want?
try selenium
beautiful soup scraps the html content it sees. i'm assuming this website was made with a framework (since there's a data-v-... attribute) like react or vue. basically, these frameworks don't put all the content into html files,. the content is appended into an element with the id #app for example, using javascript, hence the data is dynamically loaded in a sense
Alright, I'll look into it. Thank you very much!
..
You don't even ask a question.
that;s a big question im trying to make sign up functionality by django rest framework but after user is created it should create a token and ofc it can't be done in our browser so trying to do that with postman but it's showing error
code ^^
this is the code
error in postman
So how did you try debugging it so far? Did you print data?
Hello Python Army, Hope you all are doing well. Anyone wants to learn Django as a pair programming? I have started to learn Django. anyone wants to join me?
class UserProfileInfo(models.Model):
user = models.OneToOneField(User, on_delete=CASCADE)
why do we do this?
Do what?
user = models.OneToOneField(User, on_delete=CASCADE) creating a OnetoOne field
OneToOneField
This is most useful as the primary key of a model which extends another model in some way. A one-to-one relationship. Conceptually, this is similar to a ForeignKey with unique=True, but the "reverse" side of the relation will directly return a single object.
the User class already has a functionality to store usernames right? so when do we use this user = models.OneToOneField(User, on_delete=CASCADE) and why?
Because you don't usually want to bloat one table to with a huge amount of data. So you can extend the model by having smaller tables you can reference as needed.
My guess is that this is less important now with frameworks like GraphQL where you can be more selective about the data you ask for, but still good practice not to bloat single models.
oh, thank you
@nova pewter However in this case, you use OneToOne or a ForeignKey to tell this model that you want to get the data based on the user described in your ForeignKey.
This way you have the user object available to use when you reference the other model, rather than just a username or id, for example.
i see
i am trying to figure out what's wrong in my code and couldn't find the problem as there is no error, so i am walking through the whole code rn
What's the goal and issue you're seeing?
you can be totally selective what you request in SQL, how much fields you query ;b
i have it posted up here wait i'll point out the issue to you
But what if you search for a user with id=1 in Django. You'll get the entire model, not just a part of it.
even if you only want one piece
GraphQL replaces REST model of the standard you interact with API
behind this model can be the same SQL database in both cases
this
..
Aha, so if I am selective in GQL, am I still making the same request as if I queried the model directly? What is the benefit of GQL in this case.
I know that I only get back what I ask for, but is the request load the same?
less messy system than when your API has too many url end points, and too many fields in its data
Ok I see, so just a more organized way to request data vs REST
I guess so
Or more efficient.
smh when i try to login with the superadmin that i created from manage.py i am able to login and the user=authenticate() method is working fine, but when i try to login with the custom user that i created i get user as "none"
are you setting is_active to true upon creating the user?
yes i checked it inside the admin panel, is active is checked
i tried printing user_name and pass_word and it is giving the correct output
do you get invalid credentials when logging in with it?
or just nothing and refreshes the login page
i get this ``` else:
print("someone tried to login and failed")
print('username:{} and password :{}'.format(username, password))
return HttpResponse("invalid login details supplied")
but what happens when you actually login in, on the admin login page (or whatever page you're loggin in)
"invalid login details supplied"
right ok
if i log in with the superuser i am able to log in
I know there's an issue if you don't hash the password as well. Did you check the DB is the pw is hashed or plaintext?
hashed
And for sure is_active?
yeah
can you print the contents of the user model that's being logged in and show the results?
1 sec
I don't see you setting is_active in reg. can you add user.is_active=true to your registration?
like this? ``` if user_form.is_valid() and profile_form.is_valid():
user = user_form.save()
user.set_password(user.password)
user.is_active = True
user.save()
right
But I realize that probably won't change anything since I'm not sure why you're getting none as your user when you log in.
Your authenticate function is returning none or it does return a user?
it is returning none when i pass in a user that i created
but when i pass in the superuser, it doesn't return none
user_name and pass_word are correct with the normal user? @nova pewter
any reason one should not have unique name/title field on product model for an ecommerce website?
More random questions from me lol if I have a flask application rendering a template that imports a python value when it renders the value of the import is the value of whatever I'm importing at the time. If the value is something that is constantly updating can I use JavaScript to then change the values as they update or does the render mean the value will always be set?
Y u can
Render makes initial state. Everything after that is a fair play for javascript
Or for additional... something like post submit requests
U can make requests with js, or using web sockets for constant stream of information
The python code is constantly checking/updating a value and when rendered what ever value it is, is rendered but I can't seem to get the js to take any of the updated values without crashing the page
After the render is rendered the values stop updating but I think that's because of how my loop is set up and if I take the render out the loop the page never loads
hey guys wanted to ask which framework b/w Flask and Django should I use to combine it with React for a web app. THanks
Whatever suits your needs.
Cheers bro
sorry, I'm dumb and I can't explain properly. How can I add a set of values, to an existing model in the db through views
That's basically the main basic functionality of a python web framework.
So you should probably check out a basic tutorial and it will walk you through that.
Question
How to add preview to your website link?
Purpose
When I share the link, I want this to have an specific image preview of the website
Canโt you just give me an example, cos I never go through all of the basic stuff, because it wastes all the time, and thatโs why I probably donโt know this
No, not really. It's quite a number of steps to get that functionality working and tutorials have been created so many times that it would be literally faster to just find one of those.
I can tell you that you put information in a form (usually) that, after you submit it, it goes through an url/route that points at your view that then does the database work you tell it to do.
Why do you need an example if you don't want to learn it?
use an iframe
Do you mean the previews shown on discord WhatsApp etc? They use something called open graph meta tags to do it. Pretty easy to use.
oops, i read that wrong
Cos I self learn from examples maybe?
You want someone to teach you something for free?
Good luck
Tutorials, examples, videos, articles, etc. do that, donโt they? ๐ค
Not on discord
This server sometimes spoils people
Hello Guys, what's the best way to build a websocket for example for google maps? Do you advice me to install a library or I can do it with import socket? Can I use the library requests for websockets? If I can't which library is the most used?
:c
That question is actually much bigger than appears on the surface. I've heard of things like REST frameworks to get at the DB through Django. For my part, I went through a number of tutorials learning how to...as I like to put it...dance with the Django DB.
The reason why this is a huge question with many answers is because you're actually asking (as I see it) how to use the application layer to access (CRUD) the DB layer, and in turn prepare the context dictionary (in Django at least) for the presentation layer.
Understanding this is actually at the heart of what (from what my 1.5 months of experience with Django) is showing me is the difference between a static one-way (information push) site, to a dynamic two-way (pull-push information site). I'm currently building a process improvement project management web application, and I can tell you first hand I'm likely over 100 hours learning, experimenting with, and expanding my understanding of how to dance with the DB in Django. And I know it's not done there. I have much more to learn (and I've got React/JS to learn yet to build another app within this web application)...
I apologize for the long response, but the challenge with your question is that it actually is valid to answer with the suggestion that you research, and learn. I too learn through examples, but such a broad question is not IMHO a good question. Coming forward with a specific question about how to take a step in learning how to dance with the Django DB would be very helpful. Frame the question with what you're aiming to accomplish, what behaviour you already have, and what you've tried to get there. Then, as someone responding to your question we are both saved time because I don't repeat what you've already tried, and your stated expectation guides me.
I shall give an example. Yesterday, I realized that with the potential for 1,000s of Process Improvement Projects for a higher-tier subscriber I needed a way to filter on the dashboard (and there is no way a lazy single search will cut it). However, I needed to be able to filter projects by Organization, Team and Process. I managed to answer this question for myself. However, had I come to this Discord I might have posed the following as a question.
Goal: I would like to filter across a DB table/model looking at three different fields in four different tables.
So far: I have managed to filter by one attribute. However, when I try to add more I get multiple returns.
What I was doing at the time was actually adding multiple submit buttons for the form. This was creating the problem.
End result...
all this makes sense, but why did the other guy have to say, that it was all basic stuff in the first place, and then afterwards, literally saying the complete opposite of his words, and that it's much easier for me to go learn myself from tutorials etc
I just don't see the logic, you know
And I don't think that my question was asked poorly, because I quite literally want to learn, how I can write info to the created models in the database, through the actual program/code, and not just through the admin console or the django shell
I can only speak for myself. One thing I've learned is that technical brilliance in programming/developing doesn't guarantee that I can communicate myself clearly. This Discord is an AMAZING community of volunteers.
We can agree to disagree. Your question is huge in scope. It's asking about how to dance between DB, Application and front-end layers. The challenge is that there are many ways to answer it. The reason I feel it was a poor question is that you've not given me a concrete expectation, what is happening or what you've tried.
You want to learn. I want to help you. However, I don't want to engage in a question where I don't even know the specifics of what you're expecting, AND where you've shown no effort to apply yourself in learning the concept.
well, idk, I guess I might just go learn it myself
anyways, thanks for the replies
That's the life of a programmer. ๐
Go and get lost in the concepts....get clear on a small thing that you're stuck on you'd like to accomplish on that journey, and then come back here with a specific question with your expectation, what's happening and what you've tried. I'll guarantee you it will be well received. And if I'm around and can help I will. ๐
Tutorials are exactly that. Examples.
Yes that's exactly it, @ionic raft . The best help is to help you understand how to find the solution, not just give it to you. That way you get to the solution, but more importantly you learn how to figure things out on your own. That's one of the hardest things to learn.
That, or, if you have at least attempted a solution and are stuck, we can help you debug that for sure. @glacial yoke
My greatest growth as someone 4 months into Python and 1.5 months in Django has come from being pushed to solve problems for myself. My experience yesterday, solving a problem I've never really seen implemented (and that there certainly is no tutorial for), came directly from getting better at solving problems myself. I believe the defining difference between a beginner programmer and an intermediate one is that you can generally find most solutions yourself. Sometimes, you have to work with a snippet from Stack Overflow. Other times, you make an abstract leap from a previously applied pattern or concept. However, the beauty of the philosophy of support in this volunteer community is that we're teaching a man how to fish. These past few weeks I've never gone hungry.
Sorry for the late reply. Yes, I send the link to someone and it displays an image
yes
Ever figure out the issue? That's a weird one. Almost as if your authentication function is messed up, but I'm guessing you haven't modified that?
took a break for a while , gonna try to fix it after an hour or so
Let me know if you make progress! I'm genuinely curious.
sure
Feel for you. Those weird errors are scary, particularly when they're super obscure and there's not much reference on them!
Good luck. Also curious...
yeah usually when i get a error i am happy because i know what to lookup on if i want to fix it
last time i didn't get any error and spent like 5 hrs fixing the issue, turned out it was a small mistake in the html XD
Bruh, can SO relate! ๐
its fun tho when it gets fixed!
Like when you refactor a field, but the refactor didn't make it to every field and it's naming.
Yes, the reward is in the fixing. The journey is in the persevering.
๐
hi, i have a problem to deploy a app
my app is a api rest
simple but i dont can deploy to heroku
I'm not sure if this is the place to ask about this.
https://www.youtube.com/watch?v=WMXWksdBhD0 (Skip to 18 seconds)
I was wondering what tool can be used to do this? Like I want text in the middle of the screen in a box, all blurred and have a small box go across each line unblurring so you can read the next inside the small box.
So I'm using django with my css file in /static/my_app/main.css and when I alter the css file it doesn't actually change the styling. Is there a way to use the edited css instead of the old file?
restarting the server didn't even work ๐
did you collectstatic?
No I did not. The django-admin command?
python manage.py collectstatic
Depending how it's setup sometimes you need to do that to refresh anything used in your static folder.
I added STATIC_ROOT = BASE_DIR / 'static' to my settings.py file and ran collectstatic but it's still using the old css values. Should STATIC_ROOT point to the app that contains the static file?
nevermind it was browser related. Thank you @dense slate
Hey, I have question regarding nodejs. I have a web server and I need to call function in javascript file. I assume that it should be done using websockets like socket.io but I have no clue how, would really appreciate a help since only thing that I can find is how to call server sided function from javascript which is completely opposite from what I need.
you may have better luck with that question on a node server? this may be #web-development but its still python web development ๐
not that I'm saying its ot, but more you're looking for a backend answer with a language that likely has less followers here than a node specific server
Bet, thank you
what does this mean?
So you need to call Javascript on the client side?
What do you actually need?
I have nodejs web server. And I need to call javascript client-sided function
So you have a website?
What do you mean by client side here?
I have a nodejs web server (thats server-side) and I need to call function from Javascript file (client-sided). I know that it can be done using websockets but idk how
Where is the Javascript file? Is it stored on the user's computer?
If so you don't need websockets thats would be an overkill
Yessir
What type of application are you trying to make?
I already have an application.
What it basically does is - check what is result of form once it's submitted, send it to server (node) and it makes a request to api on another site with data from the form, and it should call something on client-side upon the result of request.
(The request can't be done on client-side so I need to route it like this)
Isn't that too hard?
anyone?
I have never made an API so
Apis are waaaaaay easier than websockets
Websockets are just a pandoras box of difficulties waiting to be opened imo
Teach me! ๐
Lmao
Use some tutorial online for your nodejs server
I need to make an Rest API right?
there are other options too. Graphql, SOAP etc. but ReST would be the easiest by far.
Ight, thanks for help kind sir!
I found this which is really simple, but I don't really understand how to call client-sided function using it
(Screenshot from video, sorry for quality lmao)
This could be used to call server-sided actions from JavaScript, but I need the exact opposite
Need a bit of help
I'm new to DigitalOcean. Cloned my django project to my django droplet and pointed gurnicore to it. This is what I get now
Am I missing something? (Probably)
In mongodb if i have set the username and password for a database do i need to specify it when using MongoClient(...) ?
Hey, I have question regarding nodejs. I have a web server and I need to call function in javascript file. I assume that it should be done using websockets like socket.io but I have no clue how, would really appreciate a help since only thing that I can find is how to call server sided function from javascript which is completely opposite from what I need.
Sending message again since I still haven't found a solution, I heard that it can also be solved by creating an simple API but I don't know how to make the API to call the client-sided function so
What do you really mean by calling client sided functions? Where are these functions coming from?
From javascript file, not from nodejs.
I need to change front-end
What does that even mean?
Where are you getting this file from?
It sounds like they basically need the client to do something in response to an event on the server.
Websockets and SSE are ways to do that.
Though it'd be a good idea to elaborate so you can be really sure you need to architect it like this in the first place.
heyy
so im messing around with some html for an amazon webpage
and i get here, and the value is assigned to nothing
any idea why?
proably some js associated with it that removed the value
im running my flask app
but when i go to 127.0.0.1:3000 it doesn't load
it worked fine yesterday
and now today it doesnt work for some reason
or run and try to open on the browser
did
im so confused
what the hell
if i run it in powershell
it works
if i run it in my WSL bash
it doesnt work
huhhh
How should i get _id of mongodb in django cuz when i type user._id it says variable cannot start with underscore
why r django channels used, do any1 have good resouces to learn them and tips to be good at django channels
WSL ports are not exposed to your host machine. You'll have to do it explicitly.
i fixed it by rebooting
so idk
Yeah maybe wsl forwards them automatically
Haven't used it for a long time, so maybe there were some changes
Any kind of application where you need a long polling connection to the server. So chat apps, gps navigation systems etc
umm docs of it are RIP
Yeah that's true
They're very complicated
Can't do anything about it though ๐คทโโ๏ธ
anyone with django rest framework experience available?
I'm trying to make a login request that when you give it the information..
1 - the cookies are set automatically with the .set_cookie() function
2 - returns the username and the user id
I have managed to do the first one but the second one is not working with me
it's either that..
1 - the user is not serialized
2 - the keywords are not right
3 - get_queryset for the user inside the cookie view doesn't work
4 - if I try to serialize the data, it attempts to create a user rather than serializing my user
class CookieTokenObtainPairView(TokenObtainPairView):
def finalize_response(self, request, response, *args, **kwargs):
#the section that sets the cookies
user = # Function that get's me the user serialized
response.data["user"] = user.data if user.is_valid() else user.errors
return super().finalize_response(request, response, *args, **kwargs)
what should I put in the user= to give me the user serialized, the user serializer class is called UserSerializer
started working on a drf and react.js project with very little experience for a code jam, lets see how this goes
more specifically, what function should I add to the serializer class so that if I call the UserSerializer(...) it returns to me the user data and not attempt to create a user
Just extend the class and add your own functionality to return the user information you'd like. Also make sure to drop the serializer in chat.
class UserSerializer(serializers.HyperlinkedModelSerializer):
password = serializers.CharField(style={"input type": "password"}, write_only=True)
class Meta:
model = User
fields = (
"id",
"url",
"username",
"email",
"password",
"groups",
"is_staff",
"is_active",
"last_login",
"date_joined",
)
read_only_fields = ("id", "is_staff", "is_active", "last_login", "date_joined")
def create(self, validated_data):
if User.objects.filter(email=validated_data["email"]).exists():
raise Ve("this email has already been used")
user = User.objects.create(
username=validated_data["username"], email=validated_data["email"]
)
user.set_password(validated_data["password"])
user.save()
return user
so I have a create function but I don't know how to make some sort of get function. searched in the drf docs didn't find such a thing
extend what class specifically?
You may want a separate serializer for obtaining the token. However, a "get" would be done kinda like this:
def validate(self, attrs):
attrs = super().validate(attrs)
attrs["id"] = self.user.id
attrs["first_name"] = self.user.first_name
attrs["last_name"] = self.user.last_name
attrs["email"] = f"{self.user.email}"
attrs["role"] = "Admin" if self.user.is_superuser else "User"
return attrs
and how would I call this in the views?
you create the serializer, provide the data and then call the is_valid() function
def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data=self.request.data)
try:
serializer.is_valid(raise_exception=True)
except Exception:
return response.Response(
"No active account found with the given credentials",
status=status.HTTP_400_BAD_REQUEST,
)
If you're not using a generic view then you would just call the serializer directly and provide the same values
so like UserSerializer(data=self.request.data) ?
You got it
neat! thanks
No problem. Hope this helps
one issue, when I call the serializer it stills attempts to create a user, should I type UserSerailzer.validate(data=self.request.data) ?
Like I said you'll probably want to create a separate serializer for it. But yeah, you need to provide the arguments.
{
"user": {
"username": [
"A user with that username already exists."
]
}
}
this is what returns, which is an exception in the create function
I would create a separate serializer there again
ok seems like the solution is a separate serializer, I'll try to do it thanks again
No one seems to know in help channels, so I'll hop into questions train if I may.. ๐ฅบ
I'm making Django REST API app for books.
I want to be able to do GET /books/?authors=Tolkien.
Problem is authors is a list:
{
"id": "1",
"authors": [
"Tolkien" # <- I want to filter for this
]
}```
If it was in form of `"author": "Tolkien"`, then this would work:
```python
author = self.request.query_params.get('author')
queryset = queryset.filter(author=author)```
but it's nested in a list, since it can be many authors.
Do you maybe know how can I access this list?
queryset= yourModel.objects.filter(author=author)
Just to clarify do you mean it's a list of authors (strings)? Or it's literally an infinite nested list with a matrix of lists?
Book dict in JSON has "authors" parameter which is a list of authors. Can have 1 or more name strings inside.
Alright so use the ORM to your advantage and just provide the list
so
queryset.filter(author__in=author)
shouldn't he use the model objects?
Not if he is using a generic view
the model would be globally accessible within the class
using viewsets.ModelViewSet
nice
and I tried this and doesn't work ๐ฆ
You have to use custom filterset I think
then try the queryset.objects...
there is no author model, I only have Book model with "authors" list field (JSONField)
btw can I ask what does the __in do exactly?
Oh. Well that's a bit odd to do. Why wouldn't you create a many to many relationship?
Also what DB as that does make a difference with JSONField
I'm new and don't know much about it. Would creating authors model fix it easily?
DB is Djangos basic, so SQLite3 I suppose, python 3.9 so JSONField works out of the box
So do you want to filter by multiple autors like this: /books/?authors=Tolkien,King,..
I want to filter just by one author for now, but the author in database is in a list, like this:
"authors": ["Tolkien"]```
are you trying to search books with the author query?
Well it should be a field that you're querying against. For example, the name of an author. The in just says if any rows column (name) in the table matches an item (name) in this list then return it
class books(viewsets.ModelViewSet):
queryset = Book.objects.all()
serializer_class = BookSerializer
search_fields = ["author"]
filter_backends = (filters.SearchFilter,)
permission_classes = [permissions.IsAuthenticated]
all I want to do is just a basic query for books written by author X, the problem is, the author of the book inside JSON is in a list
use the search_fields and filter_backends
if you just go to /books/ you'll get all
if you /books/?author=... it will search
If you dont know what web developement is then let me explain it simple for you:
don't forget to import the filters function from rest_framework
basically its developing the web, yeah, you're welcome
?
you can add more stuff in the search fields so you don't need to filter the queryset yourself
doesn't seem to work
shows me entire db
wait, doesn't work for simple id too, so maybe I implemented it wrong
it's just about importing filters and adding
search_fields = ["author"]
filter_backends = (filters.SearchFilter,)```
below serializer_class?
yea
then somehow I managed to make it not working ๐
why did you add id?
at first I tried with authors but didn't work, so I added id so I can try querying for not embeeded thing
i am learning python
"id" only doesn't work for looking for certain ids too
oh right lol
https://medium.com/swlh/searching-in-django-rest-framework-45aad62e7782 this is the article I learned this from
give it a read you might find why it's not working with you
tag me if you found out why it's not working 
@wraith cypress hey I know why I didn't make your proposition work:
i was doing /books/?id=xxxxx and it should be /books/?search=xxxxx
i used "search" parameter and it works now, but it's not what I need: I need searching with /books/?authors=Tolkien way
so SearchFilter doesn't seem to do it for me. I'll try ronek22 suggestion now and try to implement custom filterset, I think I have an idea about how to make it work
then, if failure, I'll go for Magic's suggestion about many-to-many relationships. Thanks everyone!
I really appreciate your time ๐
your welcome, I just want to add that the manytomany relations is generally better practice so I'd suggest you read this https://stackoverflow.com/questions/25386119/whats-the-difference-between-a-onetoone-manytomany-and-a-foreignkey-field-in-d
but for books you may not need to make an author model for each and every writer so you can use the normal search in json fields
chattting
Anyone recommend what's better with full stack development like Ruby, React.js ?
What's the best and easiest ?
ruby and react js are two different things.
you should choose between reactjs and vuejs since they are now the top web frameworks with future
reactjs is the most famous so you will find a lot of libraries and tutorials
vuejs is the better choice since it's easier and has a very easy to understand documentation and cheat sheet, but less famous so less jobs
for backend development it's either nodejs or flask or django imo
nodejs for if you want to be full stack javascript
flask is for the more simple backends
django is fully loaded with libraries and options and is an easy go-to for a python programmer that wants to go into making good backend servers
now since you are here I'd suggest you start with flask to understand how backends work then switch to django
have created model here but when i run makemigrations i get no migrations to apply wt may be the reason?
and for frontend it deppends, do you want to make better websites with less libraries and less jobs go for vue
if you primarily focus on jobs go for react
how can i add an image to an ImageField after save it (django 3.2)
there is a library for image serving you should research for it
show me what happens when you type the command makemigrations
type in the app name after makemigrations
yes i already did this
but
class Media(models.Model):
name = models.CharField(max_length=255,)
file = models.FileField(null=True, blank=True)
preview = models.ImageField(null=True, blank=True)
category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True)
plan = models.ForeignKey(Plan, on_delete=models.SET_NULL, null=True)
def __str__(self):
return self.name
def update_image(sender, instance, created, *args, **kwargs):
instance.preview = create_preview(instance.file.name, instance.name) #this function return the path of the image
instance.save()
post_save.connect(update_image, sender=Media)
updates?
i created a function that creates the video preview, and i save it in the same folder with the video
i just need to add the path to the Imagefield
thats where im stuck
did you apply the routes in the settings?
@wraith cypress that worked thanks actually, the model was outside the app i just moved in to check is that how it should work?
Your models.py file looks to be in the same directory as the settings.py file....
sometimes if the makemigrations doesn't work you should specify where are the changes
u can just delete the migratiosn folder and pycache then re do makemigrations, this would fix too
yes he should add models and other stuff on another app, the one above maybe or create another one
so let me explain to you how django works, every app contains it's views, urls, and models
but every project has a base file that contains the main urls, settings, wsgi/asgi
so making models in your base file is not a good idea, you should create an app for every major function in your database like posts, users, services etc
idk as im just learning. i found that after creating app the settings.py moves inside the app is that for any reason ? or am i wrong
yes
nOW CAN SOMEONE please help with that ImGEfield grrrr ๐ข
check the link I sent...
yes
not just the pillow part
at first the model was outside my app and got same message what to do in trhat case
what is the main issue?
does anyone know how to use discord oauth2 w django
allauth
how do you have a model outside an app, nothing should get out of your app
okay ill remember this
just remember to split your projects to apps and keep the main file only for the main stuff
the code keep looping cause what im giving doesnt corrispond to what he asks
in models
how..
wait
do i need any custom user model for that?
no, allauth has custom user models built in
oh that makes shit much easier
although depends on your needs you might need to create your own but for as long as I used it I never needed to
yea yea you're good with the built in
also, will allauth save my access and refresh token or do i gotta do that myself?
django is the one that takes care of this
oh
what allauth does is create a normal user just like any django user but you have a custom user model for allauth specific models
ohh
if you are making it in a restful framework you will need .set_cookie to set the cookies but otherwise you are ok
welcome
https://stackoverflow.com/questions/39639264/django-highlight-current-page-in-navbar
check the accepted solution. can i somehow use the url name with namespace ?
@wraith cypress I made authors filtering work with custom filter, I just made one inheriting from SearchFilter and changed search_param to "authors" instead of "search" ๐
Thanks again! Also to ronek22 and Magic ofc ๐
welcome, and thanks you teached me about search_param!
you have to check your views
def get(url):
html = requests.get(url)
soup = bs4.BeautifulSoup(html.content, "html.parser")
return soup.find_all(class_='base-search-card__info')
get('https://ca.linkedin.com/jobs/search?keywords=python&location=Canada&geoId=101174742&trk=public_jobs_jobs-search-bar_search-submit¤tJobId=2687992426&position=1&pageNum=0')```
hi, does anyone know why this is not returning anything??? ๐
ummm, no, im trying intergrade this into flask, so its just web scraping im making rn
but it returns none for some reasons
I don't have experience with beautiful soup, I prefer selenium
though I'm interested on why it's not returning
although my app will take in huge amount of data from internet, im not sure can my laptop run that with selenium
wait, as long as i dont do any input or any action, it wont overload right?
like this app only take a peek of the data and add into a dict
umm pretty much overloading needs to be loaded a lot
well, i can set a range for every hour, like take in slowly
and store them into a cache
also you are not hosting this app on your laptop to hundreds of users
so if you host it on a provider it should handle requests well
make sure requests are asynchronous
i will try use selenium