#web-development

2 messages · Page 105 of 1

steady cypress
#

no timeout

#

just put that in your <script> element and after 3 seconds you will see a cool thing

vivid spear
#

peeps

limber laurel
#

What exactly does {% load static %} do?

silver shell
#

@vivid spear peeeeps

nova nacelle
#

What exactly does {% load static %} do?
@limber laurel it just loads your static folder... then you could just type {%static' urlinsidestaticfolder'%} as the url to get the files in it.

limber laurel
#

Thanks

#

And if I for example had a media direcotry I could techinaclly load media the same way right?

stable kite
#

no

#

you can't load media directory

nova nacelle
#

like if there is an images folder inside the static folder... then you just type {%static 'images/name.format'%}.

#

And if I for example had a media direcotry I could techinaclly load media the same way right?
@limber laurel you can't load it... just have it in static folder.

limber laurel
#

ok

nova nacelle
#

@limber laurel you can't load it... just have it in static folder.
@nova nacelle and follow the {%static' '%} thing.

sturdy coral
#

Any react devs here?

static harbor
#

how can I convert csv to excel and send it download without saving locally

#

for example I have a excel file I upload it and convert it into dataframe and in the same view I change some data in the dataframe now I want that data frame to convert into excel and download it to user

response=HttpResponse(data.to_excel("a.xlsx"),content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename=%s_Report.xlsx' % excel_file.name
in this case it get saved locally with name of a.xlsx
I AM using django

vivid spear
#

why does it return a 404 error?

wanton ridge
#

I wanna do if the user account exists in the database the it will redirect to my homepage

#

even if i type the correct datas in the login and click on submit i am getting the msg

#

anyone know what i am doing wrong?

vivid spear
vivid canopy
#

hey guys i have a bit problem i want connect it to styl.css file that link rel but idk why it just doesnt react anyway. i tired a lot of ways but any of them worked can anyon ehelp please?

versed python
#

@vivid canopy try removing the first slash in your href

vivid canopy
#

i did it also with it but didnt work i can try it agian

#

nothing changed

#

this is maybe some error report from cmd "127.0.0.1 - - [25/Oct/2020 12:24:02] "GET /demoapp/visualize/styl.css HTTP/1.1" 404 -"

remote ruin
#

hey guys, when should i use breakpoints for responsiveness?
my homepage loooks fine at 500px now and i wondered when to set the media-queries

raw vortex
#

@vivid canopy Have you tried something like <link rel="stylesheet" href="{{ url_for('visualize', filename='styl.css') }}" /> (you will need from flask import url_for)?

remote ruin
#

added: i can use them whenever i want i know, but when is it best to use, are there some standards?

vivid canopy
#

@raw vortex didnt try it but now i m reding something like in templates shouldnt be home or about page. bur thanks i will try it

#

it didnt worked

raw vortex
#

Can I see what you tried to do?

vivid canopy
#

me?

raw vortex
#

Yes

vivid canopy
#

okey so in about and home.hmtl is just h1 wich says this is home / about page

#

in styl. css is just body {background color grey}

#

just that prob it dont want to connect with css

#

i already tried evrything

raw vortex
#

What I would suggest is to have a different folder for your non-template files. For example, you can have:
demoapp ├── templates │ ├── index.html └──── assets └── css └── styl.css

vivid canopy
#

i can try it but

raw vortex
#

Then, you can change your linktag to <link rel="stylesheet" href="{{ url_for('assets', filename='css/styl.css') }}" />

long abyss
#

I am a team lead in Dubai and looking to work with a remote engineer who has at least junior level of technology. 👋👋👋👋👋 🇦🇪
It will be part time work at first.

  • Basic understanding of technical - at least junior developer
  • Experience working remote.
  • Open-minded and think out of box.
  • Always kind & cooperative.
    DM me for more details
vivid canopy
#

@raw vortex didnt work gonna try another things but ty for your time

native tide
#

b'1::F::1::10::48067\n',
b'2::M::56::16::70072\n', here i wanna omit b and \n in each line

vestal hound
#

b'1::F::1::10::48067\n',
b'2::M::56::16::70072\n', here i wanna omit b and \n in each line
@native tide what do you mean "omit b"?

#

so you want to replace '\n' with nothing?

stable kite
#

@native tide #bot-commands message
#bot-commands message

native tide
#

@vivid canopy You need to use {% load static %} then provide the src as "{% static path %}"

#

Oh you're using flask

#

It's something similar to that it's on stackoverflow somewhere

vivid canopy
#

i fell like i will rip my hair out

#

i made new env from the start

#

and this is what i get jinja2.exceptions.TemplateNotFound: templates/home.html

#

if i have just return render_template('about.html') site writes me back jinja2.exceptions.TemplateNotFound: inedx.html

native tide
#

Show the code

quick cargo
#

is it in a top level folder called templates

vivid canopy
#

yes

#

so in home and about html is again just h1 this is home/about page

native tide
#

Have you tried making your styleshert href = url_for(filename in templatefolder)

vivid canopy
#

didnt but i have other prob it dont even open site

quick cargo
#

does it load any other templates?

vivid canopy
quick cargo
#

okay

vivid canopy
#

/about /home any of them doesnt work

native tide
#

It says indenx. Html

#

So you have a typo

#

Rerun the code to update it

vivid canopy
#

like rerun?

quick cargo
#

restart it

vivid canopy
#

like trough cmd or whole visual?

#

heh

#

same

quick cargo
#

as in -> turn it off -> turn it on again

vivid canopy
#

i did same

quick cargo
#

whats the html for home and about

#

!paste

lavish prismBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

quick cargo
#

put it in there^

vivid canopy
#

in home ist just extands index.html and it says h1 this is home page

quick cargo
#

you get the same error or what

#

need to see code

vivid canopy
#

doesnt work trough link

#

same about.html

native tide
#

yeah... so there's your typo

#

you said inedx.html

vivid canopy
#

what i have to do?

native tide
#

don't you see your error?

vivid canopy
#

in vs?

vivid canopy
#

in vs any errors

native tide
#

What is the error?

#

From that message

#

jinja2.exceptions.TemplateNotFound : inedx.html

#

What does that mean? In your code you tried to load a template caleld inedx.html but there is no such template.

#

Now find where you typed that.

#

And change it to what it should be

vivid canopy
#

propably i know what u mean

native tide
#

do you understand what the error is telling you?

vivid canopy
#

yes but i didnt call file template if i understand it right render_template calls file templates automaticly like u dont need to connect it with code like if u understand me

quick cargo
#

You tell it what it extends though

#

and rn you're telling it extends inedx.html

native tide
#

^^

#

And that extends is trying to load a template which doesn't exist.

vivid canopy
#

now i absolutly dont understand i m mixed

vivid canopy
#

okey thanks i fixed it with that extends

#

deleted it and it goes

native tide
#

@vivid canopy Can you explain what extends does?

static harbor
#

how can I simultaneously return response and render html by same view?

for example I want to acheive this

wb.save(response)
 return response,render(request,'location/index.html',{'columns':data.columns.values.tolist(),'rows':data.to_dict('records')})
vivid canopy
#

propably it takes from index.html form taht block to that site where is extends

quick cargo
#

. not ,

native tide
#

response.render() renders a template?

vivid canopy
#

thanks guys but maybe in few mins i will have a nother prob with that link rel

#

sry D

quick cargo
#

mostly the top half

native tide
#

@vivid canopy extends "template" adds your {% block content }% to that template. It's Flask template inheritance.
Read about it here to understand:
https://flask.palletsprojects.com/en/1.1.x/patterns/templateinheritance/

You tried to extend to a template which doesn't exist. "inedx.html" is not "index.html" so it's a typo. You could've changed the filename and it would've worked.

vivid canopy
#

cool elegant and it looks easy to orientation @quick cargo

native tide
#

@quick cargo It's nice. Maybe have the black div extend lower?

quick cargo
#

i sorta wanna keep how low the black goes the same rn because the lower half will look better with the lighter

native tide
#

Also just my opinion but the top right discord button looks a bit out of place

#

The text of the button doesn't really line up with the text of the navbar

#

but that's just nitpicking

quick cargo
#

probably a dodgy margin

naive current
#

hi! anyone here good with jquery?

vivid canopy
#

okey guys sry for hussle u but i have 2 more probs one is with that link rel

#

and second problem is with this ul and li it doesnt show propably its not called but idk rly

quick cargo
#

@native tide can you not spurt random nonsense in every channel

haughty turtle
#

So I have about 25 items that I need to rotate through on my main page, but I am only displaying 3 at a time. To do this is it through Django or JS

native tide
#

Why is there like 50 chemical names

haughty turtle
#

Those are the help channels @native tide and wrong channel to discuss that in

native tide
#

@vivid canopy also use endblock not endblock main

silver shell
#

anybody ever managed to add a custom page in django admin panel?

haughty turtle
#

Hmm, so to create a slider to obtain my items from the DB through Django and display them using VueJS

limber laurel
#

<link rel="stylesheet" href="{% static css/style.css %}">

#

Could not parse the remainder: '/style.css' from 'css/style.css'

#

I get this error

#

What is causing it?

#

Even if I add ``

native tide
#

Try {% load static %} above it

limber laurel
#

I already have load static in the file

#
<!DOCTYPE html>
{% load static %}
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="{% static `css/style.css` %}">
    <title>{{ video.title }}</title>
native tide
#

In your settings.py you might need to set your static directory

#

If I remember correctly

limber laurel
#
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),
]
#

This thing?

native tide
limber laurel
#

STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),
]
#

seems like I should have everything for it to work

#

at least in development

stable kite
#

@limber laurel which django version do you use?

near bison
#

Opinions on this site design so far?
@quick cargo How do you make that wave like seperation ? is is an svg? i have seen that kinda design, but never looked into how to do it

native tide
#

@limber laurel so can you show us your directory layout

quick cargo
#

@near bison svg ye

limber laurel
#

How can I get the tree in the terminal?

near bison
#

what part is the svg?

stable kite
#

@limber laurel which django version do you use?

near bison
#

like .. Is the gradient also in the svg?

limber laurel
#

