#web-development

2 messages ยท Page 164 of 1

native tide
#

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>```
native tide
opaque rivet
#

@native tide bootstrap provides utility classes for your elements.

You can press on elements in your theme to see its source code.

native tide
#

right on

subtle otter
#

Hello , is it possible to use save_file when using fetch()??

short wave
#

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?

native tide
#

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

opaque rivet
#

@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?

native tide
#

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

mint folio
subtle otter
#

@short wavehit your brother up when u finish that :3 lemme make some profit too

opaque rivet
#

If you are unsure just search it up.

#

@native tide What's the question? Ask it, instead of asking to ask.

civic pewter
#

'Image' object has no attribute '_committed' WTF?

gritty cloud
#

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?

wooden ruin
gritty cloud
#

ok i fixed my path

#

now it is path('answer/<int:pk>')

wooden ruin
#

it's an arbitrary html tag that serves no base purpose but is useful for organization. <br> is for new lines

gritty cloud
wooden ruin
#

wdym by not working?

gritty cloud
#

OOOOOOOOOOOOOOOOOOO

#

i see what the problem is

#

ty for the help dude!

fresh leaf
#

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...

gritty cloud
#

what does that mean

#

o i see

#

so first the model

#

The model looks good

fresh leaf
# gritty cloud bid system?

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.

gritty cloud
#

ok

#

so for the admin site

#

you don't need to do anything weird

#
admin.site.register(YourModelHere)
#

first import themodel tho

fresh leaf
#

I have done that.

#

I didn't show the imports

gritty cloud
#

ok

fresh leaf
#

In this snippet

gritty cloud
#

so next the create listing form

#

you have a forms.py?

fresh leaf
gritty cloud
#

well that is not very close to django principles

#

you should make a forms.py in your app

#

and put forms in there

fresh leaf
#

Oh, okay.

#

Also I want to ask you something

gritty cloud
#

what is it

native tide
#

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?

gritty cloud
#

they are written in c

fresh leaf
native tide
gritty cloud
#

where if you register models with admin.site.register

#

the admins can delete, add, and update all records

fresh leaf
#

Yes, but

gritty cloud
#

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

gritty cloud
fresh leaf
#

Sorry... Let me elaborate a bit

gritty cloud
#

no i mean @native tide 's question

#

not urs

fresh leaf
#

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?

fresh leaf
gritty cloud
#

so in forms.py you just move the code from admin.py

twin hamlet
#

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>

gritty cloud
#
class ListingForm(forms.ModelForm):
  class Meta:
    # stuff
gritty cloud
#

{% if user.is_authenticated %}

twin hamlet
dusk portal
#

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

gritty cloud
#

this will return true if the user is logged in

twin hamlet
#

but there is an logical error

gritty cloud
#

ok lemme show u

dusk portal
#

@twin hamlet kya hua(how can i help)?

fresh leaf
twin hamlet
gritty cloud
#
{% if user.is_authenticated %}
  <!--For if user is logged in-->
{% else %}
  <!--For if user is  not logged in-->
{% endif %}
gritty cloud
#

you can access the user by just calling the user in the template

twin hamlet
gritty cloud
#
<h1>Hello there {{user.username}}</h1>
lavish prismBOT
#

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.

gritty cloud
#

except passwords

twin hamlet
#

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')
gritty cloud
#

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

vivid canopy
#

who can help?

deep tinsel
#

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

dusk portal
deep tinsel
#

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

opaque rivet
#

Yes, continue with Django. Don't expect to learn it quickly. It takes time and dedication.

subtle otter
#

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

velvet yew
#

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

thorn igloo
#

you can use that to actually tell the backend whether to use the percentages or not

subtle otter
#

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

thorn igloo
#

that's just what you want to happen

#

and it seems like you did not implement that validation

subtle otter
#

yea what should i implement pls?

thorn igloo
#

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

subtle otter
#
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

thorn igloo
#

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

subtle otter
#

yea i want to allow that

thorn igloo
#

it's gonna send the data for both things

#

anyways, nvm

subtle otter
#

but when it runs i want flask to know that the percentage value of the unchecked checkbox shouldn't be used

thorn igloo
#

again, this sounds like you just need if statements

subtle otter
#

i know but how do i get to know if the it is checked or not like in this one checkBox2.checked

thorn igloo
#

append the data to postData

subtle otter
#

guys how can i download files returned from flask to fetch ??

deep tinsel
#

Fetch?

#

If you mean like wget, you can always download static files using wget from flask or nginx

subtle otter
#

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

foggy fiber
#

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>
deep tinsel
#

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 :))

foggy fiber
#

uh... I restarted apache2, nothing has changed... and idk how anything else helps

deep tinsel
#

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.

foggy fiber
#

cause I can run the app without Apache... but uh I don't want to

deep tinsel
#

Any log messages?

#

Try other URLs?

foggy fiber
#

Idk what URLs you mean for me to try, though

#

/index.html is all that I have

deep tinsel
#

Ah, no static files?

#

You could try a .png or .txt file

foggy fiber
#

the problem has got to be with my "site config" or whatever

#

cause static files I have set don't work

deep tinsel
#

virtual host looks incorrect here:

#

Port 80 is specified

foggy fiber
#

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)
deep tinsel
#

Sorry man, your configuration is broken. Paste what you have now.

#

(apache2 is SUPER fun btw ๐Ÿ˜‰ )

foggy fiber
#
<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)
deep tinsel
#

check /etc/hosts

foggy fiber
#
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
deep tinsel
#

remove/comment 127.0.1.1 Webserver Webserver and restart apache2, lets try

#

or reorder with localhost

foggy fiber
#

Nothing

deep tinsel
#

try adding ServerName globally to /etc/apache2/httpd.conf

foggy fiber
#

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

deep tinsel
#

Not for me, but yeah, you tried another path...

foggy fiber
#

Try again, I accidentally typed "https"

deep tinsel
#

I get a 200 ๐Ÿ™‚

foggy fiber
#

So static works, flask doesn't

deep tinsel
#

Check logs again, i sus WSGI config

foggy fiber
#

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

#

Where are Apache logs stored?

deep tinsel
#

/var/logs/apache2/access.log or something

foggy fiber
#
[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

deep tinsel
#

๐Ÿ™‚

#

sudo apt-get install certbot

#

check out some docs on using LetsEncrypt/certbot with apache2

foggy fiber
#

Well, I've got SSL certificates from CloudFlare

#

I just dunno how to use them

deep tinsel
#

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")

foggy fiber
#

which... I think I have

#

idk I have 2 files, cypheriel.codes.pem and cypheriel.codes.key

deep tinsel
#

This error from CF means your origin host certificate is invalid or self signed

foggy fiber
#

... the one I downloaded from them?

deep tinsel
#

The one you are using on your origin host, in apache2 presumably

foggy fiber
#

uh

#

Yeah... I don't understand

deep tinsel
#

You need to configure HTTPS on your origin host (server) with a valid certificate for CloudFlare

#

Look into LetsEncrypt for apache2 using certbot.

foggy fiber
#

Oh wow, that was easier than expected

#

Finally, my issues have been solved. Thank you very much for your help

harsh summit
#

hey guys, what's the recommended mysql module to use?

proper meteor
#

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.?

proper meteor
tidal dock
#

how to link react app to flask

sullen plaza
#

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.

tidal dock
#

i didnt get it

#

im beginner

sullen plaza
#

Ok let me help you then. You are creating a Rest Api using flask right?

vivid canopy
#

help pls

#

i have this

vivid canopy
#

what i should do?

subtle otter
#

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

raw compass
subtle otter
#

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)
        })
raw compass
#

thats the request. You will need to do the same though in flask for the response.

subtle otter
#

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

raw compass
#

are they downloading though direct into your browser? Can you see the response when you use the Network in dev tools?

subtle otter
#

yup there is a response headers after finishing that

#

so i found something , people are using <a> tags to download the files

scenic pendant
native tide
#

What does the div tag in html?

surreal portal
#

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?

inland oak
#

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

surreal portal
#

I'm trying to tame Django and create a fullstack app with Django + React or NextJS.
I'm eventually using DRF

inland oak
#

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

surreal portal
#

I'd like to have a functional auth system with the app too

inland oak
#

Plenty of options how to do it

#

From your own... to a lot of in built choices

inland oak
surreal portal
#

Microservices

inland oak
#

then JWT cookies could be quite useful approach to auth

surreal portal
inland oak
dense slate
#

That's exactly the stack I'm using: Next.js + Django + GraphQL

#

Did you have questions about it?

opaque rivet
opaque rivet
opaque rivet
inland oak
surreal portal
inland oak
#

my every app is a small api on its own

#

connected with others only by db model foreign keys

opaque rivet
#

and each "app" is on the same docker container in this case?

opaque rivet
#

mine is a bit monolithic at the moment

#

so maybe if I split it up into microservices I can reduce the number of apps

frosty osprey
#

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.

dense slate
#

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.

frosty osprey
#

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

inland oak
#

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

frosty osprey
#

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

inland oak
#

so... client's internal moderator essentially?

surreal portal
#

The way i wanna use Django is, there's a service updating the DB

frosty osprey
#

i guess?

surreal portal
#

And another one using the updated Db for the client

inland oak
#

you can set restrictions quite good there

#

to prevent any un authorized action

frosty osprey
#

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

inland oak
#

emm... from my experience... wrapping into django admin is an easy peasy task

frosty osprey
#

i haven't messed that much with it, so idk

inland oak
#

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

frosty osprey
#

well they want version control, so that might be complicated

surreal portal
#

Btw I love Django's ORM

inland oak
surreal portal
#

Migrating is so easy to do

inland oak
#

Killer feature in my opinion

frosty osprey
#

django orm is pretty great, but i like sqlalchemy better

surreal portal
#

Django has SQLAlchemy's advantages and Alembic's

frosty osprey
#

yeah but you can't use it outside of django

native tide
#

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?

frosty osprey
#

not easily anyways

inland oak
#

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

frosty osprey
inland oak
#

yeah

frosty osprey
#

uhh in my experience it's been pretty robust

fresh dragon
#

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?

inland oak
#

did you try using its task manager feature?

surreal portal
#

Isn't Discord's backend with Rust?

#

What's Discord's stack?

#

Rust + ElectronJS?

frosty osprey
inland oak
#

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

frosty osprey
#

what are you trying to do with it?

inland oak
#

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 ๐Ÿ˜‰

dense slate
#

Maybe game of thrones reference.

frosty osprey
#

that's probably a you problem lol

inland oak
#

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

surreal portal
#

Btw for security and authentication, OAuth + cookie-based JWT for microservices?

inland oak
#

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

honest ginkgo
#

huh

dense slate
noble spoke
#

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

inland oak
#

I disabled native authorization in Django

#

and enabled pyJWT

#

whose logic I wrote to handle stuff with auth for me

foggy bramble
#

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?

hasty path
#

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.

random lava
#

Hi, does anyone know if its possible to run a js function from the flask backend?

dense slate
#

@hasty path Is there a global/environmental variable being used for the calc?

#

Something that could be different based on the machine?

inland oak
surreal portal
#

Is it recommended to modify the User model from Django ?

#

Or is there a way to extend it

dense slate
#

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

inland oak
#

I wonder if perhaps creating your own user would be easier than going with third option

surreal portal
#

Ty will look at it

cerulean badge
#

(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]

dense slate
#

@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?

inland oak
#

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

hasty path
#

Where can I see my print statements in my deployed django app ?

dense slate
#

so filter instead of all() will return a list of whatever based on your filter.

#

e.g. Users.objects.filter(username="madlad")

cerulean badge
glossy scroll
#

guys

#

whys is the help channel so unhelpful regarding django

#

they never reply

dense slate
#

Maybe people are at work and not a lot of people available?

#

I usually get replies.

glossy scroll
#

ive asked like 3 4 questions during different time of day and night

#

not once anyone replied

#

can i ask a question here?

dense slate
#

Sorry to hear that.

#

Of course.

#

@cerulean badge Can you explain exactly what you are trying to get?

glossy scroll
#
  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

cerulean badge
# dense slate <@!810158114190917662> Can you explain exactly what you are trying to get?

(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

glossy scroll
#

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

stark tartan
#

how Prevent Multiple Sessions for a User in Django Application

dense slate
#

where does question_set come from

cerulean badge
indigo kettle
cerulean badge
indigo kettle
#

exam.question_set.filter(questionindex__session=session).order_by('questionindex__index')

dense slate
#

You can find more examples of that here:

cerulean badge
#

this is what i want

hasty path
#

Where can I read my print statements in my deployed django app

dusk portal
#

@hasty path same name

dusk portal
frail tapir
#

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. ?

dawn heath
#

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

dense slate
indigo kettle
#

@cerulean badge maybe like this?

qs = QuestionIndex.objects.filter(question__exam=exam, session=session).order_by('index')
questions = [x.question for x in qs]
cerulean badge
indigo kettle
#

ok bro

fervent raft
#

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

bright saffron
#

where can i get a free tutorial on django

dense slate
#

Really?

floral fulcrum
subtle otter
#

Anyone ever added a progress bar to his website?? a progress bar for the script while it's running

terse vapor
#
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?

outer apex
terse vapor
#

Sorry for the confusion, what I actually trying to say is that the datepicker doesn't work

lavish prismBOT
#

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.

urban iris
#

really usefull

inland oak
# urban iris

Nice. I realized that I probably just did not know how to cook it.

urban iris
#

it helped me a lot when i was learning the basics of web desingn

#

when i was trying to do a REST api

native tide
#

How can I put background image in html?

#

for the following website:

#

this is the image i want

calm plume
native tide
#

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">```
calm plume
#

