#web-development
2 messages ยท Page 164 of 1
so in my html code
<!DOCTYPE html>
<html lang="en">
<head>
<title>Login</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="{{ url_for('static', filename='css/bootstrap.min.css') }}" rel="stylesheet">
</head>
<body>
</body>
</html>```
what should i add/ change to make it look something like this?
@native tide bootstrap provides utility classes for your elements.
You can press on elements in your theme to see its source code.
right on
Hello , is it possible to use save_file when using fetch()??
i'm trying to find something about this type of search, search by category, but i only find simple things like search by name, someone know where i can find content about how to do a thing like this?
so i tried to do this
however if i let the href = "" visit the website it works
but if i download that websites css file and then run it from a folder it doesn't work
@native tide that href to the stylesheet is relative to the html file. It seems that you have an incorrect path to your css file, maybe try absolute paths?
what do you mean?
by absolute paths?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>AI Cosmos Research Engine</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://bootswatch.com/5/cyborg/bootstrap.css" rel="stylesheet">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-search" viewBox="0 0 16 16">
<path d="M11.742 10.344a6.5 6.5 0 1 0-1.397 1.398h-.001c.03.04.062.078.098.115l3.85 3.85a1 1 0 0 0 1.415-1.414l-3.85-3.85a1.007 1.007 0 0 0-.115-.1zM12 6.5a5.5 5.5 0 1 1-11 0 5.5 5.5 0 0 1 11 0z"/>
</svg>
</head>
</html>```
also <svg..></svg>
how do i put it on the shortcut icon
They are just different attributes or categories. You would use each input as a filter to search your data.
@short wavehit your brother up when u finish that :3 lemme make some profit too
If you are unsure just search it up.
@native tide What's the question? Ask it, instead of asking to ask.
'Image' object has no attribute '_committed' WTF?
yo guys im using django and have this form
form action="{% url 'answer' question.pk %}" method='POST'
the url for answer is path('answer', views.new_answer, name='answer')
but when i submit he form
the url that is shows is question/answer/<int:pk>
so why is this happening?
you give an argument of question.pk, so it's probably appended to the end of the url even though you might not want to
it's an arbitrary html tag that serves no base purpose but is useful for organization. <br> is for new lines
still not working @wooden ruin :(
wdym by not working?
Hey, I'm a beginner and trying to implement bid system in Django. I want it to work on both Django admin page and and template, therefore I created modelform and modeladmin in Admin.py. I'll send the code.
This is the snippet of models.py
class bid(models.Model):
listing = models.ForeignKey('listing', on_delete=models.CASCADE)
user = models.ForeignKey(User, null=True, on_delete=models.CASCADE)
bid = models.DecimalField(max_digits=6, null=True, decimal_places=2)
def __str__(self):
return f"{self.user}, {self.listing} {self.bid}"
class listing(models.Model):
user = models.ForeignKey(User, null=True, on_delete=models.CASCADE)
Title = models.CharField(max_length=50)
Description = models.CharField(max_length=300)
Price = models.DecimalField(max_digits=6, null=True, decimal_places=2)
category = models.ForeignKey(category, on_delete=models.CASCADE, related_name="categories")
def __str__(self):
return f"{self.Title}"
This is admin.py:
class bidForm(forms.ModelForm):
class Meta:
model=bid
fields = ['user', 'listing', 'bid']
def clean(self):
start_price = bid.listing.Price
userbid = self.cleaned_data.get('bid')
if userbid <= start_price:
raise ValidationError('Please place a bid higher than starting price')
return self.cleaned_data
class bidAdmin(admin.ModelAdmin):
form = bidForm
list_display = ('user', 'listing', 'bid')
admin.site.register(bid, bidAdmin)
start_price = bid.listing.Price This line is the problem
"Price" is an instance of the "listing" foreignkey in bids. I haven't managed to compare it to the bid I'm making in the modelform correctly, please help me on this regard...
bid system?
what does that mean
o i see
so first the model
The model looks good
I'm working on a commerce website. I want user to bid on a product from the template as well as from the admin page.
ok
so for the admin site
you don't need to do anything weird
admin.site.register(YourModelHere)
first import themodel tho
ok
In this snippet
well that is not very close to django principles
you should make a forms.py in your app
and put forms in there
what is it
why are most python builtins functions blank except for comment when I try to inspect them? is it because they're not written in python?
no they arent
they are written in c
So you're telling me not to do so that admin can make bids from the admin page?
That's what I thought, I wanted to have confirmation. Why is it just comments and "pass" and no reference to C?
the admins can access the admin site
where if you register models with admin.site.register
the admins can delete, add, and update all records
Yes, but
they would also be able to do everything from the main site
since whatever a normal joe schmo can do an admin can do too
i don't understand ur question
Sorry... Let me elaborate a bit
So I'm following the correct basic concept in my code right? I mean validations from admin interface and etc.
Custom admin form validation isn't a bad idea right?
I'm still learning a lot of things so I might get confused. So far everything is clear. I'll create forms.py first.
cool
so in forms.py you just move the code from admin.py
I just want to display this tags according to the user logged in
<li><a class="dropdown-item" href="{% url 'edit_prof' %}">EDIT PROFILE</a></li>
<li><a class="dropdown-item" href="{% url 'edit_prof'_eng %}">EDIT PROFILE</a></li>
class ListingForm(forms.ModelForm):
class Meta:
# stuff
use an if statement
{% if user.is_authenticated %}
I know if else
I have done work in Flask
And doing nice in django just facing some issues with docs (as I'm new in docs)
One thing my mind says now is "You can't make anything of ur own in django u just know what to how and what's in docs
Btw i have done 5 pages of docs ig 10-10 times and Learned those stuff properly so what should i do continue with docs or leave it
this will return true if the user is logged in
but there is an logical error
ok lemme show u
@twin hamlet kya hua(how can i help)?
Thanks so much for tips ๐ญ
There are two diff users bro
{% if user.is_authenticated %}
<!--For if user is logged in-->
{% else %}
<!--For if user is not logged in-->
{% endif %}
ik
you can access the user by just calling the user in the template
Wait
<h1>Hello there {{user.username}}</h1>
Hey @twin hamlet!
It looks like you tried to attach file type(s) that we do not allow (.html). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a.
Feel free to ask in #community-meta if you think this is a mistake.
you can access everything about the user from here
except passwords
def home(request):
# eng = Engineer.objects.get(user = request.user.id)
# eng_id=eng.id
# user = User.objects.get(pk=request.user.id)
# lab = Labour.objects.get(user = request.user.id)
# lab_id = lab.id
# print("ID and Username : ",lab_id.id,lab_id)
# user_id = user.id
# print(user,user_id)
# print(eng_id)
# print("Labour {}".format(lab_id))
# print("Engineer {}".format(eng_id))
# if lab_id and user_id:
# context = {'lab_id':lab_id}
# if eng_id and user_id:
# context = {'eng_id':eng_id}
#'user_id':user_id
return render(request, 'home.html')
for example if you wanted to see all the posts a user posted you could call {{user.post_set}}
post set will be a queryset you can loop through
who can help?
Rip respect noone replied
Sorry aryan, didn't look like you posted a questions
Generally speaking, if you implement Django you are stuck to some paradigms. I've always found a way around problems, e.g. middleware or overloading a function or something @dusk portal
Ok so should i continue
Btw ik flask and FastAPI both so it's not that hard for me
I enjoy Django if i want easy migrations and simple DB actions, and if I want to combine the backend with frontend stuff e.g. HTML templates Jinja or whatever
But yeah, Flask is lighter weight and arguably easier. Simpler
Yes, continue with Django. Don't expect to learn it quickly. It takes time and dedication.
Hello , so i'm trying to set up a download interface on my website and i got these two checkboxes that bring that select percentage slider , and i'm using fetch to send the form post request to flask , i want to check if the checkboxes are checked or not because now even when they are not i still get the default value from them
I'm creating a crypto casino web app on Django as an exercise, if anyone (who also want to play around with Django) wanna join let me know
what's the problem here? the check boxes also have a value which you can send to your backend
you can use that to actually tell the backend whether to use the percentages or not
when the checkbox is not check i still get values from it
yea i want to know if the checkbox is checked or not
like in js u type checkbox.checked
you're getting it's value because it's value is not really dependent on whether the check box is checked
that's just what you want to happen
and it seems like you did not implement that validation
yea what should i implement pls?
you can use javascript and if else statements to only send the percentage values when it's checked
or you could just do the checking in the backend and only use the value if the checkbox is checked
either one of the two
but two is better since frontend can always be altered by the user
document.getElementById('download').addEventListener('submit', function(e){
e.preventDefault();
const postData = new FormData(this);
checkBox1 = document.getElementById('checkbox-1-1');
checkBox2 = document.getElementById('checkbox-1-2');
if((checkBox1.checked == false) && (checkBox2.checked == false)){
alert('Please Select a type')
}else{
fetch('/download',{
method:'POST',
body:postData
}).then(function(){
console.log('Success');
}).catch(function(error){
console.log(error)
})
}
})
i got this
i want to do this
so read the value from the request and use an if statement
man, do you see your if statement
it doesnt catch all conditions
what if one is checked and the other is not? it's still gonna run the fetch method
yea i want to allow that
but when it runs i want flask to know that the percentage value of the unchecked checkbox shouldn't be used
again, this sounds like you just need if statements
i know but how do i get to know if the it is checked or not like in this one checkBox2.checked
append the data to postData
guys how can i download files returned from flask to fetch ??
Fetch?
If you mean like wget, you can always download static files using wget from flask or nginx
i got this form post request
document.getElementById('download').addEventListener('submit', function(e){
e.preventDefault();
const postData = new FormData(this);
checkBox1 = document.getElementById('checkbox-1-1');
checkBox2 = document.getElementById('checkbox-1-2');
if((checkBox1.checked == false) && (checkBox2.checked == false)){
alert('Please Select a type')
}else{
fetch('/download',{
method:'POST',
body:postData
}).then(function(){
console.log('Success');
}).catch(function(error){
console.log(error)
})
}
})
then i'm using flask with a script that zips files then returns the zipped file return send_file('NormalWS.zip',as_attachment=True) but the send_file isn't launching any download
So, I've been trying to get my Flask application to run with Apache and trying to get stuff working with SSL... but uh, my first issue is that heading to http://cypheriel.codes/ it brings up the default Apache page. I dunno what's wrong, but for some context here is the tree:
/var/www
โโโ FlaskApp
โย ย โโโ __pycache__
โย ย โย ย โโโ app.cpython-39.pyc
โย ย โโโ app.py
โย ย โโโ cypheriel.codes.key
โย ย โโโ cypheriel.codes.pem
โย ย โโโ flaskapp.wsgi
โย ย โโโ poetry.lock
โย ย โโโ pyproject.toml
โย ย โโโ static
โย ย โย ย โโโ index.html
โย ย โโโ templates
โย ย โโโ index.html
โโโ html
โโโ index.html ยซ This is the Apache default page
and the FlaskApp config:
/etc/apache2/sites-available/FlaskApp.conf
<VirtualHost *>
ServerName cypheriel.codes
ServerAdmin REDACTED
WSGIScriptAlias / /var/www/FlaskApp/flaskapp.wsgi
<Directory /var/www/FlaskApp/>
WSGIProcessGroup FlaskApp
WSGIApplicationGroup %{GROUP}
Order allow,deny
Allow from all
</Directory>
Alias /static /var/www/FlaskApp/static
<Directory /var/www/FlaskApp/static/>
Order allow,deny
Allow from all
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
LogLevel warn
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
I'm a complete beginner to this, so a good bunch of this stuff has been copied from guides like https://www.digitalocean.com/community/tutorials/how-to-deploy-a-flask-application-on-an-ubuntu-vps
Try other URLs
Try restarting apache2
Hmm
Test with curl locally
and test with url on your flask app directly e.g. curl localhost:8000, to confirm index.html or so is confirmed
(some ideas :))
uh... I restarted apache2, nothing has changed... and idk how anything else helps
if you can get index.html from localhost:8000 (flask app), then you've confirmed flask is not the problem and it is trying to serve the correct data
Other URLs could help because apache2 might be a little strict about requests for index.html
404 not found. incorrect configuration.
I already know flask is not the problem, it's gotta be apache
cause I can run the app without Apache... but uh I don't want to
the problem has got to be with my "site config" or whatever
cause static files I have set don't work
now I just get "Internal Server Error"
Jun 14 01:10:00 Webserver systemd[1]: Starting The Apache HTTP Server...
Jun 14 01:10:00 Webserver apachectl[53282]: AH00112: Warning: DocumentRoot [/var/www/html] does not exist
Jun 14 01:10:00 Webserver apachectl[53282]: AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1. Set the 'ServerName' directive globally t>
Jun 14 01:10:00 Webserver systemd[1]: Started The Apache HTTP Server.
I can see the app is enabled, too..
root@Webserver:/var/www/FlaskApp# a2query -s
FlaskApp (enabled by site administrator)
Sorry man, your configuration is broken. Paste what you have now.
(apache2 is SUPER fun btw ๐ )
<VirtualHost *:80>
ServerName cypheriel.codes
ServerAdmin totallylegitemail@email.com
WSGIScriptAlias / /var/www/FlaskApp/flaskapp.wsgi
<Directory /var/www/FlaskApp/>
WSGIProcessGroup FlaskApp
WSGIApplicationGroup %{GROUP}
Order allow,deny
Allow from all
</Directory>
Alias /static /var/www/FlaskApp/static
<Directory /var/www/FlaskApp/static/>
Order allow,deny
Allow from all
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
LogLevel warn
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
and /var/www/FlaskApp/flaskapp.wsgi is
import sys
import os
import logging
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0, "/var/www/FlaskApp/")
from app import app
app.secret_key = os.urandom(24)
check /etc/hosts
root@Webserver:~# cat /etc/hosts
# Your system has configured 'manage_etc_hosts' as True.
# As a result, if you wish for changes to this file to persist
# then you will need to either
# a.) make changes to the master file in /etc/cloud/templates/hosts.debian.tmpl
# b.) change or remove the value of 'manage_etc_hosts' in
# /etc/cloud/cloud.cfg or cloud-config from user-data
#
127.0.1.1 Webserver Webserver
127.0.0.1 localhost
# The following lines are desirable for IPv6 capable hosts
::1 ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
ff02::3 ip6-allhosts
remove/comment 127.0.1.1 Webserver Webserver and restart apache2, lets try
or reorder with localhost
Nothing
try adding ServerName globally to /etc/apache2/httpd.conf
Do I just put ServerName cypheriel.codes?
I mean it's not a host issue, I highly doubt it
because I can see the default apache stuff
huh. so http://cypheriel.codes/static loads
Not for me, but yeah, you tried another path...
Try again, I accidentally typed "https"
I get a 200 ๐
So static works, flask doesn't
Check logs again, i sus WSGI config
Okay... something's not right
root@Webserver:/var/www/FlaskApp# flask run --host=0.0.0.0
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
* Running on all addresses.
WARNING: This is a development server. Do not use it in a production deployment.
* Running on http://157.230.80.194:5000/ (Press CTRL+C to quit)
nvm. that port is closed
so http://cypheriel.codes:8000/ works, but not through apache
Where are Apache logs stored?
/var/logs/apache2/access.log or something
[Mon Jun 14 01:27:02.774716 2021] [wsgi:error] [pid 2330:tid 140572232759040] [client <IP>:58052] No WSGI daemon process called 'FlaskApp' has been configured: /var/www/FlaskApp/flaskapp.wsgi
AHA! I got it working
Few errors later
Now that we've got that out of the way... How on Earth do I manage HTTPS
๐
sudo apt-get install certbot
check out some docs on using LetsEncrypt/certbot with apache2
cloudflare has some different SSL options
If you use Full, then you also need to have a valid certificate from CF to your server ("origin host")
which... I think I have
idk I have 2 files, cypheriel.codes.pem and cypheriel.codes.key
Well... https://cypheriel.codes/ works but it says "authority invalid" or something
This error from CF means your origin host certificate is invalid or self signed
... the one I downloaded from them?
The one you are using on your origin host, in apache2 presumably
You need to configure HTTPS on your origin host (server) with a valid certificate for CloudFlare
Look into LetsEncrypt for apache2 using certbot.
Oh wow, that was easier than expected
Finally, my issues have been solved. Thank you very much for your help
hey guys, what's the recommended mysql module to use?
Develop a Django web application which helps for users to track and monitor their water intake. The application should provide option for setting up the target intake of water and allowing them for entering the details of all the ways of intake water they consume in a day, and the app will calculate the total intake of water and display the results to them, it has to also display the schedule of general intake of water intake age wise.?
Guys does anybody know how to do this i am struct with this problem..
how to link react app to flask
how to link react app to flask
@tidal dock expose the rest end points you created in flask and just ping them from your react app using fetch or axios or any other httpclient.
Ok let me help you then. You are creating a Rest Api using flask right?
what i should do?
guys , so i'm working on a download interface using flask , i got a return send_file() but don't know how to transform the blob returned into a downloadable file
You need to set the Content-Type header correctly
u mean like this @raw compass ??
fetch('/download',{
method:'POST',
headers: {
'Content-type' : 'application/x-zip-compressed'
},
body:postData
}).then(function(res){
return res.blob()
}).then(function(data){
console.log(data)
}).catch(function(error){
console.log(error)
})
thats the request. You will need to do the same though in flask for the response.
oh u mean this return send_file('NormalWS.zip',as_attachment=True,mimetype='application/x-zip-compressed') i already got it set up
the problem is the files aren't getting downloaded so i'm trying to use that blob to download the files in js
are they downloading though direct into your browser? Can you see the response when you use the Network in dev tools?
yup there is a response headers after finishing that
so i found something , people are using <a> tags to download the files
Just going to place this here, in case of any interest - A short introduction to adding a Google Login to your FastAPI applications, the newest feature of EasyAuth
https://joshjamison.medium.com/add-google-login-to-a-fastapi-app-with-easyauth-c8c3e926ad0a
What does the div tag in html?
Hello, I wanted to ask something about Django apps. Which way is the most useful and organized to create an API? The api app separated from an users one, or both inside api?
I think you should not be having app for api
Check django rest framework btw
Saves from a lot of job to do API in django
I think structure, where your every app is fulfilling its own set of endpoints, tests, model, serializers is the most comfortable way to approach it
After all... I think it is the way django creators offer you to work with
I'm trying to tame Django and create a fullstack app with Django + React or NextJS.
I'm eventually using DRF
So... have users in its own app
But do not create api app
Create new app, when you will have new big enough database model (table)
Which fulfills big enough job to have its own separated set of tests
I'd like to have a functional auth system with the app too
Will be your backend monolith or microservices
Microservices
then JWT cookies could be quite useful approach to auth
My mistake was to store them on the local browser bc I didn't see how I should produce cookies
https://pythonbasics.org/flask-cookies/
I searched it recently, found how cookies created in flask.
That's exactly the stack I'm using: Next.js + Django + GraphQL
Did you have questions about it?
Do you prefer GraphQL compared to REST?
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie or js-cookie library if you want to set them from frontend.
you don't create an api app? I always do ๐ณ
shrugs. what would be the point. whole application is one api
Wait do you need GraphQL?
my every app is a small api on its own
connected with others only by db model foreign keys
and each "app" is on the same docker container in this case?
mine is a bit monolithic at the moment
so maybe if I split it up into microservices I can reduce the number of apps
can i get someone's opinion real quick? at work, i'm on a project to develop basically a CRUD app, but the project lead wants to use django admin to basically do everything, but the client is requesting things like version control and material design.
i dont think that this is the intended use case for django admin and it seems to me that it would just be easier to build our own views.
I like the flexibility GraphQL provides vs. REST.
@surreal portal No you don't need it. You could use REST as well if you need API endpoints.
he wants to use django admin mainly because there's so much done for you, but i think there'd be a lot of friction trying to do it that way
could you tell more about usage intention of the app
like... I have three apps at work, where two aren't needing django admin
and one that serves as CRUD and django admin at the same time
well, it's under NDA, so i can't really be specific, but it essentially allows the business to administer their assets
intended user would be the client's internal admin
so... client's internal moderator essentially?
The way i wanna use Django is, there's a service updating the DB
i guess?
And another one using the updated Db for the client
django admin usage is fine, if it would be used by admin or moderator person
you can set restrictions quite good there
to prevent any un authorized action
i'm not worried about authorization and all that. my concern is the amount of effort adapting django admin to the client's use case
vs just doing it with custom views
emm... from my experience... wrapping into django admin is an easy peasy task
i haven't messed that much with it, so idk
like...
I would waste at least ten times less time
with wrapping into django admin
than trying to create custom views
the only drawback of django admin....
...that probably not always possible to make 'custom' enough feature
but if it is not an issue, it is golden
well they want version control, so that might be complicated
Btw I love Django's ORM
me three
Migrating is so easy to do
Killer feature in my opinion
django orm is pretty great, but i like sqlalchemy better
Django has SQLAlchemy's advantages and Alembic's
yeah but you can't use it outside of django
Hi all,
I'm having some issues with django framework. I have git repo of the project and the settings.py is different for development and production. I want to know how can i easily manage development commits and how to merge everything to production master branch without merging the settings.py file?
not easily anyways
actually it is possible to use standalone django usage
but well... not a lot of point if you have already framework)
I would replace Discord framework with Django though
Discord bot's framework is buggy as hell in my opinion and does not deserve to be used beyond necessary features
yeah
uhh in my experience it's been pretty robust
is there a way that i can use selenium to select a drop down list and then click one of the items from that list?
https://www.technomarket.bg/search?query=remington this is the site and i want to click the drop down list as shown in the picture, I am typing using the xpath to do this:
elemental= driver.find_element_by_xpath("/html/body/tm-root/main/tm-search/div/tm-product-filter/div/mat-drawer-container/mat-drawer-content/div[2]/div[1]/div[2]/tm-product-filter-facet[2]/div/mat-form-field/div/div[1]/div/mat-select/div/div[2]")
elemental.click()
(i am copying the full xpath from the page of the site) but i get an error that the element is not found
any idea why?
ะขะตั ะฝะพะผะฐัะบะตั ะฝะฐะน-ะณะพะปัะผะฐัะฐ ะฒะตัะธะณะฐ ะทะฐ ะฑัะปะฐ, ัะตัะฝะฐ ะธ ะพัะธั ัะตั ะฝะธะบะฐ ะฒ ะัะปะณะฐัะธั. ะัะฟะธ ะปะตัะฝะพ ะธ ะฑััะทะพ ะพะฝะปะฐะนะฝ ั ะฑะตะทะฟะปะฐัะฝะฐ ะดะพััะฐะฒะบะฐ. ะฃะดัะปะถะฐะฒะฐะฝะต ะฝะฐ ะณะฐัะฐะฝัะธััะฐ ั ะฟัะพะณัะฐะผะฐ ะะฐัะฐะฝัะธั ะฟะปัั.
did you try using its task manager feature?
haven't had the reason to
whatever its stuck... I have their the same features falling every week with different errors
sometimes even silently
the last error I found as the most hilarious
what are you trying to do with it?
I had just task running in a background loop
which made some acctions to channel messages
task got stopped on its own, with caught message, something like "Tirion"
who the hell is Tirion?%
and what this error means ๐
Maybe game of thrones reference.
that's probably a you problem lol
I mean... I check logs for the running bot
it gets every week different errors%
those discord servers aren't really stable thing
like... some time passes
the bot continues working fine...
...until it gets new errors from discord, that temporally shut it down
regardless, I would prefer using my own task manager than what discord offers
Btw for security and authentication, OAuth + cookie-based JWT for microservices?
I still did not learn basic ways yet
only got my hand on
cookie-based JWT and can say for sure, it is a good thing for microservices to authentificate users
there is only some ethical problem with cookies in general.
bot
funny defense
quite quick one
huh
I second JWT for microservices.
using FastAPI, can i have routes that only work when no authentication is provided?
eg, a profile creation route like
@router.post("/", response_model=schemas.User, status_code=201)
async def create_user(
user: schemas.UserCreate,
db: Session = Depends(get_db),
):
if operations.get_user_by_username(db, username=user.username) is None:
return operations.create_user(db, user=user)
raise HTTPException(status_code=400, detail="User already exists")
this works for unauthorized users as well as authorized
but it doesnt make sense to let authorized users access this route
actually, is this even a problem
i am at the moment handling it in a semi hacky way
I disabled native authorization in Django
and enabled pyJWT
whose logic I wrote to handle stuff with auth for me
Anyone worked with ckeditor? I cant style my table, how can I have color picker for table in the editor? Is there any plugin for that? Other problem is that I want my table responsive, when i try to add "auto" for height it gives me an error. So how can i resolve these errors?
I have deployed my Django app on Heroku using postgresql. My deployed app is not doing some calculations (calculating percentage of marks) correctly. But when I run my project on localhost with the exact same code, the calculations are correct. I don't get whats going wrong.
Hi, does anyone know if its possible to run a js function from the flask backend?
@hasty path Is there a global/environmental variable being used for the calc?
Something that could be different based on the machine?
it sounds like possible.... with something like web sockets
Is it recommended to modify the User model from Django ?
Or is there a way to extend it
Yea
You extend the base user model to a custom user model.
You need to do so at the beginning of your project to prevent problems later.
@surreal portal
I wonder if perhaps creating your own user would be easier than going with third option
Ty will look at it
(context django)
how do i sort the order of a queryset with its related model's field?
class Question(models.Model):
exam = models.ForeignKey(Exam, on_delete=models.CASCADE)
class QuestionIndex(models.Model):
session = models.ForeignKey(Session, on_delete=models.CASCADE)
question = models.ForeignKey(Question, on_delete=models.CASCADE)
index = models.PositiveIntegerField()
i can get all questions of an exam like so exam.question_set.all()
but how do i sort them with index field of their related model QuestionIndex where session is given
[i can't include index in Question as it is randomly generated(and hence different for different sessions) when user participates the exam]
@inland oak Would there be a benefit to it? This way you age all the user functionality baked in for very little custom code.
@cerulean badge In the admin? or do you want to filter the results in a function?
probably nothing, I guess.
well, except for django admin locked under totally separated user database
uh. probably I guess using third option would be still better than creating your own user
since I would have easier access to auth methods, inbuilt or plugin addded ones
No I have just called model objects here and there to count them or to convert their int value to str
Where can I see my print statements in my deployed django app ?
in a function
You can use model_name.objects.filter(field_name="string or whatever")
so filter instead of all() will return a list of whatever based on your filter.
e.g. Users.objects.filter(username="madlad")
but its a one 2 many field so i need to do session=session to it aswell how do i do that?
ive asked like 3 4 questions during different time of day and night
not once anyone replied
can i ask a question here?
Sorry to hear that.
Of course.
@cerulean badge Can you explain exactly what you are trying to get?
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth import authenticate
class LoginForm(AuthenticationForm):
def __init__(self, *args, **kwargs):
super(LoginForm, self).__init__(*args, **kwargs)
for visible in self.visible_fields():
visible.field.widget.attrs['class'] = 'form-control m-2'
visible.field.widget.attrs['placeholder'] = f'{visible.label}'
def clean(self):
username = self.cleaned_data.get('username')
password = self.cleaned_data.get('password')
if username is not None and password:
self.user_cache = authenticate(self.request, username=username, password=password)
if self.user_cache is None:
raise self.get_invalid_login_error()
else:
self.confirm_login_allowed(self.user_cache)
return self.cleaned_data
I have an inactive user model and the authenticate() function return None even on correct credentials if the is_active bool is set to false
This creates a problem that the user cant have feedback whether his account credentials are invalid or his account is inactive
(context django)
how do i sort the order of a queryset with its related model's field?
class Question(models.Model):
exam = models.ForeignKey(Exam, on_delete=models.CASCADE)
class QuestionIndex(models.Model):
session = models.ForeignKey(Session, on_delete=models.CASCADE)
question = models.ForeignKey(Question, on_delete=models.CASCADE)
index = models.PositiveIntegerField()
i can get all questions of an exam like so exam.question_set.all()
but how do i sort them with index field of their related model QuestionIndex where session is given
[i can't include index in Question as it is randomly generated(and hence different for different sessions) when user participates the exam]
this
the authenticate function
returns None even on right credentials if the user is inactive
does anyone know why this happens
i basically cannot give the user a feedback to whether his account credentials are invalid or his account isn't activated
how Prevent Multiple Sessions for a User in Django Application
where does question_set come from
its because Question has a foreignkey field to Exam
exam.question_set.all().order_by('questionindex__index')
yes but question is a one 2 many modal so with questionindex so i need get the questionindex with session=session
exam.question_set.filter(questionindex__session=session).order_by('questionindex__index')
one question have multiple questionindex and i want to sort question by questionindex's index field but since one question have many questionindex i want to use(sort with) the questionindex's index whose session=session
this is what i want
Where can I read my print statements in my deployed django app
@hasty path same name
Why would u put a print statement in deployed app
it's not a good practice
Guys ..
Help me with this.
in django app folder the templates are not working. ..
when I try to make a extends a html file in main directory to a html file in app folder. .
{%extends %} is not working.
Any django templates not working the html file..
Why. ?
How can I fix this. ?
how do I insert my data cvss2 and cvss3 at the same time is inserted with vulnerability model without rely on relationship vulnerability on cvss2 ? https://dpaste.org/eyYC#L72
You can set up logging and print to a file.
@cerulean badge maybe like this?
qs = QuestionIndex.objects.filter(question__exam=exam, session=session).order_by('index')
questions = [x.question for x in qs]
but that would be a list and i want a queryset bro
ok bro
hey, im working on transitioning over from flask to quart and was wondering if there was an equivalent for request.environ.get('HTTP_X_REAL_IP', request.remote_addr) (get ip address of visitor), cheers
edit: im working with hypercorn and nginx
where can i get a free tutorial on django
Really?
got it sorted, in headers
Have you tried google or YouTube?
Anyone ever added a progress bar to his website?? a progress bar for the script while it's running
Deadline = DateField('Deadline', format='%Y-%m-%d')
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
$( ".dtpick" ).datepicker();
});
</script>
<form method="post" action="">
{{ form.Deadline(class='Deadline') }}
{{ form.hidden_tag() }}
<input type="submit"/>
</form>
I try to add datepicker into my flask app, but after some research and tutorial on internet, it still doesn't work
I tried to create a request form but the error just keep pop out
how should I solve it?
What error are you getting?
Sorry for the confusion, what I actually trying to say is that the datepicker doesn't work
Hey @urban iris!
It looks like you tried to attach file type(s) that we do not allow (.pdf). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a.
Feel free to ask in #community-meta if you think this is a mistake.
Nice. I realized that I probably just did not know how to cook it.
it helped me a lot when i was learning the basics of web desingn
when i was trying to do a REST api
How can I put background image in html?
for the following website:
this is the image i want
You would do that in your css
i used a online css website
cyborg bootstrap something
so i have little clue on how to do that
<link href="https://bootswatch.com/5/cyborg/bootstrap.css" rel="stylesheet">```
Do you have a custom css file?
i downloaded bootstrap and saved all the css stuff into a
static file
i tried changing the bootstrap.min.css code
but since i have no clue what i am doing
But do you have a css file for your own custom css?
i didn't get anything doen
If not, you should make one
what do you mean?
how can i do that?
You can add your own css file and import that as well
The background image is set like this:
html {
background-image: link;
}
The link being the image link
right on
You would import that css file, yes
so i make my own one is that correct?
Yes
do i have to put quotation mark around the link?
I think so
background-image: url("http://link")
aoopy.PIE for the pythonUtilLib.pypl
i am thinking about adding a char field whose values will be comma seperated integers string, which can be used to represent the question order. but i feeling this isn't how data should be stored what is your opinion. (context django)
i have but i cant find the best one
any website u know
two tutrials on YouTube that I'd strongly recommend:
Try DJANGO Tutorial - 1 - Welcome
Try DJANGO Tutorial series is here to teach you Django bit by bit.
Playlist: https://www.youtube.com/playlist?list=PLEsfXFp6DpzTD1BD1aWNxS2Ep06vIkaeW
Code: https://github.com/codingforentrepreneurs/Try-Django
Subscribe: http://joincfe.com/youtube
Pro: http://kirr.co/ni5fia
In this Python Django Tutorial, we will be learning how to get started using the Django framework. We will install the necessary packages and get a basic application running in our browser. Let's get started...
The code for this series can be found at:
https://github.com/CoreyMSchafer/code_snippets/tree/master/Django_Blog
Flask Tutorials to cr...
thanks a lot man
guys anyone know how to setup lottie for web
no
im new to django and i was wondering for things like home screen or log in do i make a separate app for those or do i make something like a "random" sort of app and put them all into one app
In [2]: from blog.models import Post
In [3]: from django.contrib.auth.models import User
In [4]: Post.objects.all()
Out[4]: <QuerySet []>
In [5]: User.objects.all()
Out[5]: <QuerySet [<User: Vaibhav_pro>]>
Unhandled exception in event loop:
File "C:\Users\Yash\AppData\Local\Programs\Python\Python38\lib\asyncio\proactor_events.py", line 768, in _loop_self_reading
f.result() # may raise
File "C:\Users\Yash\AppData\Local\Programs\Python\Python38\lib\asyncio\windows_events.py", line 808, in _poll
value = callback(transferred, key, ov)
File "C:\Users\Yash\AppData\Local\Programs\Python\Python38\lib\asyncio\windows_events.py", line 457, in finish_recv
raise ConnectionResetError(*exc.args)
Exception [WinError 995] The I/O operation has been aborted because of either a thread exit or an application request
Press ENTER to continue...
In [6]: User.objects.all()
Out[6]: <QuerySet [<User: Vaibhav_pro>]>
In [7]:
this is the django api to deal with databases on my cmd
i want to ask why this error came and what it means actually , as whenever i hits it first time this error always c omes
what is the reason
is it a big problem?
please anybode help
No problem! Feel free to contact me for more!!
It seems to be a command prompt problem -- switch to another version, maybe 2.0.1 or some 2.x version, should work
ok , i am working in a virtualenv , i am thinking about installing ipython in it
is that the Jupyter kernel?
I'd suggest you take a look at docker -- it's free and lightweight, and you can use a bash or zsh shell to work with -- it'll make your life simpler going forward
i think that's more suited for data analytics -- haven't personally used it so can't really say
ok , thanks
All right. What would be easier...
adding pre rendering for Create React App or switching to Next.js
is anyone using flask
Is there any tool or something that'd help with creating front-end JS with Django? I'm building a web app but JS is cancer
why is that? if you want to build a web-app you can not escape JS
Django to Djago Rest Framework
and making front-end with React
Is there not a single tool on earth that'd help with it? I thought the point of Django is that you can do web dev in Python but it's the same as if I was doing it without Python so what's even the point?
Django is good for backend
But how do I submit stuff to my python script from the front end?
https://docs.djangoproject.com/en/3.2/intro/tutorial04/
with POST request
For example I have this:
<form>
<label>Enter a number:</label><br>
<input type="text"><br>
<input type="button" value="Submit number">
</form>
I'd like the button to submit the value to my .py that does the processing
the link above provides exactly what you seek
I've went through that already but didn't understand a single line of it
The examples are way too complex
start from the begining of the tutorial or get youself one of the..... beginner friendly django books
I can get you authors
Django for Beginners: Build websites with Python and Django - Kindle edition by Vincent, William S.. Download it once and read it on your Kindle device, PC, phones or tablets. Use features like bookmarks, note taking and highlighting while reading Django for Beginners: Build websites with Python and Django.
A fucking book lol
How does nested list work
same as when its not nested
but you reference it as you would reference other elements
list_a = [1, ['a'], 3]
list_b = list_a[1] # ['a']
For debugging ๐ I wanna check the values of a dictionary in my backend. When I print and check its values on localhost it works fine but not on my deployed app for some reason
Why print why dont use if
yeah ill try that
So many Aryans yes!
Can a Django guru help at #help-potato?
Can someone advice...
React-snap or react-static, or some other static build enchancement
or stop being mad and I don't need anything of that?
(I have already create react app)
when should i use clean method and when validators? (context django)
Are you trying to make a React App static?
i'm new in web dev..., please gimme some resources/tutorials
The clean() method is used to work with all the fields of a form and is called when MyForm.is_valid() is called. Validators can then be used inside the clean method to attach different validator errors/msgs to a specific field or to non-field.
cleaning a form means taking the form data, validating the data in regard of its intended field (type, formatting, etc.) and raise errors if needed. You would call clean() if you want to customize the validation of one or more field in your form i.e.: you want to put value into a field according to a specific business rule and you want to raise an error if it violates that rule but wouldn't be catched by normal field validation.
i mean the clean_[fieldname] method
The clean_MyField method is used to do custom validation to that specific MyField, you will not have access to other fields. It is ran after clean() (in fact clean() is run before every field specific clean, one field at a time), so a python object will be provided instead of the original string provided into the form (which is stored in self.cleaned_data) and you will have access to errors attribute. It must returns the current value of MyField in cleaned_data.
why validation errors not showing up with crispy forms
it is in html but not showing up i am rendering it with cirspy forms
context django
yeah
Not really sure if I need it
(more like my front end team mate wishes having SEO optimized app, which loads itself always to search engines)
he event went from Create React App (CSR) to Next.js (SSR), just for that
I call it crazy
Because we aren't exactly having a lot of dynamic content in the first place
all the dynamic content we have...
can be either appearing with the new commit of the frontend
or with the new commit of changes in the backend setings.
Nothing that would change with user hands
At best.... we have things that can be changed a bit with web site future moderators
but it changes only amount of choices in selectors
as far as I get...
according this table
SSR with Rehydration should be more than enough in my opinion
in our situation
having full SSR is just crazy
so... all we really need if we would go crazy with pre rendering... to add to our Create React App, usage of react-snap
๐คทโโ๏ธ
I'm pretty sure you can add SSR to CRA
I would prefer remaining as CSR application
because SSR would increase complexity to infrastructure as far as I get
not really? Currently we are having it hosted in Nginx, just serving static files
with SSR, it would be requiring more than having static file server?
mm, did you have before already hard choosing if you should select SSR, or CSR with pre rendering before?
I get it that... the choice perhaps can be varied depending on the content of the web site?
I just use Next because of fancy filesystem routing
I don't even notice SSR/SSG, although I've been paying more attention with my latest project
https://nextjs.org/docs/basic-features/pages#static-generation-recommended
this Is quite interesting page about it
basically Static Generation (read prerender) is recommended by next.js doc as well
while server side rendering is recommended only as last step resort%
they make pre render being flexible... to be full pre render, or pre rendering only shell, which will be populated with fetched data lately
Yes, static generation will always be best
which means I guess that Next.js application can be fully used as CSR only as well
Next.js is flexible to work in both ways
Yes, it can
The Next discord is saying the exact same things you are now lol
link? ๐
i was learning Generic views and made some changes after that this error started coming
@ember adder yo sir
It seems that you are trying to join two tuples, but it takes str or os.PathLike objects. Paste the line of code that raise this, that would help.
wait lemme show code
from django.shortcuts import render,get_object_or_404
from django.http import HttpResponse,HttpResponseRedirect
from .models import Question,Choice
from django.urls import reverse
from django.views import generic
class IndexView(generic.ListView):
template_name='app1/index.html',
context_object_name='latest_question_list'
def get_queryset(self):
return Question.objects.order_by('-pub_date')[:5]
class DetailView(generic.DetailView):
model = Question
template_name='app1/detail.html'
class ResultsView(generic.DetailView):
model=Question
template_name='app1/results.html'
def vote(request,question_id):
question = get_object_or_404(Question, pk=question_id)
try:
selected_choice=question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
return render(request,'app1/detail.html',{'question':question,'error_message': "You didn't select a choice."})
else:
selected_choice.votes += 1
selected_choice.save()
return HttpResponseRedirect(reverse('app1:results', args=(question.id,)))```
from django.urls import path
from . import views
app_name='app1'
urlpatterns = [
path('',views.IndexView.as_view(),name='index'),
path('<int:pk>/detail', views.DetailView.as_view(), name='detail'),
path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),
path('<int:question_id>/vote/', views.vote, name='vote'),
]
๐
Paste the stack trace, you can switch to copy/paste view from the wegpage
Hey @dusk portal!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
โข If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
โข If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
Whats a component of a Django web application someone in a team of 4 could have expected to have worked on. On my resume I have a verifiable lie that I helped a local charity with creating a web application that you can use to enroll relatives in for financial need (donation type thing).
@velvet yew You can just use Django, but you won't be able to do fancy UI stuff or perform async actions without JS. Django will let you do basic HTML/CSS with templates.
If you need to update something on the spot without a page refresh, for example, you will need to do an AJAX request, which requires JS.
My advise is dont lie on your resume because it only takes the interviewer asking you about it to know you have never touched or done what you say
So you CAN, but to get the full effect of modern websites, you need JS in some way. The most effective way now is to overlay a front-end framework (e.g. React, Angular, etc.)
@rustic moss Are you trying to get a Django job without experience?
I would ask you what makes it intuitive.
I mean any basic payment-collecting website could be created by 4 people I suppose.
why dont you actually write a project
Oh are you looking for an actual created project? ๐
I mean I created a marketplace with payment processing, user reviews, communication, etc. alone. I don't know what a team of 4 means.
Like, it could be created faster maybe.
But anything could be created by 4 people.
Why dont you just make a project that interests you
If you havent written or worked on the thing you say you have
it's very very obvious about what you have and havent done
I mean, fake it till you make it I guess, sure.
what have you actually done in terms of experience
like... what
well have you done any full web pages / web apps with Django, Flask... anything?
This is a most bizarre conversation. ๐
is flask the best for starter?
flask is a good start yes
@lethal flicker Some people think so because it is smaller and lightweight to learn on. I personally preferred Django because it let me focus on creating because so much is built in.
i see
@rustic moss Why are you even applying for entry level coding then?
well your actual experiences seem to be far far less than what you want to put on your resume
this isnt even about morality, but what you have done is miles bellow what i feel like you're saying you have done
A company taking you on if you say you havent got much experience wont expect you to know everything or even know much
but if you're saying, "hey i made xyz with this that and the other" and they take you on
Ok, one person could create the backend, one could do the front end.
they'll expect that you're more competent than you are
Two would do it faster.
litterally anything
litterally just make a basic Django app and just play around with it
for the sake of a few days of work
well do that before making up things you cant do lol
Can't tell if trolling or...
@rustic moss We already answered your original question.
I don't think anyone wants to help develop your lie.
Man if you dont know anything about the field you're applying for no matter how much stuff you make up, you're still not going to know anything
and the company taking you on will just end up expecting you to know stuff you dont
One little right question and the lie will fall apart.
"So what cache backend did you use"
@rustic moss The whole point is that you don't understand what we're saying, that ANYthing could be created.
4 people could create a solid app in about 3-4 months, maybe less.
But, that could be literally anything.
well just say you made amazon
So pick a fake project, and assign yourself a fake role. There you go.
I mean, what Amazon is at its core (minus the AI), could easily be made within a few months.
Search with filters.
oh yeah
Btw, apparently it is popular to make clones of famous sites
you can make a basic version of amazon in Django in no real time if you're familiar with it
Is there some sort of channel where we can advertise in here?
no
Or is advertising banned?
we dont allow advertising
Oh ok
hey what
plz help me out
@dusk portal Could you switch to the copy-and-paste view of the traceback and copy it here as text?
sure 1 sec sir
from django.shortcuts import render,get_object_or_404
from django.http import HttpResponse,HttpResponseRedirect
from .models import Question,Choice
from django.urls import reverse
from django.views import generic
class IndexView(generic.ListView):
template_name='app1/index.html',
context_object_name='latest_question_list'
def get_queryset(self):
return Question.objects.order_by('-pub_date')[:5]
class DetailView(generic.DetailView):
models=Question
template_name='app1/detail.html'
class ResultsView(generic.DetailView):
models=Question
template_name='app1/results.html'
def vote(request,question_id):
question = get_object_or_404(Question, pk=question_id)
try:
selected_choice=question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
return render(request,'app1/detail.html',{'question':question,'error_message': "You didn't select a choice."})
else:
selected_choice.votes += 1
selected_choice.save()
return HttpResponseRedirect(reverse('app1:results', args=(question.id,)))
Oh, I see the issue
You are putting a tuple somewhere as an argument that wants a string, or other specific thing.
It's the comma behind template_name='app1/index.html'
First line of IndexView
It turns that string into a tuple
oh
wait
lemme see7
got it
Lfmao
u know what this proves , this proves aryan yes aryan is bot coder @patent cobalt
Sorry @dusk portal I waited a long time to receive your traceback and then I got back into the Con I was virtually attending.
xD sorry from my side too
but love u all
ur support
i dont need an teacher i dont need any tut. i dont need to pay a single cent
i can learn from masters from makers and get queries solved by proz
right in a sec
love u alll
@app.route('/', methods=["POST","GET"])
def home():
if request.method == "POST":
session["movieName"] = request.form["movieName"]
return redirect(url_for("result", nm = session["movieName"] ))
else:
return render_template("index.html" )
@app.route('/result')
def result(nm):
return f"in result {nm}"
it says that nm argument is missing
can anyone help?
Aren't you missing methods attribute in your @app.route decorator?
no its there.
just forgot to copy that
TypeError: result() missing 1 required positional argument: 'nm'
does redirect work that way? I usually pass/return a context/dict.
here they retrieve the args through request.args.get(argname)
but request.for[""] should be working right?
and why is it giving missing argument i dont get it
Hi All
I have <Courses:[course str representation]>
i want to get course instance based on that is it possible?
it depends if the string representation is unique or not
yes it is unique
then you can get that instance based on that unique thing, where are you stuck?
well let me explain
in the request data i pass courses object to validate method
and if i check the type (<Courses:[course str representation]>) it tells me course instance
however, when i try to save it, i get the error that it is not course instance
anyway, solved it using String related field
nice
np, haha glad you think so!
Why Stringrelated fields become read only?
coursename=serializers.StringRelatedField()
coachname=serializers.StringRelatedField()
class Meta:
model=Groups
fields=['groupname','coursename',
'startdate','groupstatus','enddate','hourperlesson','coachname']```
here is my code, i can not see coursename and coachname as POST fields
docs says it is read only
I believe you have to pass in a queryset to your stringrelatedfield
something like
coursename=serializers.StringRelatedField(queryset=CourseName.objects.all())```
or whatever your coursename object is defined as
Django, API, REST, Serializer relations
as per docs, we dont have queryset attribute for StringRelatedField
in that case, maybe stringrelatedfield is not writeable
because it is read only
yes that's case
in which case you should use a primarykeyrelatedfield if you want to write to it
doesnt do my job
it is numbers, i dont like numbers
i like titles names and et
will try slugrelatedfield again
unfortunately, computers like numbers
using pk is very common
and you will see it very often
slug should work as well though
as you see I didint use safe method here and html is seen, when I use safe method, cards getting vertically arranged
How can I solve?
Hello, I am currently looking for replacing starlette with another python api as starlette is executing one api call twice and it's fucking up with the table queries, any suggestions? How's falcon?
The code is supposed to do exactly what is needed, while request is made it makes two requests simultaneously and the queries get executed twice, it's a simple request made from android app
and please reply if someone does seem to know my issue
I would be immensely grateful
No offense my guy but if you havent even shown any code you cant just claim a framework with 152 contributors is fucking up, why dont you show the offending code
hello, is it ok to ask questions about fastapi here?
a simple code structure that adds a row to the table ends up duplicating cus the endpoint is being executed twice
the endpoint does some thing major like it performs few checks and then adds the row
when checking the http requests made through app, it shows that same url is being called twice
Mate, without code, nobody can help
Is it the fault of the android app that merely calls the url? how does that even happen
Yes it is, go for it
probably
what is being used to write the app?
the android app
it's in java
but I don't understand how a request call can be executed twice
there's no way really
I have heard that if the endpoint takes too long to respond, chrome makes the call again
but that doesn't apply to an android app using requests does it?
a lot of things you think shouldn't happen will happen in code
especially when you're dealing with libraries you didn't write and don't understand how they work
Well I see what you mean
this has happened to me
I simply used the url on chrome, and it messed up the queries executed
can you get into the devtools of the android app and see the requests being called?
why is the request taking so long?
actually this is very rare but happens a lot when lot of users are using it
so you cannot reproduce this locally at all
probably cus a lot of users are using the app and the tasks in the endpoint even tho not that major but I guess it's enough to make the endpoint 1s time taken
I have no idea really so my last resort was to make write the api again but using different framework
but now that I realise it might not be the framework but maybe in android
like mariosis voiced, I have doubts that it is the fault of the framework
it's a simple request call so there isn't much debugging there so not sure why
yeah i guess so
and it's not like it'll everytime do it twice
rarely it does :/
Is it the same request or is one a redirect
About fastapi..have u guys ever deploy it with deta?
I tried doing that but it gave me this error :/ so im wondering if anyone had the same problem and knows how to solve this? Or maybe even suggesting better ways to deploy fastapi? That could help too as im trying to find ways to deploy my fastapi
let me explain
I want a field to be shown in detail in GET request
i have a coachfield which is connected to groups class
with foreign key
in GET request, i want to see coach id, name surname, and unique number
in POST request, i want to choose only name/surname from dropdown
you want to serialize the nested model?
yes
in this case, POST request tells me to fill
ALL the details of nested object which i am not intended to do
does your model have defaults on them, and you may need to specify required=False in your serializer
i will post a picture
if serializer.methodfield fails
to u for better understanding
I need to keep POST method like this
and GET like this
if i change the serializer as per my need, extra 3 fields appear
I can make additional serializer field as readonly however,
in this case, i can not add coach name
@indigo kettle did u manage to understand my problem ๐ ?
which function is run before validation?
when we try to save?
i am talking about modelserializer
is there a better way to wrte this code ```py
import requests
from typing import Union, Optional, Dict
def linkedin_requester(method: Union['get','post','put'], url: str, payload: Optional[Dict]):
if(method == 'get'):
return requests.get(url)
if(method=='post'):
return requests.post(url, payload)
if (method == 'put'):
return requests.put(url, payload)
requests.request(method.upper(), url, data=payload)
Also, it's redundant to put parenthesis for if statements.
thanks @proper hinge , I do realize that, its just that I have been coding a lot of JS these days, force of habit lol
Is there anyway to get the local time zone ( just tthe name of timezone like EST PST) in jinja/django front end?
https://pypi.org/project/django-tz-detect/
Apperently user session has time offset stored in it
So there are plugins capable to simplify its extraction
to cut short the path...
...I advice trying to extract information about user from his browser
I remember there is some function which gets a lot of info
there should be stored his timezone as well
so you can extract it directly from user browser to user client side without backend participation
windows.navigator I think?
or actually people advice using those javascript functions
https://stackoverflow.com/questions/6939685/get-client-time-zone-from-browser
jzts and Intl libraries
apperently Intl perhaps even inbuilt
Thanks @inland oak , I'll look into it. I already have an MW ready which activates django.utils tz for local rendering. Just need to initially activate each user's local tz. This should help.
is there a way to check if a button was clicked
add javascript to it, which activates script on its click.
i dunno js ๐ฆ
but i want it such that on click it displays some data
under the form
Does anyone have any idea of this
What kind of data is it and where will it be coming from?
You have a couple of options depending on where it comes from. If you have control over it, you could have it hidden in an element on the template, and then on button click, you could find that element and unhide it say.
If it's from an external source, then you'd have to submit a request and render the response.
Can you share the route for /?
Hi, I am trying to create a website
However one of the page don't open up after pressing a button
but if i put the specific link it works
The error I get is Method Not Allowed?
The error message is as it is
Are you submitting a POST request? Make sure your route accepts a POST request
https://flask.palletsprojects.com/en/2.0.x/quickstart/#the-request-object
oh alright
I do that by saying
@app.route('/keywords_uploaded', method="POST")
def ksjkmskmm....````
right?
Read the doc I linked
its string coming from the form above ( for now) later i want it to come from the python file as it will be coming from the database
I am currently working on a website project, would anybody like to collaborate with me on it?
It's to generate PDFs or PNGs from LaTeX.
You can specify a get or post method yes
Any time you're submitting data, consider adding a post method
isn't it on "GET" by default?
yes, because that's pretty much viewing the page
Yep
can anyone see what is the prob?
Unable to write into user settings. Please open the user settings to correct errors/warnings in it and try again.
error
I'm assuming you have a problem saving the file
{
"window.zoomLevel": 0,
"editor.suggestSelection": "first",
"vsintellicode.modify.editor.suggestSelection": "automaticallyOverrodeDefaultValue",
"python.languageServer": "Microsoft",
"files.autoSave": "afterDelay",
"workbench.editorAssociations": {
"*.ipynb": "jupyter.notebook.ipynb"
},
"launch": {
"configurations": [
]
},
"liveServer.settings.donotVerifyTags": true,
"liveServer.settings.donotShowInfoMsg": true,
"editor.formatOnPaste": true,
"editor.formatOnSave": true
"emmet.showSuggestionsAsSnippets": true,
"files.associations": {
"*html": "html",
"*njk": "html"
}
}
i want to add prettier extension
Oh lol k
it says the above json there is some error
how do i import a .sql file to my django db
I gues .sql is a dump file
if it is postregsql...
...go to postgres
and perform direct uploading of the dump to the db
then you can inspect db with django
to find which fields it has
i already decided on phpmyadmin cause im more familiar with it, thanks tho!
shrugs.
anything that suits you
Ah gotcha. If it's from the database via Python file might be simpler. Whereabouts from the form will the string be?
Hey guys I have a situation, I am trying to show data from multiple model in a single list view cbv using get_context_data(). It is showing when until I created and used the form on same view and when I call the post function for the form and after submitting the form all the data from model didn't showing up. How can I show the data even after filling the form?? Plz help
my table in the admin panel has an extra s, my model is the correct spelling, what is causing this?
my model:
Django itself add s in modela
Welcome
wut
I never noticed this
just run makemigrations categories once more
i can get it in the python file
how do i make it so that instead of objects, my values display as rows like how the user table does it
@primal thorn in admins.py you can have list_display = list of fields you wanna display
Also to answer your previous question about an extra s
in your model add the following lines
class Meta:
verbose_name_plural = 'Categories'
that fixed it! thank you
Guys I need help with flask
I want to make a web dashboard for my bot but I don't know how to make and how to connect it with
I'll help you out in a bit
how can we get a boolean value from a checkbox/toggle button in flask?
get args gives None
Hello everyone, i am currently try to migrate from Strapi to FastAPI i wonder now since i always had my API just open, how would somene secure it so that only my frontend APP has access to the api.
From what i understand so far i could use JWT, and this is working as Login etc, but well i dont want users to "login" everytime they visit the website, how can i "login" the app itself
you can also write a __str__ method in your model
return self.title
views.py```py
from django.shortcuts import render,get_object_or_404
from django.http import HttpResponse,HttpResponseRedirect
from .models import Question,Choice
from django.urls import reverse
from django.views import generic
class IndexView(generic.ListView):
template_name='app1/index.html'
context_object_name='latest_question_list'
def get_queryset(self):
return Question.objects.order_by('-pub_date')[:5]
class DetailView(generic.DetailView):
models=Question
template_name='app1/detail.html'
class ResultsView(generic.DetailView):
models=Question
template_name='app1/results.html'
def vote(request,question_id):
question = get_object_or_404(Question, pk=question_id)
try:
selected_choice=question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
return render(request,'app1/detail.html',{'question':question,'error_message': "You didn't select a choice."})
else:
selected_choice.votes += 1
selected_choice.save()
return HttpResponseRedirect(reverse('app1:results', args=(question.id,)))```
from django.urls import path
from . import views
app_name='app1'
urlpatterns = [
path('',views.IndexView.as_view(),name='index'),
path('<int:pk>/', views.DetailView.as_view(), name='detail'),
path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),
path('<int:question_id>/vote/', views.vote, name='vote'),
]
``` urls.py
got it thanks!
As a rule of thumb, as working with generic CBVs, you want to name them with the following general formula:
ModelnameGenericViewname
so whats the issue i have provided model name
can u explain clearly
example plz
but in docs and vid
his is working