3.0.8.

#

@stable kite

stable kite
#

@limber laurel try this py STATICFILES_DIRS = [ BASE_DIR/'static', ]

limber laurel
#
TypeError: unsupported operand type(s) for /: 'str' and 'str'```
#

I think what you are trying to say does the same as join

stable kite
#

@limber laurel in the new version of django we can do directly this

#

this is a shortcut because django uses pathlib

limber laurel
#

Well if I use the snippet I get an error

#

@stable kite

#

and in the static directory I have css directory

#

and then I have a style.css file

#

Wierd

#

It just started randomly working

#

But for some reason when I make changes in my css I dont see the new changes

pulsar hinge
#

But for some reason when I make changes in my css I dont see the new changes
@limber laurel It happend like that? No errors?

limber laurel
#

That was some glitch now it works

#

No error

#

Now it seems to be working

#

really wierd

pulsar hinge
#

If it ever happens again just go into inspect mode, network, right click ur style.css and click clear browser cache and cookies. Refresh the page and shoudl be working fine

limber laurel
#

Ok

mossy hamlet
#

Hi!
Sqlalchemy page shows that I can work with sessions like that:

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

# an Engine, which the Session will use for connection
# resources
some_engine = create_engine('postgresql://scott:tiger@localhost/')

# create a configured "Session" class
Session = sessionmaker(bind=some_engine)

# create a Session
session = Session()

# work with sess
myobject = MyObject('foo', 'bar')
session.add(myobject)
session.commit()

However, whenever I do session = Session() in my Flask app, the whole thing hangs.
For more context - I'm doing the engine and sessionmaker instance (Session) in my init file, and importing this Session into another file where I do session=Session().
I have been googling around and can't figure out what I'm doing wrong.

native tide
#

@limber laurel oh.. so your CSS page wasnt loading in the browser? Just CTRL F5 each time you make updates as that'll clear browser cache to load the css as its saved in cache.

stable kite
#

@limber laurel have you added this in your urls.py

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)```
limber laurel
#

Yeah

#

Added that when was setting up media files

radiant aurora
#

Hi Guys, need some help with deplying an django app on heroku

#

Can anyone help?

#

Getting this error