Do you have a custom css file?

native tide
#

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

calm plume
#

But do you have a css file for your own custom css?

native tide
#

i didn't get anything doen

calm plume
#

If not, you should make one

native tide
#

how can i do that?

calm plume
#

You can add your own css file and import that as well

native tide
#

so make my own css file and set background to that image

#

and import that image?

calm plume
#

The background image is set like this:

html {
  background-image: link;
}
#

The link being the image link

native tide
#

right on

calm plume
native tide
#

so i make my own one is that correct?

calm plume
#

Yes

native tide
#

do i have to put quotation mark around the link?

calm plume
#

I think so

mighty meadow
#

background-image: url("http://link")

native tide
#

aoopy.PIE for the pythonUtilLib.pypl

cerulean badge
#

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)

bright saffron
#

any website u know

ivory bolt
# bright saffron where can i get a free tutorial on django

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...

โ–ถ Play video
topaz basin
#

guys anyone know how to setup lottie for web

primal thorn
#

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

rain delta
#

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

ivory bolt
ivory bolt
rain delta
#

ok , i am working in a virtualenv , i am thinking about installing ipython in it

ivory bolt
#

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

ivory bolt
rain delta
#

ok , thanks

inland oak
#

All right. What would be easier...
adding pre rendering for Create React App or switching to Next.js