for example, if my model is blog, I'd name a detailview as:
BlogDetailView(DetailView):
try it out, in the meanwhile, I'll look into it
lol
got it
i was naming it
Models=Question
it was
model = Question
im dumb
omg didn't notice that myself
Hi, I've built my first backend on Django
And for ttesting deployed it on heroku
With postgres on heroku with its add on
Heroku had auto deployment
Now it's production ready and I'm planning to host it on AWS, should I host it on an EC2 instance? Or use lightsail or Elastic Beanstalk with probably RDS? Needed some guidance here
someone please help
#help-broccoli i need some help with selenium, would be very nice if someone can take a look please
Thank you
request.form.get(input_name) doesn't work?
guys i'm having a problem
i took one twitter logo from lottie and make it button in html
<div class="gm" data-file="tweet"></div>
</a>```
but when i move it in main.scss
using
`bottom: -6.7em`
from the point i move it another point it becomes button how can i fix it
ping me
you'll need to use JS for that. Your backend only receives information about your form via requests. So, you'll either need to send new requests each time the checkbox changes or handle it on the client-side, both which require JS
"from the point i move it another point it becomes button how can i fix it" ?
already did
first i directly linked url to animation but now i created button and moved the button and i gave link to button
it was this simple and i waste my whole 1 day on it
๐คฆโโ๏ธ
so, what even is your question?
this was not anymore
-
CORS. You are able to specify which hosts can request your API. Browsers will not parse your API response if the CORS header is invalid. (but don't rely on CORS).
-
Token authentication can be used. Users do not have to login each time because the tokens are stored as cookies.
However one issue with JWTs is that you'll need to implement a system to revoke them.
Maybe it'll just be much easier using basic token authentication
ohh :(
It's not a bad thing, for web-dev you will always have to learn JS later down the road.
i see
Uh, so that's not a good way to get started with js
The document is a pretty intermediate concept
And you should never use var
I'd recommend the Codecademy course to learn the basics, and then you'll understand this better
It's a completely different language than Python, so it has its own rules on how it works
The Codecademy course is rather good, but please don't try to speedrun
When you do that, you don't learn it properly
I've made that mistake before
okay so i'm little confused on 31:13 why we should only use "bm" if i have 3 icons and i want to access them individually then should i name them other than "bm" ?
Check out WrapPixel! https://www.wrappixel.com/blackfriday
https://designcourse.com - Learn UI/UX from Scratch with my new service (coming soon)
-- Today, we're going to conclude our 2 part crash course on creating animated icon designs using lottie.js. In the first video (linked below), we designed the icons using Adobe Illustrator. In this vid...
@rugged charm it returns an empty list. Wait I'll send the html side code
it will return true or false if you send the checked value of the input, otherwise it will give the value in value attribute of the input field
div class="form-check form-switch">
<form>
<input class="form-check-input" type="checkbox" id="flexSwitchCheckDefault" name="toAdd", value =True>
<label class="form-check-label" for="addToDb">add to your collection</label>
</form>
</div> ```
in this case if it is not checked it will return None to python otherwise True that too as a string...
ps: please enclose the value for input field in quotes
no get is fine.....get_list is needed when you have multiple check boxes
i just have one tho
ya so try request.form['toAdd']
ok
shows key error now
T_T
ok so can I just add a button instead an get a boolean value from it?
just print request.form and see what all keys do you have
buttons can have call to action not values, checkbox is the right approach
Has someone tried to send protobuf data through flask-socketio? ๐ค
it shows empty dictionary TT
https://stackoverflow.com/questions/11556958/sending-data-from-html-form-to-a-python-script-in-flask
you haven't setup the form method as post
can anyone help me with django dynamic urls
in index.html i want to create dynamic links to details.html
href="{% url 'details' book.id %}"
i have added path to urlpatterns
path('moredetails/<slug:id>',views.moredetails,name='details')
in views.py also defined function with parameter id
def moredetails(request,id):
event = {'date':'22-08-21','place':'london'}
return render(request,'sayhello/readmore.html',{
'event':event,
})
in index.html file i am iterating over list of dictionary and yes the dictionary has a key id
but the error i am getting is
NoReverseMatch at /book/
Reverse for 'details' with arguments '('',)' not found. 1 pattern(s) tried: ['moredetails/(?P<id>[-a-zA-Z0-9_]+)$']
hey the form doesn't know where to send the data action is missing too
oh so what should I put there?
can you just go through the stackoverflow link i sent you
okay
can anyone have a look here
- what is the use of id in your view?
- try adding <app_name>.details as the url in action
hi all, does anyone have any suggestions for tutorials or free courses to learn Flask, I'm just trying to learn Flask for my thesis, maybe you guys have suggestions where I should learn it.
uh yeah there is this great series on youtube
How To Build Websites with Python and Flask! In this videos I'll walk you through building a very basic website with Flask. You'll see just how easy it is to get started with this powerful web framework!
Python is great, and building websites with Python is even better! Flask makes it super easy to build websites with Python quickly and eas...
helped me a bunch when i was learniung
How can i work with dates before consult them in the database?
are you using django?