#
git push heroku main
Enumerating objects: 1011, done.
Counting objects: 100% (1011/1011), done.
Delta compression using up to 4 threads
Compressing objects: 100% (402/402), done.
Writing objects: 100% (1011/1011), 4.12 MiB | 120.00 KiB/s, done.
Total 1011 (delta 578), reused 1007 (delta 576)
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz
remote:        More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure
remote:
remote:  !     Push failed
remote: Verifying deploy...
remote:
remote: !       Push rejected to duspy.
remote:
To https://git.heroku.com/xyz.git
 ! [remote rejected] main -> main (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/xyz.git'
rapid bramble
#

Anyone willing to make a quiz application? Has to be in Django, and I'm paying for it, though not much.

#

Ping or DM me if you are interested.

toxic flame
#

Quiz app?

#

@rapid bramble what will it be about?

rapid bramble
#

Sending on DM.

toxic flame
#

ok

jolly pilot
#

How can i get a list of servers user is in and check if user is administrator with flask-discord?

#

Ping if answering

rapid bramble
#

Answer is you can't @jolly pilot

#

And pretty obvious

jolly pilot
#

How

#

How does mee6 for example do it?

#

@rapid bramble

rapid bramble
#

Because it's on a lot of servers and it just checks mutuals

jolly pilot
#

But

#

Explain why discord has 'know what servers youre in'

rapid bramble
#

That's only for an individual

#

Not meant to be seen by others

jolly pilot
#

Wdym

#

I just wanna display the server list on the website

#

And see if the user has manage_guild perms

#

@rapid bramble

nova nacelle
#

Anyone willing to make a quiz application? Has to be in Django, and I'm paying for it, though not much.
@rapid bramble Can you elaborate?

rapid bramble
#

Sending a DM

nova nacelle
#

Okay.

rapid bramble
#

@jolly pilot Oh, you mean display his own list, that's doable via Oauth2 callback

jolly pilot
#

Yes

#

But how

#

fetch_guilds gives me an empty list

#

getting the username and profile picture works fine but getting guilds just does not work

nova pendant
#

pretty simple question, im running a quick and dirty Quart server to test the payload of another application, however i cant seem to print anything out to the console: ```py
from quart import Quart, websocket, request

app = Quart(name)

@app.route('/death')
async def hello():
print("test")
return 'hello'
app.run()

#

i can see something was posted but i cant get anything to print, be it the request, the payload, or anything else such as just 'test'

#
[2020-10-25 10:11:48,767] 127.0.0.1:60752 POST /death 1.1 405 137 997```
nova nacelle
#

I guess because it returns 'hello'?

nova pendant
#

?

nova nacelle
#

wait.

nova pendant
#

it should print before it returns anything

#

the second code box i sent is the entire console output, i need the request payload to print to the output but nothing is printing

nova nacelle
#

okay i see it now... I'm really working so just paid half attention to that.

minor pumice
#

I am looking to send request from one user to another in django can some tell me how can I do that!!?

vivid canopy
#

guys want to ask how can fix problem with reloading site for explain lets say i have in main.py port set to 1717 and lets say sites background in css is set to grey color so next i change grey to green and let port stay to be 1717 reload site and sites background is still grey but if i change port lets say to 1716 and load site again with port 1716 , sites background is green. So dont u have anybody experience with this how to fix it?

#

should be problem with this link? <link rel="stylesheet" type='text/css' href="{{ url_for('static' , filename='style.css') }}">

toxic flame
#

linuxrechrips

#

@vivid canopy i suppose that's flask

vivid canopy
#

yeah

toxic flame
#

@minor pumice ForeignKeys?

vivid canopy
#

flask

toxic flame
#

Sorry I know 0 flask xD

vivid canopy
#

foreignkeys?

toxic flame
#

ForeignKeys can be used to connect users / models which can be accessed

#

@vivid canopy talking to Rahul

vivid canopy
#

aha sry

minor pumice
#

I am using django notification along with it

#

I am looking send accept and decline option from one user to another

toxic flame
#

oh

#

Let me see

vivid canopy
#

@toxic flame dont u know how is this problem called in django propably its similiar problem so i can better search for some solutions?

silver shell
#

Anybody here had any success making a custom page in django admin board?

toxic flame
#

@vivid canopy in django you just add a STATIC_URL on settings and then on the template:

{% load static %}

{% static 'css/stlye.css' %} to load the css

native tide
#

@vivid canopy CTRL + F5 in ur browser

#

resets browser cache and therefore css

toxic flame
#

yea sometimes css doesn't load in real time for me

native tide
#

bc it's saved in cache which needs to be reset for you to see updated code

vivid canopy
#

@native tide whaaat it works thanks a lot

native tide
#

👍 it was a big issue when I was at that stage

#

just stackoverflow it lol 🙂

strange briar
#

hey guys, anyone works with FastAPI ? I have a question about the structure of a project, i would like to implement OAuth2 following this tutorial https://fastapi.tiangolo.com/tutorial/security/oauth2-jwt/ but i don't know where should i put my code for it, so for now i placed the source code at auth.py in the main folder but i don't know

native tide
#

I'm sending a request to my API and all my fields are empty. But, my serializer is only returning an error this field may not be blank for 2 out of 3 of my fields...

#
class UserSerializer(ModelSerializer):  # In DRF serializer validation is done serializer-side
    class Meta:
        model = Users
        fields = ["username", "email", "password"]

    username = CharField(max_length=20, allow_null=False, required=True,
                         validators=[UniqueValidator(queryset=Users.objects.all(),
                                                     message="Username is taken, try something else"),
                                     MinLengthValidator(4, message="Username is too short (<4 characters)")])

    email = EmailField(allow_null=False, required=True, validators=[UniqueValidator(queryset=Users.objects.all(),
                                                   message="An account with that email already exists")])

    password = CharField(allow_null=False, required=True, max_length=100)```
#

The password field isn't getting the validation. But the only difference is that it doesn't have the UniqueValidator validator... how strange

#

Anyone know how I can fix this?

#

I made a fix. In my serializer if any of my fields are empty it returns a dict with key error so in my JS I checked if the response object contains and error key and it will render one message saying that the form is incomplete, rather than a seperate error message for every field.

#

So yeah that's pretty much done. Now I need to do session auth and I don't understand it 😄

snow sierra
native tide
#

farmer propoganda

trim star
#

Is it possible in python/django to verify that a file extension matches its type?

#

I know in linux the file command does this but I want to avoid executing this command via subprocess if I can do it in python natively

vestal hound
#

Is it possible in python/django to verify that a file extension matches its type?
@trim star what do you mean "matches"?

#

like whether a file with a particular extension is actually what it advertises?

trim star
#

for example, verify that example.jpeg really is a file of type jpeg

#

Yes @vestal hound

vestal hound
#

ah

#

I'm not sure if there's a library for that

#

there probably is

#

but if not, it's not a very hard problem, but it is a wide one

#

because the difficulty of verifying if a file is the type it's supposed to be varies, right?

#

e.g. how do you tell if a Python file is a valid one? you have to compile it.

#

but I guess you only want to do this for a specific set of extensions, right?

trim star
#

@vestal hound yes

vestal hound
#

@vestal hound yes
@trim star namely?

trim star
#

pdf, jpeg, png @vestal hound

#

docx

vestal hound
#

okay

#

if you can't find a prebuilt solution

#

I'm sure each of these has some kind of header

#

you can open the file and check for that

trim star
#

@vestal hound yes. I think security wise if I cannot find a well supported solution, then doing that myself in native python is better than calling subprocess and more platform independent

native tide
#

Hi guys, how can I pass a value to javascript in a jinja template from flask?

mortal mango
#

is there a way I can edit the error pages (404, 403, etc) on my apache web server?

spiral smelt
gaunt marlin
#

@native tide from your flask view, you can pass context variable to template, and in the template you can use {{ variable }} anywhere for example:

<script>
  var a = "{{ variable }}";
</script>
plucky tapir
#

django, does anyone have experience with no reverse match error? Apparently its due to an html url call

zealous tusk
#

Can anyone help me with fetching data from django models and applying it into my templates. I am a vey beginner of django?

gaunt marlin
#

@plucky tapir the error will show up if django can't find the url you specified, are you using url's name in your code to specify or the url path itself? it's better to use url's name as it work like variables

stable kite
#

@zealous tusk show your model

gaunt marlin
zealous tusk
#

okay wait

native tide
#

@native tide from your flask view, you can pass context variable to template, and in the template you can use {{ variable }} anywhere for example:

<script>
  var a = "{{ variable }}";
</script>

@gaunt marlin aight thnx

plucky tapir
#

@gaunt marlin path('<int:pk>/update/', views.updateRegister, name='update'),

It has to be something with my primary key?
<td><a class="btn btn-sm btn-info" href="{% url 'update' Userinfo.id %}">Update</a></td>

gaunt marlin
#

@plucky tapir can you show the full error?

#

is Userinfo a context variable you passed to the template?

plucky tapir
gaunt marlin
#

@plucky tapir here is the problem
with arguments '('',)' not found

your Userinfo.id return a tuple with a blank string element inside of it

#

check why it return that instead of an integer

plucky tapir
#

would Userinfo.id be the way to pass the pk? @gaunt marlin

gaunt marlin
#

@plucky tapir you pass your model query as variables to the template right?

#

have you tried to see {{ Userinfo.fname }} show up in your template?

#
yourview(request):
  ...
  query = YouModelName.query_stuffs
  return render('template_path.html', {
     'a_variable': query
})
#

this is an example

#

so i can use {{ a_variable.model_attribute ]} on template to render

plucky tapir
#
    Userreg = Userinfo.objects.all()

    context = {'users': Userinfo}

    return render(request, 'users/dashboard.html', context) ```
#

@gaunt marlin objects.all() passes it correct?

gaunt marlin
#

yes

#

@plucky tapir wait that is wrong

#

you set variable of your query as Userreg

#

and you settings {'users': Userinfo} which is wrong

#

it supposed to be {'users': Userreg}

#

and in your template @plucky tapir

{% for user in users %}
  {{ user.id }}
{% endfor %}
#

you should pass variable instead of model name

plucky tapir
#

@gaunt marlin would I need to add anything in the url 'update' button?

gaunt marlin
#

@plucky tapir not yet, first you need to fix your view code like i mentioned above

#

you passing the wrong thing to your context variable

#

that why it returned empty tuple

#

here the fix
your view:

 def home(request):
    Userreg = Userinfo.objects.all()

    context = {'users': Userreg}

    return render(request, 'users/dashboard.html', context) 

your template(just an example, apply to your template logic):

{% for user in users %}
  {{ user.id }}
{% endfor %}
#

you users = Userinfo.objects.all() when you set from template

plucky tapir
#

@gaunt marlin {% block content %}<h5> Hello {{user.username}} {{ user.id }}</h5>

#

I can see the username and user id although I have a model called Userinfo that I cannot really display any information from

gaunt marlin
#

@plucky tapir user is an instance of your Userinfo model, you can display any of the Userinfo attributes like normal. What is your goal ? I cannot really display any information from which information you looking for?

plucky tapir
#

For now it was first name last name and city from Userinfo, I also have a User model for Users to login with a password, but focusing on Userinfo at the moment, I had a button there for Update but I wasnt passing a pk properly so I removed it

gaunt marlin
#

@plucky tapir now you will be passing like this with different parameter variable

<td><a class="btn btn-sm btn-info" href="{% url 'update' user.id %}">Update</a></td>
#

remember pk in django is also any field that has primary_key=True

nova nacelle
#

django, does anyone have experience with no reverse match error? Apparently its due to an html url call
@plucky tapir can you share the ss of the error?

#

For now it was first name last name and city from Userinfo, I also have a User model for Users to login with a password, but focusing on Userinfo at the moment, I had a button there for Update but I wasnt passing a pk properly so I removed it
@plucky tapir is your query solved?

plucky tapir
#

I'm not sure what query solved is

nova nacelle
plucky tapir
#

view will be pretty messy, got stuck, started using both class based and function based

nova nacelle
#

view will be pretty messy, got stuck, started using both class based and function based
@plucky tapir Share that too.

plucky tapir
nova nacelle
#

@plucky tapir pn=models.CharField(validators=[RegexValidator("^0?[5-9]{1}\d{9}$")],max_length=15, null=True, blank=True). use this for the phone number. NOT RELATED TO YOUR QUE ANYWAYS

gaunt marlin
#

@nova nacelle i found out his problem earlier this is his view:

def home(request):
    Userreg = Userinfo.objects.all()

    context = {'users': Userinfo}

    return render(request, 'users/dashboard.html', context) 
#

he was passing the wrong context variable to the template

#

if you scroll up you can see my messages

nova nacelle
#

@gaunt marlin That is why i first asked- if his query is already solved.

gaunt marlin
#

he set users variable to Userinfo which is the model by mistake

#

it suppsoed to be {'users': Userreg}

nova nacelle
#

pn=models.CharField(validators=[RegexValidator("^0?[5-9]{1}\d{9}$")],max_length=15, null=True, blank=True). use this for the phone number.
@gaunt marlin what do you think about this?

gaunt marlin
#

i'm no expert in regex but that is not his error which he just posted
Exception Value: Reverse for 'update' with arguments '('',)

#

he was using this <td><a class="btn btn-sm btn-info" href="{% url 'update' Userinfo.id %}">Update</a></td> so you can see the problem

#

Userinfo

nova nacelle
#

@gaunt marlin I've mentioned that brother...

#

It was just an advise.

gaunt marlin
#

oh ok i though you went off topic

#

because that not related to the current problem

nova nacelle
#

@gaunt marlin Yeah, I just saw that he tried to import a phone field and later commented it and user a simple charfield... So, i just suggested using the regex.

gaunt marlin
#

we don't want to fall another one when the current solution isn't done

#

!xy-problem

lavish prismBOT
#

xy-problem

Asking about your attempted solution rather than your actual problem.

Often programmers will get distracted with a potential solution they've come up with, and will try asking for help getting it to work. However, it's possible this solution either wouldn't work as they expect, or there's a much better solution instead.

For more information and examples: http://xyproblem.info/

plucky tapir
#

What do y'all suggest, going back to cbv? Atm I'm wanting to create, details, update, delete input

gaunt marlin
#

@plucky tapir your current problem is this error right ?

Exception Type: NoReverseMatch at /users/dash/ Exception Value: Reverse for 'update' with arguments '('',)' not found
plucky tapir
#

@gaunt marlin Yeah

gaunt marlin
#

@plucky tapir now you will be passing like this with different parameter variable

<td><a class="btn btn-sm btn-info" href="{% url 'update' user.id %}">Update</a></td>

@plucky tapir have you tried my solution ?

plucky tapir
#

@gaunt marlin Alright so now its pulling up my user id, when I believe I need to pull up the primary key that is from the "Create" that I just made

gaunt marlin
#

@plucky tapir can you describe the flow more clearly? i'm having trouble understanding this I need to pull up the primary key that is from the "Create" that I just made

#

so you have dashboard page that list all the user info with a create button and an update button for each user. The create button will redirect to a create form, the update button redirect to the update form

#

is that what you trying to tell me ?

#

when you create an object from create form, you need to redirect to the dashboard page -> which will query the userInfo table again and list all the userInfo old and new

#

so the dashboard will list all users id order in ascended order

native tide
#

Unsure if this is the best place to ask. Currently researching to build a price aggregator for specific products would python be the best option for scraping ecommerce prices and feeding into a database? Any suggestions on front end frameworks would be appreciated.

gaunt marlin
#

@native tide for python there are dedicated package for scraping like scrapy and other. For javascript i can only think of https://github.com/puppeteer/puppeteer , but use what you more comfortable and needed

#

for frontend you might encounter javascript generated contents, for those you can use headless browser

native tide
#

@gaunt marlin have used scrapy in the past I haven't touched a scraper in a few years so just making sure it's still my best option needs to be highly scalable. Doing the leg work before I search for a developer.

gaunt marlin
#

there alot of tools, but i generally just use python requests and xml to get web content 😄

native tide
#

@gaunt marlin u can be highly naughty at an exceptional speed with requests 😄

gaunt marlin
#

as long as i'm not breaking the web site scraping rules and have not too much requests per interval

native tide
#

@gaunt marlin what do you think about single board computers hosting the scrapers and pushing results to web server vs having web server based scrapers??

gaunt marlin
#

@native tide i think it's based on your design, of course having a web scraper running in the background is much cheaper than using single board computers. I don't think web scraping would take that much resource if you have the correct flow

#

i'm no dev ops so i have little or no knowledge about VPS or AWS

native tide
#

@gaunt marlin I have around 50 odroids n2 sitting in a box and thought I could use them for this project.

gaunt marlin
#

i think you can use those if you want, but you have to be the one maintaining the hardware. I generally run scraper on the server then i only need to maintain the software not the hardware itself

#

imagine this: your android die - > server web still alive get no data
vs
the scraper only die when your server hosting the website

vivid canopy
#

hey guys wanna ask when i have this bar finished how do i make that if i click on it it send me to that site. dont want to know how to do it to details but want to know if i have add there buttn?

gaunt marlin
#

@vivid canopy you can use a tag with href attribute for it

<a href='https://www.google.com'>click to go to google</a>
vivid canopy
#

ty

native tide
#

anyone working django w/ react?

vivid canopy
native tide
#

just do it in css?

nova nacelle
#

Yeah

vivid canopy
#

idk what comand to use

stable kite
#

anyone working django w/ react?
@native tide yes

native tide
#

google it

vivid canopy
#

googling it for 45 min D

native tide
#

width: 35%

#

you're googling wrong 😄

vivid canopy
#

when i use this text goes from left

native tide
#

so you need to re-position your text...

#

which is another css tag

#

@stable kite Have you implemented any auth yet, session/token auth to be specific?

stable kite
#

@native tide yes

vivid canopy
#

i made tag for left and right text but when i used width text anyways goes from left

native tide
#

yes so re-position your text

#

use the internet to find the css tag for that

nova nacelle
#

Use margin-left:65%

#

And width:35%

gaunt marlin
#

you can use float: right or float:left in your div css

native tide
#

and just center the text.

vivid canopy
#

@nova nacelle thanks

native tide
#

@stable kite which auth method?

nova nacelle
#

@vivid canopy Your welcome.

stable kite
#

@native tide the inbuilt one

native tide
#

@stable kite I mean... session, token? Which one?

stable kite
#

@native tide session

native tide
#

within the API endpoints?

stable kite
#

@native tide no with ajax

native tide
#

could you upload your code for that?

primal kernel
#

Hey guys! some Django expert here? I just asked this in stackoverflow, could you help me with it? I know i'm missing something stupid but It's driving me crazy! https://stackoverflow.com/questions/64535154/django-not-showing-a-model-in-admin-page

stable kite
#

could you upload your code for that?
@native tide for that you should have both frontend & backend on the same sever

native tide
#

@primal kernel Have you done makemigrations?

primal kernel
#

Yeah I did it

native tide
#

and then migrate?

primal kernel
#

Ofc

#

And I can see the results in my DB, my only problem is that I can not see it in my admin page

native tide
#

@stable kite not really, but if you can upload your code I'll understand what you're talking about. How can you be doing session auth if it's not in the API endpoints 😄

stable kite
#

i am using POST ajax Request for that

native tide
#

Yea. So you're making a request to your API which handles the session auth?

stable kite
#

@native tide ```py
#views.py
def signin(request):
if request.method=='GET':
return render(request,'index.html')
elif request.method =='POST':
try:
username=request.POST['username']
password=request.POST['password']
try:
validators.validate_email(username)
print('hi')
username=CustomUser.objects.get(email=username).username
return function.signin(request,username,password)
except:
return function.signin(request,username,password)
except:
return JsonResponse({'status':'Failed','error':'Unable to get user data'})

else:
    pass        

def signup(request):
if request.method=='GET':
return render(request,'index.html')
elif request.is_ajax() and request.method =='POST':
try:
username=request.POST['username']
password=request.POST['password']
firstname=request.POST['firstname']
lastname=request.POST['lastname']
email=request.POST['email']
re_password=request.POST['re_password']
try:
validators.validate_email(email)
return function.signup(request,firstname,lastname,username,email,password,re_password)
except:
return JsonResponse({'status':'Failed','error':'Please enter a vaild email address'})
except:
return JsonResponse({'status':'Failed','error':'Unable to get user data'})
else:
pass

#

@native tide ```py
#functions.py
def signin(request,username,password):
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
return JsonResponse({'status':'Success','error':None,'uuid':user.uuid.hex},status=200)
return JsonResponse({'status':'Failed','error':'Please Enter the correct Username & Password'})

def signup(request,f_name,l_name,username,email,password,re_pass):
if password == re_pass:
try:
CustomUser.objects.create_user(username=username,email=email,password=password,firstName=f_name,lastName=l_name)
return JsonResponse({'status':'Success','error':None,},status=200)
except :
return JsonResponse({'status':'Failed','error':'Username already exists,Please try with other username',})
else:
return JsonResponse({'status':'Success','error':'Password dose'nt match,Please try again',})

native tide
#

Thank you 🙂

stable kite
unique glen
#

hey i used namecheap and hosted my google site
it works when i added www at the beginning but it does not works ( error 404 ) when i just typed sitename.me any help ?

vast dragon
#

you need to either add a DNS entry, or setup a redirect

pale hearth
#

Do you know if i can request a website with a specific local storage variable ?

#

Like have a different result depending of this value

#

for web scrapping

#

Or more easy, simulate a click on a button lemon_unamused

zealous tusk
#
{% for product in featured_products %}
<h4>{{product.product_name}}</h4>
{% endfor %}

#

Why I cant see this is my template .

#

But when I do this with python I get the required output.

#
def index(request):
    featured_products = Product.objects.order_by('product_name')[:4]

    # This gives me the correct output
    for product in featured_products:
        print(product.product_name)
    print(featured_products)
    context = {'featured_product': featured_products}
    return render(request, "shop/index.html", context)
#
class Product(models.Model):
    """
    This class defines the information related to a product. 
    """
    product_id = models.AutoField
    product_name = models.CharField(max_length=50)
    product_category = models.CharField(max_length=50, default="")
    product_subcategory = models.CharField(max_length=50, default="")
    product_price = models.IntegerField(default=0)
    product_desc = models.CharField(max_length=700)
    publish_date = models.DateField()
    product_img = models.ImageField(upload_to="img/home/", default="")
    product_rating = models.PositiveIntegerField(default=10, validators=[MinValueValidator(1), MaxValueValidator(5)])
    def __str__(self):
        return self.product_name
#

This is my model.

#

Ping me once, if you can help.

clear arch
#

Should I go with Django or Flask?

native tide
#

@zealous tusk Do u have featured_products in your context

#

django

clear arch
#

any advantages?

native tide
#

honestly it doesn't matter what u choose

clear arch
#

which is easier for begginers?

native tide
#

probably flask ig

zealous tusk
#

@native tide yes.

#

you can see the code above

clear arch
#

ig means I guess?

native tide
#

context = {'featured_product': featured_products}

#

shouldn't it be 'featured_products' for the key

clear arch
#

well thx for your suggestion

native tide
#

@zealous tusk

clear arch
#

Can you link me to some of django resources?

zealous tusk
#

lemme do it

#
def index(request):
    featured_products = Product.objects.order_by('product_name')[:4]
    for product in featured_products:
        print(product.product_name)
    print(featured_products)
    context = {'featured_products': featured_products}
    return render(request, "shop/index.html", context)
#

is this what you asked me to do right?

stable kite
#

But when I do this with python I get the required output.
@zealous tusk wdym?

deep bloom
#

a

zealous tusk
#

means when i itrate that featured_prod list i can see the names of products.

#

but i cant get it into template

#

yeah i solved the problem.. thanks guys

#

How to slice items in django ?

native tide
#

yes that was right

#

did it solve the issue?

#

if you do {% for product in featured_products %} the context key is "featured_products" but you had "featured_product" which isn't the same

#

and what do you mean by slice

zealous tusk
#

@native tide yes

#

slice means how can i display third element of a query set?

devout coral
#

Good Morning, does anyone here have some advice on how I should be handling caching and sessions in production for a Django web app?

native tide
#

@zealous tusk do model.objects.get(e.g. username="user").pk

#

and .pk gives you the primary key

#

so then you can find that element

zealous tusk
#

okay thanks man!

devout coral
#

Has anyone here set up celery for Django before?

balmy hamlet
#

Has anyone here implemented sign in with apple? I was wondering if someone had some good reads or code somewhere they are willing to share. I am trying to implement sign in with apple on my fastAPI backend.

devout coral
#

Log in with Apple ID you mean?

balmy hamlet
#

Yes

vestal hound
#

Has anyone here set up celery for Django before?
@devout coral why

devout coral
#

I am trying to set it up and running into issues

vestal hound
#

yes

#

what issues?

#

if you have problems just post them

devout coral
#

Well the issue is the task just stays pending forever.

vestal hound
#

do you have a worker running?

devout coral
#

I have redis inside of a docker and it connects to it just fine but it never executes

vestal hound
#

sounds like you don't...? that's my initial guess

devout coral
#

Alright, worker is what exactly? Redis is the broker right?

vestal hound
#

yes

#

no

#

well

#

okay, let's just say yes

#

anyway

#

so there'll be one process that basically keeps track of tasks

#

and assigns them

#

to workers.

#

so it sounds like you only have the Celery server running

#

but not workers

#

so it has nothing to dispatch the work to

devout coral
#

Well, I have celery running. And I have redis in a docker running as well. I thought celery received the task from django when I use the .delay() then it gets sent from celery to redis to be executed...

#

Is that not how it works. This is what I understood from the docs.

vestal hound
#

yup, basically

#

okay, never mind what I just said

#

do you have the logs

#

from your running process?

devout coral
#

Well, I could not find where to get the logs...

vestal hound
#

huh.

#

did you ever run celery?

#

like the command

devout coral
#

Yes

vestal hound
#

yeah, that window should have logs

devout coral
#

I did the info for the log to show on the terminal but I could not find a txt or anything with logs if that is what you mean

vestal hound
#

oh, nope

#

just like

#

whatever shows on the terminal

devout coral
#

Oh yeah, I can re run it one sec

#

Forgot to run my docker... One more sec

#
 -------------- celery@d012-itmgrlb2 v5.0.1 (singularity)
--- ***** -----
-- ******* ---- Windows-10-10.0.17763-SP0 2020-10-26 11:43:49
- *** --- * ---
- ** ---------- [config]
- ** ---------- .> app:         DivisionManagementSystem:0x54735c8
- ** ---------- .> transport:   redis://127.0.0.1:6379/0
- ** ---------- .> results:     redis://127.0.0.1:6379/0
- *** --- * --- .> concurrency: 8 (prefork)
-- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker)
--- ***** -----
 -------------- [queues]
                .> celery           exchange=celery(direct) key=celery


[tasks]
  . DivisionManagementSystem.celery.debug_task
  . main.tasks.add
  . main.tasks.send_email
#
[2020-10-26 11:44:37,519: INFO/MainProcess] Connected to redis://127.0.0.1:6379/0
[2020-10-26 11:44:37,538: INFO/MainProcess] mingle: searching for neighbors
[2020-10-26 11:44:38,612: INFO/MainProcess] mingle: all alone
[2020-10-26 11:44:38,663: WARNING/MainProcess] c:\users\edwin.cruz\desktop\divisionmanagementsystem\venv\lib\site-packages\celery\fixups\django.py:203: UserWarning: Using settings.DEBUG leads to a memory
            leak, never use this setting in production environments!
  warnings.warn('''Using settings.DEBUG leads to a memory

[2020-10-26 11:44:38,663: INFO/MainProcess] celery@d012-itmgrlb2 ready.
#

@vestal hound

[2020-10-26 11:44:38,663: INFO/MainProcess] celery@d012-itmgrlb2 ready.
[2020-10-26 11:45:57,550: INFO/MainProcess] Received task: main.tasks.add[cdc7e954-d5c5-4b8a-8ef2-343f6e16acc2]
[2020-10-26 11:45:59,584: INFO/SpawnPoolWorker-9] child process 10356 calling self.run()

Then when I run a task it does that and it is still pending 3 minutes later.

native tide
#

How can I create a decorator that gets triggered from a websocket event which then calls the method it's wrapping

limber laurel
#

Could I load my nav bar from static?

devout coral
#

@limber laurel wdym?

silver shell
#

Hi, i am trying to use django test client to log in, like this: https://dpaste.org/NLJB My view looks like this: https://dpaste.org/yFiS I know the view works because i can log in via both browser and POSTMAN. For some reason i get Forbidden: /api/v1/users/auth/ when i try with django test client. What am I doing wrong here?

limber laurel
#

@devout coral like have my navbar.html file in a static folder

sterile peak
#

guys, any advice for someone who just started learning django?

devout coral
#

@limber laurel No that should be a template really, I would put it wherever you are putting you base html stuff

#

@sterile peak Read the docs, then follow a tutorial. Then once you can understand everything in the tutorial build something.

sterile peak
#

@sterile peak Read the docs, then follow a tutorial. Then once you can understand everything in the tutorial build something.
@devout coral alright, you mean the official django documentation right?

clear arch
#

Can anyone suggest me a good tutorial on django?

devout coral
#

@sterile peak Yes

#

@clear arch You like written or video?

clear arch
#

video

sterile peak
#

@devout coral also i haven't worked on front end technologies before so for coding django templates are the basics enough or do i have dig deeper

#

do i have to*

devout coral
#

@sterile peak Well you would want to learn the Django Templating Language which is very similar to jinja2

#

@clear arch There is probably the best one out there.

clear arch
#

@devout coral thx

sterile peak
#

@sterile peak Well you would want to learn the Django Templating Language which is very similar to jinja2
@devout coral jinja2? oh man haven't learnt it either.. looks like i have long way ahead of me

#

and are you currently working on any django proejcts?

clear arch
devout coral
#

@sterile peak Me yes

#

@clear arch Congrats

clear arch
#

thx

#

So we will have to learn Django Template Language right

devout coral
#

Also the templating language is super easy

sterile peak
#

@sterile peak Me yes
@devout coral what are various frameworks/technologies that come in handy while working on your projects in django?

#

i am looking to shift my job so i am trying to gauge some essential skills

devout coral
#

Well the good thing about Django is that it is a "Batteries Included" so you only really need django to get a site running.

sterile peak
#

oh that's great to know.. so react or any other fancy JS framework is required?

devout coral
#

No.

#

I just use JS and JQuery when needed.

sterile peak
#

oh that's great.. but how do we make good UI?

devout coral
#

Also if you want to make your front end life a lot easier use bootstrap

sterile peak
#

i mean clean UI that is pleasnt to look at

devout coral
#

Bootstrap is probably your go to at the beggining.

sterile peak
#

i have some experience with it, i worked with bootstrap and jquery couple of years ago

clear arch
#

bootstrap 4 is great

devout coral
#

So if you have some experience with it I would say use it.

sterile peak
#

great man, thanks! since how long you've been coding using django ?

devout coral
#

At the beginning bootstrap sucks because you are not sure everything it has and the grid system confuses some but once you have some experience you can make the most of it.

#

@sterile peak A little over a year now

clear arch
#

When I started using Bootstrap it took me like half an hour to figure where everything was xD

devout coral
#

Had my first client(that needed web dev) last August which was also my django project

sterile peak
#

At the beginning bootstrap sucks because you are not sure everything it has and the grid system confuses some but once you have some experience you can make the most of it.
@devout coral totally true! i generally dont enjoy working with JS or any of the UI technologies but i am keen to chage that

devout coral
#

@clear arch Nice, it took me about an entire project lmao

sterile peak
#

Had my first client(that needed web dev) last August which was also my django project
@devout coral Congrats on that! are you freelancing?

clear arch
#

@devout coral can you please explain why we use templates?

#

static ---> dynamic is that it or something else?

devout coral
#

@sterile peak I was I no longer do it. Got annoying after a bit.

#

@clear arch The reason we use templates is to make life easier and no need to re write a bunch of stuff. Also helps a lot with dynamic content.

sterile peak
#

okay, let me get my hands dirty with django

devout coral
#

Templating allows you to have a base file(base.html) which will contain things that every page will share (header, nav bar, footer, etc.) and then in your body you can place a "block". Later when you are ready to make a page you can "extend" from that base file and replace that "block" with the code in the current html file.

#

Other things it allows you to do is add loops and logic right in your html. So for example if you want to display multiple users in one html page but do not know the quantity or who it is. You can simply pass a query set to your template then use a for loop right in your html to make the necessary tag(s) for each of the users.

toxic flame
#

Specially with includes on django

#

it saves alot of copy and pasting

sterile peak
#

Other things it allows you to do is add loops and logic right in your html. So for example if you want to display multiple users in one html page but do not know the quantity or who it is. You can simply pass a query set to your template then use a for loop right in your html to make the necessary tag(s) for each of the users.
@devout coral this is one of the best things about django

devout coral
#

Yes, it is.

#

@toxic flame You have any prior experience with celery and django integration?

toxic flame
#

django

#

idk whats celery

clear arch
#

thx @devout coral

toxic flame
#

I heard flask is more lightweight

#

I've been working with django for around 3-4 months now and I can build large scale projects

#

django is easy to learj and understand

devout coral
#

The only way flask is lightweight is that it is smaller in size(because Django includes a lot more out of the box). However, for the same size project doing the same things the performance differences are negligible.

clear arch
#

@devout coral quick question: jinja vs dtl

sterile peak
#

I've been working with django for around 3-4 months now and I can build large scale projects
@toxic flame so what else do you use apart from django??

toxic flame
#

backend frameworks?

#

i also know php

sterile peak
#

@toxic flame for backend and front end.. i would lke to know the things that are absolutely necessary to build large scale projects

devout coral
#

@clear arch no real big difference from what i know tbh. Just that DTL is already included in Django.

toxic flame
#

oh

pale hearth
#

Hi ! i'm trying to scrapping and i've some sort of "selector" which aren't button but we can click on it, how can i trigger this action ?

toxic flame
#

html, css, sass, js, vuejs, django, these are the default I use for a large scale project

sterile peak
#

sass? software as a service?

toxic flame
#

no

clear arch
#

ok @devout coral thx

toxic flame
sterile peak
toxic flame
#

okay xD

sterile peak
#

vuejs? i am new to UI so please bear with me. i hear about react, flutter and angular but not much of vue.. what is your opinion?

toxic flame
#

imo vue is easier and flexible than react

#

vue can have scoped / nested css for each element which is very flexible for me

haughty turtle
#

VueJS is good, its open source, I would recommend it if you want to learn it personally, but job wise VueJS isnt as popular as React of Angular atm I have heard. So if you are determined to get a job off the bat then go with something like React or Angular, I personally am going with VueJS then will play with Angular or React later on.

sterile peak
#

oh alright, so many js frameworks it gets overwhelming very easily

#

currently i am very focused on getting up to speed with django post that i reckon some js framework would be good thing to learn?

haughty turtle
#
from django.db import models


class Category(models.Model):
    category_name = models.CharField(max_length=100)
    
class Product(models.Model):
    product_name = models.CharField(max_length=200)
    product_price = models.DecimalField(max_digits=5, decimal_places=2)
    ```
I am creating a Category model in which new categories can be created such as Clothing, Accesories, Textiles etc. I want my Product model to inherect one of the categories created. How would I go about doing this
clear arch
#

I am getting an error when I am typing os.path.join(BASE_DIR, 'templates') the error is name os is not defined?

haughty turtle
#

did you import os

clear arch
#

in the settings?

haughty turtle
#

where you have the following code

clear arch
haughty turtle
#

then yes import it there

clear arch
#

ok does it matter where I import it?

sterile peak
#

yes..

clear arch
#

nvm got it thx @haughty turtle

devout coral
#

@clear arch Not trying to be rude but it does not seem you are too familiar with python. If this is the case I would suggest you learn python basics before diving into django or you will get VERY overwhelmed.

#

@haughty turtle Did you get your model thing figured out or need some help still?

haughty turtle
#

yea need some help still

#

Trying to figure out the best way to go forward, I need to have my products specify what categories they are in as I will need to display them per category later on, as also per gender.}

clear arch
#

@devout coral I thought os was already imported as I am following a tutorial in that os module was already imported

devout coral
#

@haughty turtle Ok, and your category is a whole model correct?

#

@clear arch Yes it is in there by default.

clear arch
#

for mine it was not xD

devout coral
#

Uhh, what version of Django do you have?

#

That is very strange.

clear arch
#

latest

devout coral
#

Ok weird.

haughty turtle
#

@devout coral yeah I imagine this would be the best way in Django, will it not? Allowing me to add new categories later on?

#

In terms of user friendliness new categories could just be added in the admin panel

plucky tapir
#
Please select a fix:
 1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
 2) Quit, and let me add a default in models.py
``` I'm trying to add an author to a models, do I just add default=True into its definition?
plush zenith
#

Guys is css hard ?

#

Or its frameworks?

haughty turtle
#

I learnt css in two days

#

@plush zenith

plush zenith
#

I learnt css in two days
@haughty turtle wow

#

Css is very complicated

#

When I look at css

#

Its

devout coral
#

@haughty turtle Yeah that works. What I would suggest is to make a relationship between categories and product.

clear arch
#

CSS is hard to remember isn't it

plush zenith
#

Yeah

#

All those rules

#

Plus u have so many kinds of framework

#

Scss bootstrap

#

Grid css

sterile peak
#

css is very confusing, so many ways to style a element

plush zenith
#

Flex box

haughty turtle
#

Programming is not about remembering stuff its about learning the fundamentals and being able to research at any given time.

https://www.youtube.com/watch?v=yfoY53QXEnI

In this video I will cram as much as possible about CSS. We will be looking at styles, selectors, declarations, etc. We will build a CSS cheat sheet that you can keep as a resource and we will also create a basic website layout. We are using CSS3 but mostly the basics. I will ...

▶ Play video
balmy hamlet
#

Does anyone here use FastAPI?

plush zenith
#

Programming is not about remembering stuff its about learning the fundamentals and being able to research at any given time.

https://www.youtube.com/watch?v=yfoY53QXEnI
@haughty turtle css is a programming language

In this video I will cram as much as possible about CSS. We will be looking at styles, selectors, declarations, etc. We will build a CSS cheat sheet that you can keep as a resource and we will also create a basic website layout. We are using CSS3 but mostly the basics. I will ...

▶ Play video
#

Not a

#

Css is not a programming name

#

Language

sterile peak
#

Programming is not about remembering stuff its about learning the fundamentals and being able to research at any given time.

https://www.youtube.com/watch?v=yfoY53QXEnI
@haughty turtle while i agree with this but without remembering sometimes it is hard to debug old code. i had to do that a lot on my previous project and all that legacy drove me crazy

devout coral
#

@haughty turtle do you know how to establish relationships in django?

devout coral
#

@haughty turtle Lol... I do not need to read it I know how to do it. I was saying it for your question.

#

Plus I have probably read that a few times already..

toxic flame
#

html and css is probably the easiest

haughty turtle
#

Yeah, thats what I am reading right now, I completed the Django tut, but that was like 4 weeks agos

#

have been completing the HTML and CSS got that done, now have to refresh what I learnt

devout coral
#

If you are starting out with django my suggestion is to always focus on the django part of it instead of front end. Once you have your funcitonality then do the front end.

toxic flame
#

you need the basic python knowledge too for django

haughty turtle
#

Ah, I did it backwards

devout coral
#

@haughty turtle Ok, well for your issue a OneToMany relationship is probably what you are looking for.

#

you need the basic python knowledge too for django
@toxic flame I cannot stress this enough. Seems like a lot of people just want to jump right into django but that is such a big mistake. You will run into all types of issues.

toxic flame
#

ForeignKey(Category, on_delete=models.CASCADE) is what u need @haughty turtle

#

put it on the product models

#

cateogroy = models.F....

#

then you can assign a category to a product, which can be filtered by:

#

Product.objects.filter(category__category_name="nameofyourcategiry")

#

I'm on my phone hehee

devout coral
#

@toxic flame Any experience with celery in django?

toxic flame
#

You asked me this already, no.

devout coral
#

Did not see your answer. Thank you

toxic flame
#

It's okay

#

There are alot of ways on making relations but I like this method more

#

it's easier than the OneToManyFields since you have to drag and drop, and do all sort of things before actually linking them together

royal radish
#

Hello everyone ! Does anyone here have experience with Flask/Celery use ? I need help with setting up so if you have done this before, would be grateful for your help
Thanks!

devout coral
#

@royal radish I have been trying to get some help with celery for the past three days... No such luck so far.

#

But if you figure something out and can help me out with my issue let me know.

toxic flame
#

Celery seems to be a realtime processor for python stuff

devout coral
#

Well it it for asynchronous work, and my set up gives no errors which is even more frustrating. Just sits on pending and never finishes the task.

limber laurel
#

@devout coral Could I create a template folder but for the whole project?

devout coral
#

@limber laurel Yes, this is normally where you would put your error templates and admin templates to re write the django back end look.

limber laurel
#

Ok

devout coral
#

However, for the individual app templates you would normally have your templates in there.

limber laurel
#

Ok\

devout coral
#

Just want to note I finally figured out my issue with celery. Apparently it is a weird issue with celery and windows and you need to add the --pool=solo to your worker.

#

Question, anyone here have a clever way to get a absolute url without the request object?

pulsar hinge
#

Hi, I'm getting error with js this time.

    at register
    at HTMLSpanElement.onclick```

I have 
```{% extends 'base.html' %}```
 at my account.html(site with problem). I included scripts.html and linked main.js before in base.html. This script is the only one not working: 
```/* Toggle Form */
    var LoginForm = document.getElementById("LoginForm");
    var RegForm = document.getElementById("RegForm");
    var Indicator = document.getElementById("Indicator");

    function register(){
        RegForm.style.transform = "translateX(0px)";
        LoginForm.style.transform = "translateX(0px)";
        Indicator.style.transform = "translateX(134px)";
    }
    function login(){
        RegForm.style.transform = "translateX(-400px)";
        LoginForm.style.transform = "translateX(390px)";
        Indicator.style.transform = "translateX(15px)";
    }```
 
Although when I just copy this script into account.html irt magically works. But that's not how it is supposed to work. It should work by including scripts in base.html. When going into Dev mode at site, my scripts are loading, but they aren't working. I've done everything with staticfiles.
devout coral
#

@pulsar hinge seems like those two elements do not exist.

pulsar hinge
#

But when pasting this script into <script> tag at account.html, it works fine

native tide
#

I'm making a request to my API endpoint to sign users up and I just tried to add session authentication, but I don't know what to do and the DRF docs are confusing.

My error:
{"detail":"Authentication credentials were not provided."}

My view:

@api_view(["POST"])  # API view for POST requests
@permission_classes([IsAuthenticated])
def register(request):  # This will register a user from their POST request.

    if request.method == "POST":
        if "username" and "email" and "password" and "confirm_password" in request.data:

            if request.data["confirm_password"] == request.data["password"]:  # Checks that password is confirmed.
                hashed_password = make_password(str(request.data["password"]))  # Hashes password
                request.data["password"] = hashed_password
            else:
                return Response(data={"password": "Passwords do not match"}, status=status.HTTP_400_BAD_REQUEST)

            serializer = UserSerializer(data=request.data)

            if serializer.is_valid():
                serializer.save()
                return Response(data=serializer.data, status=status.HTTP_201_CREATED)

            else:
                return Response(data=serializer.errors, status=status.HTTP_400_BAD_REQUEST)

        else:
            return Response(data={"error": "Model fields not satisfied"}, status=status.HTTP_400_BAD_REQUEST)```

How do I provide auth details?
pulsar hinge
#

It just doesn't work while including

devout coral
#

@pulsar hinge You are probably referencing before it is loaded in then. Try loading the script at the end.

pulsar hinge
#
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href=" {% static 'css/style.css' %} ">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    
    <title>RedStore |{% block title %}{% endblock title %}</title>
</head>
<body>
{% include 'navbar.html' %}
{% block content %}

{% endblock content %}
{% include 'scripts.html' %}
</body>

</html>``` Replacing include scripts after body or html doesn't make a diffrence
#

That's weird cause other scripts are working just fine. There is only one error, but at pages that don'trequire this script.

#

@devout coral sorry for ping, just want to make sure u see it

swift sky
#

is flaskforms appropriate for building a dashboard which can pull data from a mysql db, and export in xls format?

#

ive only used flaskforms for logins and data upload pages.

wanton ridge
#

anyone know what i am doing wrong? with password hashing

swift sky
#

print your query

#

lookup how to mogrify and print the content of your sql query

#

object of type none has no len

#

type none

#

check to see if your script is even querying properly

#

that is my guess

wanton ridge
#

i also tried removing len nothing worked

#

yep its properly

swift sky
#

someone more experienced maybe

#

ive only done auth 1 time

#

i used this way though

#

    #login page and location logic
    @app.route("/login", methods=["GET", "POST"])
    def login():
        connection = db_connection()
        error = None
        if request.method == "POST":
            email = request.form.get('email')
    #        print(email)
            password = request.form.get('password')
    #        print(password)

            with connection.cursor() as cursor:

                sql = "SELECT email, password_hash FROM users WHERE email=%s"
                cursor.execute(sql, (email,))
                result = cursor.fetchone()
                connection.close()
      #          print(type(result['password_hash']))
     #           print(result['password_hash'])



                if result is None:
                    flash("That email doesn't exist")
                    return render_template("login.xhtml", error=error)
                else:
                        if bcrypt.check_password_hash(result['password_hash'], password.encode('utf8')):
    #                        print(bcrypt.check_password_hash(result['password_hash'], password.encode('utf8')))
   #                         print(bytearray(bcrypt.check_password_hash(result['password_hash'], password.encode('utf8'))))
                            session["logged_in"] = True
                            flash("You were just logged in!")
                            return redirect(url_for("staffdashboard"))
                        else:
                            flash("Incorrect password, please try again.")
                            return render_template("login.xhtml")```
#

check your db as well

#

make sure the columns are loaded properly

wanton ridge
#

but why you removing password in cursor.execute

#

i don't get it

swift sky
#

because it's already in my query

#

sql = "SELECT email, password_hash FROM users WHERE email=%s"

wanton ridge
#

ahh i see

swift sky
#

as you see i still have my print statements from debugging

#

xD

#

traumatic experience

wanton ridge
#

hehe

swift sky
#

for me the big error was that I actually was not pulling the right hash

#

so iw as getting invalid salt

#

but i feel like yours isn't pulling anything because you're getting a none type

#

i can't help you more than I've done already though 😦 i suggest use lotsa prints

wanton ridge
#

now i have this error

#

i just removed the len() > 0

#

and then i tried and got this error

devout coral
#

@pulsar hinge Sorry, I went to a meeting. Why do you have a scripts.html? Why not have a js file with them and load those into the base file in the header or after the body tag?

swift sky
#

sry I can't help too busy 😦

pulsar hinge
#

@pulsar hinge Sorry, I went to a meeting. Why do you have a scripts.html? Why not have a js file with them and load those into the base file in the header or after the body tag?
@devout coral Yea, tried that as well. Didn't change anything. But I solved it removed variables and referenced to it directly.

devout coral
#

@pulsar hinge I just noticed your variables were not in the same scope... They were made outside of the functions.

mortal mango
devout coral
#

Yes, as the error reads you are trying to add a non-nullable field and you need a default or allow it to be null.

mortal mango
#

oh

#

@devout coral so what would I do? I just want to create a new model.

#

would I allow it to be null?

devout coral
#

@mortal mango If the picture is not needed sure, otherwise set a default. Like if it is for a profile picture I would suggest you set a default.

mortal mango
#

I want to put an image url so I set it as charfield.

#

Can't I just go into the admin page and put in the URL?

#

so what is the default?

#

what would it be used for?

#

@devout coral

haughty turtle
#

Ah Django is so beautiful, my model relationships worked perfectly, was worried about how I would be able to identify which one I would want, but Django made sure to take care of that for me.

#

@mortal mango Show a snippet of the code you are trying to add into models

devout coral
#

@mortal mango You can set the default to just an empty string then.

#

@haughty turtle Good to hear!

#

I thought you were using a FileField but since it is just a CharField empty string for default is fine.

haughty turtle
#

Yea I just now need to figure out how to get it to give my users the same options outside of admin.

devout coral
#

Nice. How did you end up implementing it ? With a select widget?

haughty turtle
#

Yea the default it would be the most user friendly way for my client to access the admin panel.

toxic flame
#

anyone here familiar with the paypalrestsdk?

mortal mango
#

@mortal mango You can set the default to just an empty string then.
@devout coral oh ok

#

you can't set it as an empty string

#

it says please enter some code

#

and if I put a space, it says Invalid Input

devout coral
#

What do you mean?

#

You mean the form is not validating and it is giving you that error? Or you cannot migrate?

#

@toxic flame I am not.

icy fog
#

Anyone knows how to display a foreign key's attribute instead of its default representation? For example, display the sender's username instead of their primary key

#

Here's my model for the Message object:

#
class Message(models.Model):
    sender = models.ForeignKey(Account, on_delete=models.CASCADE, null=False,
                               blank=False, verbose_name="Sender", related_name='sender')
    receiver = models.ForeignKey(Account, on_delete=models.CASCADE, null=False,
                                 blank=False, verbose_name="Receiver", related_name='receiver')
    content = models.TextField(max_length=512, blank=False, null=False,
                               unique=False, editable=False, verbose_name="Message")
    read = models.BooleanField(default=False)
    timestamp = models.DateTimeField(auto_now_add=True)```
#
class Account(AbstractBaseUser):
    email = models.EmailField(verbose_name="Email", max_length=64, unique=True)
    username = models.CharField(max_length=30, unique=True)
    date_joined = models.DateTimeField(
        verbose_name='Date Joined', auto_now_add=True)
    last_login = models.DateTimeField(verbose_name="Last Login", auto_now=True)
    is_admin = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']

    objects = PigeonAccountManager()

    def __str__(self):
        return self.username

    def has_perm(self, perm, obj=None):
        return self.is_admin

    def has_module_perms(self, app_label):
        return True

    def get_username(self):
        return self.username```
#

That's my model for my account object

devout coral
#

@icy fog You mean you want to change it's default representation, like if you were to do a print(object_here)

icy fog
#

Yeah, something like that

#

cuz it's not helpful to debug when it's only showing me the ID of the Account object instead of its username

devout coral
#

Your __str__ method handles that. So change the return of it

icy fog
#

The str method works fine for other representation because it works here where it actually displays the username of the Account object

#

My problem is that it doesn't display the username on the 'sender' attribute when it's represented on the API view of DRF

trim star
#

Is it a good practice to have your migration files in your version control repo? It seems not

icy fog
#

is there some way to manually change the representation of that without affecting the value of the attribute itself?

devout coral
#

@trim star Yeah not a good idea, you normally want to add migrations to gitignore

#

@icy fog What representation, I am sort of confused now.

icy fog
trim star
#

@devout coral Thats what I thought

icy fog
#

It seems to retrieve the Account object's ID and display it directly instead of using the str method of the Account object

#

I don't know if it's possible to change the way DRF API-view displays it

devout coral
#

@icy fog Can you not just change it in the view where you do the return for the get request??

icy fog
#

Hmm, I think it might be possible but I'm using generics for that one

#

here's what my view for it is:

class MessageListView(ListCreateAPIView):
    queryset = Message.objects.all()
    serializer_class = MessageSerializer
    permission_classes = [permissions.IsAuthenticated]```
#

I don't know if it's possible to define a method which alters the presentation of the Account object's value so that it uses the str method

mortal mango
#

that's what pops up when I just click enter to leave a blank string

devout coral
#

@icy fog I think a custom serializer is the only way to go then..

#

@mortal mango ... I meant to set a default in your model... Not just press 1 and give it a one off.

mortal mango
#

oh

devout coral
#

default=''

mortal mango
#

oh ok

#

it worked!

#

is there a way to upload an image to my domain url? like mydomain.com/image and it would show the image

devout coral
#

Like an image field?

mortal mango
#

no like I want my domain to be an image url

#

so like I would do mydomain.com/image and it would show the image

#

Like an image field?
@devout coral is there an option for an image field?

devout coral
#

Yes image fields exists in django models

mortal mango
#

oh so I just want my logo to show up. So people can get the logo.

#

so the easy way would be to do an image field right?

trim star
#

I have another best practices question:
So the application that I'm contributing to has a non-interactive mode for instances in which the admin does not have access to the command line. They print an initial default password to stdout for the admin to log in, and never enforce that the admin change that default password.

This seems like a security issue to me..what do you think?

vale orbit
#

So would one recommend flask more for api development and django for progressive web apps? Or would it work better to use a flask backend to a react/angular app?

vestal hound
#

So would one recommend flask more for api development and django for progressive web apps? Or would it work better to use a flask backend to a react/angular app?
@vale orbit what do you mean "progressive web app"?

#

you can use DRF (Django REST Framework) to build an API

#

consider also FastAPI

vale orbit
#

Single Page Application is what I mean.

I have also heard good things about connexion for api development, any thoughts on that one?

vestal hound
#

Single Page Application is what I mean.

I have also heard good things about connexion for api development, any thoughts on that one?
@vale orbit if anything, vanilla Django would be worse than Flask for SPAs

#

never heard of that, sorry

vale orbit
#

Ok, then I guess I will stick to my initial instinct of “use flask backend as a replacement for express js”

vestal hound
#

DRF will work for that too

vale orbit
#

Which one allows for faster development time?

mortal mango
#

Does anyone know how to set up post requests in django rest framework?

#

or does anyone know any good tutorials

vestal hound
#

Does anyone know how to set up post requests in django rest framework?
@mortal mango what do you mean?

mortal mango
#

I want to post something to my API json data

vestal hound
#

Which one allows for faster development time?
@vale orbit I'd say Django...? because it's opinionated

mortal mango
#

but idk exactly how

vestal hound
#

do you mean you want to POST from Django, or handle POST requests in Django?

mortal mango
#

in

vestal hound
#

same as vanilla Django

#

create an API view

mortal mango
#

I'm new to django

vestal hound
#

hm.

#

then you should start with the Django tutorial

#

before moving to DRF

mortal mango
#

yeah I've done that

buoyant leaf
#

how to get Voice Verified

mortal mango
#

I have pretty much everything set up except for the post

buoyant leaf
#

role

#

pls tell me

mortal mango
#

@vestal hound

vestal hound
mortal mango
#

does return Response send the user data?

#
from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from . models import exo
from . serializers import exoSerializer

class exoList(APIView):
    def get(self, request):
        exo1 = exo.objects.all()
        serializer = exoSerializer(exo1, many=True)
        return Response(serializer.data)

    def post(self):
        return Response({"message": "Got some data!", "data": request.data})
        return Response({"message": "Hello, world!"})

def home(request):
        return render(request, 'files/index.html')
#

@vestal hound this is my code but it's not working

vestal hound
#

define "not working"

#

your post method is missing a request parameter

mortal mango
#

"detail": "JSON parse error - Expecting value: line 1 column 1 (char 0)"

#

oh

#

still not working

#

same error

#

"detail": "JSON parse error - Extra data: line 1 column 5 (char 4)"

native tide
#

I'm making a request to my API endpoint to sign users up and I just tried to add session authentication, but I don't know what to do and the DRF docs are confusing.

My error:
{"detail":"Authentication credentials were not provided."}

My view:

@api_view(["POST"])  # API view for POST requests
@permission_classes([IsAuthenticated])
def register(request):  # This will register a user from their POST request.

    if request.method == "POST":
        if "username" and "email" and "password" and "confirm_password" in request.data:

            if request.data["confirm_password"] == request.data["password"]:  # Checks that password is confirmed.
                hashed_password = make_password(str(request.data["password"]))  # Hashes password
                request.data["password"] = hashed_password
            else:
                return Response(data={"password": "Passwords do not match"}, status=status.HTTP_400_BAD_REQUEST)

            serializer = UserSerializer(data=request.data)

            if serializer.is_valid():
                serializer.save()
                return Response(data=serializer.data, status=status.HTTP_201_CREATED)

            else:
                return Response(data=serializer.errors, status=status.HTTP_400_BAD_REQUEST)

        else:
            return Response(data={"error": "Model fields not satisfied"}, status=status.HTTP_400_BAD_REQUEST)```

How do I provide auth details?
vestal hound
#

same error
@mortal mango what are you passing in the request

#

@native tide hm.

#

you should let your serializer do all of that

native tide
#

what should it do? 😳

vestal hound
#

the view?

#

the view should pass the data to the serializer

#

and let it do validation.

#

in particular

#

if you use, for example, is.valid(raise_exception=True)

#

a ValidationError will automatically be caught and returned in the Response as 400

mortal mango
#

I give up

#

this is hard

vestal hound
#

basically, any work involving converting from/to data that will be sent over HTTP should be done by the serializer

native tide
#

Sure I can move over the validation to the serializers, but what do I need to counter:
{"detail":"Authentication credentials were not provided."}
It only appeared as soon as I added session auth. I think I need to provide a CSRF header in my request but I did that (I think) and I'm not getting anywhere

#

@mortal mango in your Response, do data={your dict}

vestal hound
#

that's probably a frontend problem

native tide
#

Probably, I just don't know what it wants as "Authentication credentials"

#

Ah, actually I think I see what I may have done wrong

#

For session auth I think I need to include the user's username and password in the request

#

of a user that already exists

vestal hound
#

yeah, I'd guess that you're sending your auth stuff wrong

mortal mango
#

@mortal mango in your Response, do data={your dict}
@native tide is response in my views or in my actual post request?

native tide
#
#settings.py
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication'
    ],

    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
    ]
}```

It's so weird. As soon as a enable SessionAuth I get that error, even on the signup view. So I must be doing something wrong
#

@mortal mango Your POST request is a request to the server. The response is the server's JSON response, which is in your view.

#

I heard that using token auth is bad, is that true? I got discouraged from using it in favor of sessions - but that's a headache.

vestal hound
#

I heard that using token auth is bad, is that true? I got discouraged from using it in favor of sessions - but that's a headache.
@native tide why is it bad?

native tide
#

I don't know, I just got told session auth > token auth

#

and now that I'm reading about it, for my specific use case making AJAX requests to my api, I think that token auth is more suited

vestal hound
#

huh.

#

any justification?

#

if not I wouldn't be too fixated on that

native tide
#

just because I don't want to fiddle around with cors and cookies 😄

vestal hound
#

no, I mean, why session auth > token auth

native tide
#

I wouldn't know. I just got told it is, infact it was in this channel lmao

vestal hound
#

huh.

#

if you can find the message it might be easier

gaunt marlin
#

@native tide if you using session authentication then you need to pass csrf token in your POST request, how are you passing it on the frontend?

#

ajax ? or just normal form

native tide
#

Was doing it with a normal form, I had the header with the X-CSRFToken but I was getting an error (its somewhere up in the chat).

I'm going to stick with tokens though.

gaunt marlin
#

@native tide that not really answer my question. There 2 way to send a POST request from the front end. Use normal form with {% csrf_token %} in the form. But you said had the header with the X-CSRFToken which is the method of using ajax/jquery to send POST request

toxic flame
#

its
{% csrf_token %}

gaunt marlin
#

ty i was mistyping

oak cave
#

I'm hoping to use Django to make a website for my current side hustle. I know what I want my site to look like. Are there any WYSIWYG style editors that leave with pretty standard html I could read/use? Are they all damn near obfuscated with javascript. I literally only know of dreamweaver

gaunt marlin
glossy goblet
#

Hello👋, I am looking for a solution to add notifications 📩 to my flask website. Can you lead me to an solution that you know is working? Thank you 🙏

spiral smelt
#

JavaScript has a notification API if that's what you mean

native tide
#

hey need help with my p5.js setup using cdn

gaunt marlin
#

hello what do you need help with ? @native tide

silver shell
#

Uhhh i am getting syntax error here:

            return {
                "success": True, {
                    "Company": company,
                    "User": user,
                    "Staff": staff
                }
            }

I just cannot see why? Can anybody here see what i am doing wrong?

gaunt marlin
#

@silver shell post your error traceback message instead of the code if it's syntax error. It can tell which line the error happened

silver shell
#

@gaunt marlin found the issue

gaunt marlin
#

@silver shell yeah i see you passing dict, but the second element don't have key value

silver shell
#

exactly

native tide
#

hello what do you need help with ? @native tide
@gaunt marlin p5.js cdn embed link plzzz

gaunt marlin
native tide
#

ok

gaunt marlin
#

jquery link in jquery official site, you only asked me for p5.js cdn...

native tide
#

ok

#

i wanna leearn p5 the jq

#

*then

merry copper
#

Hello
I need help with the concatenation
I'm trying to concat str and dictionary .
I already used str()
but I'm not satisfied with the result.

#

this is what I've got after using str()

#

@app.get('/api/case-image/{case_id}')
def case_image(case_id: int):
db = DB.init_db()
image_path = DB.get_case_image(db, case_id)
db.connection.close()
#print(image_path)
site_url = 'http://10.34.102.60/jupyter-suture/view/suture-api/'
#return {'image_path': site_url+str(image_path)}
return {'image_path': site_url + image_path}

#

@app.get('/api/case-image/{case_id}')
def case_image(case_id: int):
db = DB.init_db()
image_path = DB.get_case_image(db, case_id)
db.connection.close()
#print(image_path)
site_url = 'http://10.34.102.60/jupyter-suture/view/suture-api/'
return {'image_path': site_url+str(image_path)}
#return {'image_path': site_url + image_path}
@merry copper this is my code

gaunt marlin
#

!code @merry copper use this to format your code so it don't look messy

lavish prismBOT
#

Discord has support for Markdown, which allows you to post code with full syntax highlighting. Please use these whenever you paste code, as this helps improve the legibility and makes it easier for us to help you.

To do this, use the following method:

```python
print('Hello world!')
```

Note:
These are backticks, not quotes. Backticks can usually be found on the tilde key.
• You can also use py as the language instead of python
• The language must be on the first line next to the backticks with no space between them

This will result in the following:

print('Hello world!')
gaunt marlin
#

also what is your unsatisfied with the return string?

viscid sedge
#

!code

lavish prismBOT
#

Discord has support for Markdown, which allows you to post code with full syntax highlighting. Please use these whenever you paste code, as this helps improve the legibility and makes it easier for us to help you.

To do this, use the following method:

```python
print('Hello world!')
```

Note:
These are backticks, not quotes. Backticks can usually be found on the tilde key.
• You can also use py as the language instead of python
• The language must be on the first line next to the backticks with no space between them

This will result in the following:

print('Hello world!')
hard spear
#

Hello guys, I'm using Flask for almost 6 months now. Can anyone link some Projects done with Flask on Github so that I can read a bit of code and it'll be easy for me to learn more concepts on Flask.

Thank You 🙂

gaunt marlin
#

!projects maybe there are some here

lavish prismBOT
#

Kindling Projects

The Kindling projects page on Ned Batchelder's website contains a list of projects and ideas programmers can tackle to build their skills and knowledge.

gaunt marlin
#

i guess not

hard spear
#

Wow that'll be really nice

gaunt marlin
#

@hard spear also i recommend this one https://github.com/gothinkster/flask-realworld-example-app as it's one the popular github repo of real world apps https://github.com/gothinkster/realworld (collection of real world repo base structure of all framework)

hard spear
#

Okay I'll def check this out

gentle ingot
#

Is there an easy way to reuse a navbar?

gaunt marlin
#

@gentle ingot yes if you talking about code base then you can apply that navbar in a block and reuse that block in other templates.

gentle ingot
#

Okay thanks. Ill look into blocks. I only have three pages and it's already getting annoying updating the links lol.

clear arch
#

Can anyone tell from where I can download templates?

vestal hound
#

Can anyone tell from where I can download templates?
@clear arch what do you mean

nova nacelle
#

Can anyone tell from where I can download templates?
@clear arch colorlib.com

clear arch
#

@nova nacelle thx

nova nacelle
#

@nova nacelle thx
@clear arch np

native tide
#

@gaunt marlin I'm not using Django forms. I'm using a React frontend, with the csrf token in the header. But idk lol

gaunt marlin
#

@native tide for react you need to set header in your POST request

headers: {"X-CSRFToken": csrfToken}
#

your csrfToken you get from Django

#

if you using react then why not use JWT token instead?

#

session way harder to manager with a front end framework

native tide
#

Yea I'm using token auth, well im trying to

#

Apparently my models need to extend the base User model which Django provides

#

So now I'm changing it all :D

gaunt marlin
#

that sound like reinventing the wheel for me

native tide
#

Lmao it feels like it too

#

Been stuck on auth for 3 days, but it is what it is

native tide
#

Is there anyway to do password hashing within a Django model, instead of doing it outside the model then passing the hashed password to the model?

gaunt marlin
#

you can override save() method of your model to do hashing within model when call save() outside

native tide
#

sounds good, thanks!

merry copper
#

also what is your unsatisfied with the return string?
@gaunt marlin I don't want it to return in list format tho.

gaunt marlin
#

@merry copper from your image seem like image_path data return a list of many image path, you can do a for loop on image_path and just return each one

#

for example

image_path_list = []
for path in image_path:
  image_path_list.append(site_url + path)

return {'image_path': image_path_list}
#

does this make sense ?

gentle ingot
#

@gentle ingot yes if you talking about code base then you can apply that navbar in a block and reuse that block in other templates.
@gaunt marlin I didn't think about this earlier but can I update the active tab?

gaunt marlin
#

@gentle ingot what do you mean ?

#

active tab ?

gentle ingot
#

When you switch from home to games>brotastic, look at the change in highlight on the navbar.

silver shell
#

Hi. I have a serializer which is based on a model with a relationship to another model. Relationship is called staff and it has blank=True and null=True. However, when i ask my serializer to validate some dict-like data with a missing staff field, it invalidates and says: "This field is required.". Ok - fine...So to counter that i then setup in my serializer staff = serializers.PrimaryKeyRelatedField(queryset=Staff.objects.all(),required=False) and now i don't get the required error anymore... But heck, if i then now use my serializer to serialize an existing object, I now then get this error: "AttributeError: 'RelatedManager' object has no attribute 'pk'"... So what do I do? How do i use serializers on models with non-mandatory relationships?

#

@gaunt marlin session way harder to manager with a front end framework no its not. And sessions are safer

#

JWT is mainly for public APIs and JWT's are heavily overused and misunderstood. Just dont use them

#

further they require you to maintain whitelists/blacklists, frequent and infrequent refreshing etc..... loads of annoyances... Session cookies has been around for a long time and have proven their worth. They are httponly (as opposed to e.g. JWT which can be read easily from JS)...and they are nativly supported in most webframeworks

native tide
#

you can store a jwt in a cookie

#

a lot of people would recommend you do

silver shell
#

@native tide sure you can...but you cannot store it in an http only cookie

#

for obvious reasons

native tide
#

sure you can?

silver shell
#

ok, how on earth would you do that?

native tide
#

nah bruh session auth is harder to do if you have a react frontend at least

#

compared to token

#

im not about to argue best practice and if you should or shouldnt

#

im simply saying you can and it eliminates the js can access it thing

silver shell
#

@native tide eh no...got my session based cookie stuff going w. react frontend in 1 hour or so

native tide
#

good for you

silver shell
#

@native tide further...why would you even do that if thats what sessions are already doing?