west mulch
#

is anyone using flask

velvet yew
#

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

ocean carbon
inland oak
velvet yew
velvet yew
#

But how do I submit stuff to my python script from the front end?

velvet yew
#

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

inland oak
velvet yew
#

I've went through that already but didn't understand a single line of it

#

The examples are way too complex

inland oak
#

start from the begining of the tutorial or get youself one of the..... beginner friendly django books

#

I can get you authors

velvet yew
#

A fucking book lol

native tide
#

How does nested list work

cerulean badge
#

but you reference it as you would reference other elements

#
list_a = [1, ['a'], 3]
list_b = list_a[1] # ['a']
hasty path
hasty path
dusk portal
#

So many Aryans yes!

velvet yew
inland oak
#

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)

cerulean badge
#

when should i use clean method and when validators? (context django)

calm plume
obsidian steeple
#

i'm new in web dev..., please gimme some resources/tutorials

ember adder
#

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.

cerulean badge
ember adder
#

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.

cerulean badge
#

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

inland oak
#

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

calm plume
#

I'm pretty sure you can add SSR to CRA

inland oak
#

I would prefer remaining as CSR application

#

because SSR would increase complexity to infrastructure as far as I get

calm plume
#

Eh, not really

#

I use Next with SSG and I don't even notice

inland oak
#

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?

inland oak
#

I get it that... the choice perhaps can be varied depending on the content of the web site?

calm plume
#

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

inland oak
# calm plume I don't even notice SSR/SSG, although I've been paying more attention with my la...

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%

Next.js pages are React Components exported in a file in the pages directory. Learn how they work here.

#

they make pre render being flexible... to be full pre render, or pre rendering only shell, which will be populated with fetched data lately

calm plume
#

Yes, static generation will always be best

inland oak
#

Next.js is flexible to work in both ways

calm plume
#

The Next discord is saying the exact same things you are now lol

calm plume
#

Be warned, it's rather active because of the conf

dusk portal
#

i was learning Generic views and made some changes after that this error started coming

#

@ember adder yo sir

ember adder
#

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.

dusk portal
#
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'),
]
#

๐Ÿ‘€

ember adder
#

Paste the stack trace, you can switch to copy/paste view from the wegpage

lavish prismBOT
#

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:

https://paste.pythondiscord.com

rustic moss
#

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).

dense slate
#

@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.

quick cargo
dense slate
#

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.

quick cargo
#

why dont you actually write a project

dense slate
#

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.

quick cargo
#

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

dense slate
#

I mean, fake it till you make it I guess, sure.

quick cargo
#

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?

dense slate
#

This is a most bizarre conversation. ๐Ÿ˜„

lethal flicker
#

is flask the best for starter?

quick cargo
dense slate
#

@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.

lethal flicker
#

i see

dense slate
#

@rustic moss Why are you even applying for entry level coding then?

quick cargo
#

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

dense slate
#

A team of 4 people could literally create anything.

#

That's your answer.

quick cargo
#

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

dense slate
#

Ok, one person could create the backend, one could do the front end.

quick cargo
#

they'll expect that you're more competent than you are

dense slate
#

Two would do it faster.

quick cargo
#

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

dense slate
#

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.

quick cargo
#

CoffeeSip 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

inland oak
#

One little right question and the lie will fall apart.

quick cargo
#

"So what cache backend did you use"

dense slate
#

@rustic moss The whole point is that you don't understand what we're saying, that ANYthing could be created.

quick cargo
#

If it's someone who knows Django

#

"Did you use any model mixins"

dense slate
#

4 people could create a solid app in about 3-4 months, maybe less.

#

But, that could be literally anything.

quick cargo
#

CoffeeSip well just say you made amazon

dense slate
#

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.

quick cargo
#

oh yeah

inland oak
quick cargo
#

yeah it is

#

although mostly front end wise

inland oak
#

There is github project that collects the list of them

#

Clone wars named

quick cargo
#

you can make a basic version of amazon in Django in no real time if you're familiar with it

slate locust
#

Is there some sort of channel where we can advertise in here?

quick cargo
#

no

slate locust
#

Or is advertising banned?

quick cargo
#

we dont allow advertising

slate locust
#

Oh ok

dusk portal
#

hey

dense slate
#

hey what

dusk portal
#

plz help me out

patent cobalt
#

@dusk portal Could you switch to the copy-and-paste view of the traceback and copy it here as text?

dusk portal
#
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,)))

patent cobalt
#

Oh, I see the issue

dense slate
#

You are putting a tuple somewhere as an argument that wants a string, or other specific thing.

patent cobalt
#

It's the comma behind template_name='app1/index.html'

#

First line of IndexView

#

It turns that string into a tuple

dusk portal
#

oh

#

wait

#

lemme see7

#

got it

#

Lfmao

#

u know what this proves , this proves aryan yes aryan is bot coder @patent cobalt

ember adder
#

Sorry @dusk portal I waited a long time to receive your traceback and then I got back into the Con I was virtually attending.

dusk portal
#

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

dapper solar
#
@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?

ember adder
#

Aren't you missing methods attribute in your @app.route decorator?

dapper solar
#

no its there.

#

just forgot to copy that

#

TypeError: result() missing 1 required positional argument: 'nm'

dense slate
#

does redirect work that way? I usually pass/return a context/dict.

indigo kettle
#

here they retrieve the args through request.args.get(argname)

dapper solar
#

but request.for[""] should be working right?

#

and why is it giving missing argument i dont get it

visual saddle
#

Hi All

#

I have <Courses:[course str representation]>

#

i want to get course instance based on that is it possible?

indigo kettle
#

it depends if the string representation is unique or not

visual saddle
indigo kettle
#

then you can get that instance based on that unique thing, where are you stuck?

visual saddle
#

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

indigo kettle
#

nice

visual saddle
#

programming is awesome โค๏ธ

indigo kettle
#

np, haha glad you think so!

visual saddle
#

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

indigo kettle
#

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
visual saddle
#

as per docs, we dont have queryset attribute for StringRelatedField

indigo kettle
#

in that case, maybe stringrelatedfield is not writeable

visual saddle
#

because it is read only

visual saddle
indigo kettle
#

in which case you should use a primarykeyrelatedfield if you want to write to it

visual saddle
#

it is numbers, i dont like numbers

#

i like titles names and et

#

will try slugrelatedfield again

indigo kettle
#

unfortunately, computers like numbers

#

using pk is very common

#

and you will see it very often

#

slug should work as well though

foggy bramble
#

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?

visual saddle
#

thank u

frosty glen
#

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

noble spoke
#

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

wispy rover
#

hello, is it ok to ask questions about fastapi here?

frosty glen
#

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

outer apex
#

Mate, without code, nobody can help

frosty glen
#

Is it the fault of the android app that merely calls the url? how does that even happen

noble spoke
indigo kettle
#

what is being used to write the app?

#

the android app

frosty glen
#

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?

indigo kettle
#

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

frosty glen
#

Well I see what you mean

frosty glen
#

I simply used the url on chrome, and it messed up the queries executed

indigo kettle
#

can you get into the devtools of the android app and see the requests being called?

#

why is the request taking so long?

frosty glen
#

so you cannot reproduce this locally at all

frosty glen
#

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

indigo kettle
#

like mariosis voiced, I have doubts that it is the fault of the framework

frosty glen
#

it's a simple request call so there isn't much debugging there so not sure why

frosty glen
#

rarely it does :/

noble spoke
#

Is it the same request or is one a redirect

wispy rover
#

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

visual saddle
#

Hi All

#

is there any ways to add extra field to modelSerializer ?

indigo kettle
#

like this?

visual saddle
#

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

indigo kettle
#

you want to serialize the nested model?

visual saddle
#

in GET yes

#

i can easily do it

#

with the separate serializer class

indigo kettle
#

yes

visual saddle
#

ALL the details of nested object which i am not intended to do

indigo kettle
#

does your model have defaults on them, and you may need to specify required=False in your serializer

visual saddle
#

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 ๐Ÿ™‚ ?

indigo kettle
#

I understand but am not sure of the answer

#

hopefully someone else will know

visual saddle
#

which function is run before validation?

#

when we try to save?

#

i am talking about modelserializer

ashen sparrow
#

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)

proper hinge
#

requests.request(method.upper(), url, data=payload)

#

Also, it's redundant to put parenthesis for if statements.

ashen sparrow
#

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?

inland oak
#

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

#

jzts and Intl libraries

#

apperently Intl perhaps even inbuilt

ashen sparrow
#

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.

jolly star
#

is there a way to check if a button was clicked

inland oak
jolly star
#

i dunno js ๐Ÿ˜ฆ

#

but i want it such that on click it displays some data

#

under the form

mortal ruin
#

Does anyone have any idea of this

outer apex
# jolly star but i want it such that on click it displays some data

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.

outer apex
native tide
#

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?

mortal ruin
native tide
#

But if i type the keywords_uploaded myself

#

it works

outer apex
native tide
#

oh alright

#

I do that by saying

#
@app.route('/keywords_uploaded', method="POST")
def ksjkmskmm....````
#

right?

outer apex
#

Read the doc I linked

native tide
#

that worked

#

thank you so much

jolly star
grand oriole
#

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.

coarse heart
rigid prairie
coarse heart
native tide
#

isn't it on "GET" by default?

grand oriole
coarse heart
rigid prairie
#

Unable to write into user settings. Please open the user settings to correct errors/warnings in it and try again.

#

error

coarse heart
rigid prairie
#
{
    "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"
    }
}
rigid prairie
coarse heart
rigid prairie
#

it says the above json there is some error

coarse heart
#

That's too common

#

Just reinstall

rigid prairie
#

but same error

primal thorn
#

how do i import a .sql file to my django db

inland oak
#

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

primal thorn
#

i already decided on phpmyadmin cause im more familiar with it, thanks tho!

inland oak
#

shrugs.
anything that suits you

outer apex
zealous moth
#

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

primal thorn
#

my table in the admin panel has an extra s, my model is the correct spelling, what is causing this?

#

my model:

zealous moth
#

Django itself add s in modela

primal thorn
#

ohh

#

ok thanks

zealous moth
#

Welcome

ivory bolt
#

I never noticed this

#

just run makemigrations categories once more

jolly star
primal thorn
#

how do i make it so that instead of objects, my values display as rows like how the user table does it

rugged charm
#

@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'

mystic vortex
#

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

coarse heart
#

I'll help you out in a bit

dapper solar
#

how can we get a boolean value from a checkbox/toggle button in flask?

#

get args gives None

tepid parcel
#

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

ivory bolt
#

return self.title

dusk portal
#

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
primal thorn
ivory bolt
dusk portal
ivory bolt
#

no

#

so your view names

#

Trying naming them as the model name plus generic view name

ivory bolt
#

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

dusk portal
#

lol

#

got it

#

i was naming it

#

Models=Question

#

it was

#

model = Question

#

im dumb

ivory bolt
#

omg didn't notice that myself

graceful flax
#

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

fresh dragon
#

#help-broccoli i need some help with selenium, would be very nice if someone can take a look please
Thank you

opaque rivet
dapper solar
#

it gives None

#

i cant get a boolean value

#

how can i track value as its changed?

topaz basin
#

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
opaque rivet
# dapper solar how can i track value as its changed?

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

opaque rivet
topaz basin
#

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

#

๐Ÿคฆโ€โ™‚๏ธ

opaque rivet
#

so, what even is your question?

opaque rivet
# tepid parcel Hello everyone, i am currently try to migrate from Strapi to FastAPI i wonder no...
  1. 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).

  2. 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

opaque rivet
# dapper solar ohh :(

It's not a bad thing, for web-dev you will always have to learn JS later down the road.

dapper solar
#

i see

calm plume
#

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

topaz basin
#

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" ?

https://youtu.be/0-LGAjW6BUk

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...

โ–ถ Play video
dapper solar
#

@rugged charm it returns an empty list. Wait I'll send the html side code

rugged charm
dapper solar
#

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> ```
rugged charm
dapper solar
#

oh okay

#

let me try it

#

request.form.getlist["toAdd"] like this?

rugged charm
dapper solar
#

i just have one tho

rugged charm
dapper solar
#

ok

#

shows key error now

#

T_T

#

ok so can I just add a button instead an get a boolean value from it?

rugged charm
rugged charm
obtuse kelp
#

Has someone tried to send protobuf data through flask-socketio? ๐Ÿค”

dapper solar
rugged charm
rugged charm
dapper solar
#

ok changed it

#

ok still same. Let me go through the user input thing once more

west mulch
#

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_]+)$']
rugged charm
dapper solar
#

oh so what should I put there?

rugged charm
dapper solar
#

okay

rugged charm
native tide
#

Any good tutorials teaching PyQT6 ?

#

or pyQT5

royal cloak
#

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.

gritty cloud
#

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...

โ–ถ Play video
#

helped me a bunch when i was learniung

west peak
#

How can i work with dates before consult them in the database?

gritty cloud