#web-development

2 messages ยท Page 182 of 1

dense slate
#

Usually that means the relevant part to what you're trying to do.

vestal hound
#

the file in which the error occurs

true kernel
#

I am not able to access the admin page. Im getting a 500 status code while accessing /admin

#

i cant debug which file is the error source

vestal hound
#

you can

#

look at the traceback

lavish ferry
#

Figured I would jump in, working at last:

<div class="image-container">
    <div class="card image-card justify-content-center">
        <h1 class="text-center">Data Manipulation</h1>
    </div>
</div>
.image-container {
  width: 100%;
  height: 400px;
  position: relative;
  background-image: url(images/other/home_encryption.png);
  background-repeat: no-repeat;
  background-size: cover;
}

.image-card {
  position: absolute;
  top: calc(50% - 20px);
  left: calc(50% - 200px);
  width: 24rem
}
lime frigate
#

ERROR: Command errored out with exit status 1: command: /data/data/com.termux/files/usr/bin/python3 -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/data/data/com.termux/files/usr/tmp/pip-install-or7kne1o/pymongo_4c8372d8aea5484bb4685e01b49d414a/setup.py'"'"'; __file__='"'"'/data/data/com.termux/files/usr/tmp/pip-install-or7kne1o/pymongo_4c8372d8aea5484bb4685e01b49d414a/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /data/data/com.termux/files/usr/tmp/pip-pip-egg-info-7k2g2h4c cwd: /data/data/com.termux/files/usr/tmp/pip-install-or7kne1o/pymongo_4c8372d8aea5484bb4685e01b49d414a/ Complete output (11 lines): Traceback (most recent call last): ). Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.

#

When i download django this happens

#

Using pip

#

Wtf...

ionic raft
ionic raft
lime frigate
#

Yes.... cuz the problems are different, and i tried the solution

#

I can't even download brew

ionic raft
# lime frigate Doesn't help....

There's also https://stackoverflow.com/questions/57444207/how-to-fix-error-error-command-errored-out-with-exit-status-1-python-when-t

Typically, when I get error messages like it can take me time to get to the bottom of cause. Following the trail typically takes more than minute of looking at a post. Unless of course you've done all that, in which case, it's a great idea to include what you've tried with your question

manic crane
#

im following a tutorial

#

and when i want to migrate i get this

#

You are trying to add a non-nullable field 'user' to post without a default

ionic raft
manic crane
#

but the tutorials code and mine is the same which is =>
class Post(models.Model):
# filters posts so only published posts are avaible in the home screen .
class PostObjects(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(status = "posted")
options = (
('draft' , 'Draft'),
('posted' , 'Posted'),
)
clique = models.ForeignKey(Clique, on_delete=models.PROTECT, default=1)
content = models.TextField(max_length=400,null=True, blank=True)
caption = models.CharField(max_length=400,null=True, blank=True)
posted = models.DateTimeField(default=timezone.now)
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='clique_posts',blank=True)
status = models.CharField(max_length=12, choices=options, default='posted')
objects = models.Manager() # default manager
postobjects = PostObjects() # custom manager

ionic raft
#

You've got blank=True and need null=True.

#

Also, use back quotes for pasting code

user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='clique_posts', null=True, blank=True)```
#

!code

lavish prismBOT
#

Here's how to format Python code on Discord:

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

These are backticks, not quotes. Check this out if you can't find the backtick key.

ionic raft
manic crane
ionic raft
#

My recommendation...Corey Schafer...His series on Django on YT is free and outstanding.

#

I'm 20k lines of code later and have a great Django web app. All from the start with Corey

manic crane
#

der code didnt have blank=true and null=true

#

wow thanks bro

ionic raft
manic crane
#

preciate it

ionic raft
#

You're welcome.
I feel ya. I get wanting to finish the tutorial. But not all teachers are equal

lime frigate
ionic raft
# lime frigate Wdym by install of python and virtual environment

Back in the early days I started getting some weird errors. After looking at things it appeared I had managed to mess up my python setup. I literally wiped Python and evertything to do with it. I then started again. Fresh install, creating a virtual environment for every project. That way I now keep all projects independent.
When I started with Python I didn't get how important that was.

lime frigate
ionic raft
lime frigate
#

Linux

ionic raft
# lime frigate Linux

That's not my bag. I'd google, remove Python and rebuild on Linux.
Side note, as a programmer you're going to need to take questions like "How do I....?" and start from the premise that you will need to research the answer.

lime frigate
#

Ok i will try

#

Thanks for the tips

ionic raft
#

For me, programming is 50% problem solving, 40% research, 10% coding ๐Ÿ™‚

ionic raft
# lime frigate Thanks for the tips

Good luck. The good news...when you do start with a fresh environment it should be better.
Also, research about creating and using virtual environment in Python

distant panther
#

help me ):

#

i want help in python django

#

my css files images are not working

#

helppppp pls

#

i m asking for help from 1 hour

#

):

#

i deployed my django app in heroku

#

html file images r working

#

help plz :/

drowsy rune
#

Hi @distant panther it sounds like it's your static files yes?

#

did you do the collectstatic command?

wild gale
dusky jungle
#

whats the best app to use to help write mobile applemon_fingerguns_shades

flat temple
#

How do I add nodejs to a dockerized django app?

versed python
#

The path is relative to cwd

wild gale
wild gale
versed python
#

The browser searches for the file in the current working directory. Since there is no webdev folder in that directory (the directory itself is called webdev), you get an error

inland oak
#

and just exposing it to your dockerized django app

versed python
long jackal
#

how can I find people to work with me on a game website?

versed python
#

Look up a tutorial on basic html

pure nimbus
#

How do I use the django template tags to iterate only over dictionary keys that begin with a certain string? I have a context with lots of keys, but I only want to load 'Column1', 'Column2', etc..

versed python
pure nimbus
#

@versed python I see. I will try that!

versed python
long jackal
#

good idea

#

thanks

wild gale
#

is it becos of the same script tag ??

versed python
#

Yes

#

Learn basic html

wild gale
#

ok sir ๐Ÿ™ thanks for guiding

true kernel
#

slight issue with urls here.

flat temple
#

@inland oak so i plan on using jest as a testing service for the front end

#

and i only need node for jest

true kernel
#

my urls simply append to the current url, instead of appending to localhost/

#

why does this happen?

wild gale
#

i guess i have to use it like this

<script> 
src= "js1.js"
</script>
calm plume
#

Err, wrong reply

calm plume
versed python
flat temple
#

I am new to all of this, including docker

#

not sure what those are

versed python
deft shore
#

What is the best way to acces static files in Django views.py (from objects especially)?

true kernel
#
urlpatterns = [
    path('', views.home, name='home'),
    path('register', views.register, 'register'),
    path('login', views.login, name='login'),
    path('all-stocks', views.all_stocks, name='all-stocks'),
    path('stocks/<str:symbol>/buy', views.buy, name='buy'),
    path('stocks/<str:symbol>/sell', views.sell, name='sell'),
    path('stocks/<str:symbol>/', views.stockinfo, name='stockinfo'),
    path('portfolio', views.portfolio, name='portfolio'),
]

url patterns look like this

#

<h4> <a href="portfolio">Portfolio</a> </h4>, this is portfolio link

true kernel
#

how?

flat temple
versed python
#

Is that even possible?

flat temple
#

idk

versed python
#

Afaik jest is usee for unit tests

#

Its not possible

#

Look into cypress if you want to write e2e tests

#

Selenium if you prefer python

flat temple
#

I think i want unit tests

#

the front end is built in javascript

versed python
#

Ahh then your framework must have jest integration

flat temple
#

thats just it, the framework is webix

#

so its not utilizing node modules

versed python
calm plume
#

If you know that, then you can set up Docker for it

flat temple
#

I do not know

true kernel
#

@versed python in href, if I give a path, shouldnt it go directly there instead of appending to current url?

calm plume
#

Well, I'd first recommend testing that outside of Docker

#

And then, if it works, you can add it into a Docker setup

flat temple
#

it seems like it can work with mocha

#

based on this github

versed python
flat temple
#

mocha is a good alternative

true kernel
#

so, say im at localhost/A. and I click on href="B"----will it go to localhost/A/B ?

#

what if I wanna go to localhost/B?

calm plume
#

Err, I think Jest can work even with static HTML, but I'm not sure

#

So you should be able to use it with this Webix

flat temple
#

perfect

calm plume
#

I'm not sure though, so I'd advise you to try it out before you set it up in Docker

flat temple
#

it seems like it can

calm plume
#

Ok, so if it's just for local testing, Docker compose should do.

#

You can set up a Node.js image and a Python image to run both Django and Node in separate containers

#

But the Node container can go to the Django container's page and run Jest on it

flat temple
#

ok, and thats gonna be on the yml file?

calm plume
#

In a docker-compose.yml, yes

flat temple
#

ok, i ihave a local.yml and a production.yml

#

so id assume the local.yml

calm plume
flat temple
#

na this isnt even a production app

#

its an app im learning with

calm plume
#

Could you show me your project structure real quick so that I can show you can example?

#

Also, do you already have a Dockerfile for django?

flat temple
#

yea iu can walk you through the project

calm plume
#

And your Django Dockerfile

versed python
#

Absolute vs relative paths

meager anchor
#

okay i hate frontend but this is insanely cool

native tide
#

no idea if this is webdev or not but tryna get a flask server running as wsgi and using live reload but cant seem to find any coherent examples or docs so if anyone has experience either or then some help would be appreciated

wheat swift
#

I can help but i also need help lol

Hello! My django model object is returning False when i try to get it's id as such: chatroom.id Does anyone know why it would do this? I saved the object right before using chatroom.save().

#

Dragon where are you running this app?

native tide
wheat swift
#

so thats pretty broad i guess giving you documentation of how to run a flask app would be what you need but your not a newb :/

#

so idk how much help it would be

native tide
#

its mainly the wsgi part im struggling with

native tide
#

thats whats preventing me from setting up the livereload by the looks of stuff

wheat swift
#

Just run the flask app

#

I would do live reload with a systemd service

#

That reboots the flask app when it fails.

native tide
#

it needs to be constantly updating the web content as im trying to set up a live counter

wheat swift
#

Flask would render different data depending on the state of the data in your flask app

native tide
#

i have the server being served but its not auto updating i still have to manually refresh the page

wheat swift
#

Oh! Lol thats a completely different thing

#

You need websockets

#

or pinging requests to auto update your page

#

There are actually 3 ways to go about it; But.. I recommend websockets.

native tide
#

well thats what livereload is supposed to do but so far it aint working

wheat swift
#

Did you try this answer on livereload?

native tide
#

probably for for testings sake one more wont hurt

#

didnt update the value until refreshed

#

might be how im running it

#

if i just run the main file and not using a flask command

#

but then i get module not installed errors cuz my pc be broke like that

wheat swift
#

yeah if u do flask run command it uses a different env

native tide
#

i cant run on host system cuz my python doesnt detect installed modules and cant run on cloud cuz the ips dont allow connections

wheat swift
#

I think you cant run it manually with the main.py file because you aren't pip installing on that command...

If you are running python for example use:

python -m pip install livereload

native tide
#

i have everything installed already

#

python just thinks i dont

#
from flask import Flask
import urllib,json,os
from mcstatus import MinecraftServer
from livereload import Server


app = Flask(__name__)

@app.route('/')
def main():
    server = MinecraftServer.lookup("51.222.134.183:2011")
    status = server.status()
    result=("{0} ".format(status.players.online))
    return(f"server has {result}/100 online")

if __name__ == '__main__':
    main()
#

thats the flask code

#

without trying to add a livereload server

#

what it looks like i need to do is include the routes somewhere else and import

#

nope didnt work

surreal merlin
#

Anyone would be able to help set up traefik with wildcard domains and auto ssl certificates? ๐Ÿ˜„

glacial yoke
#

How could I create a function in the django backend, and then have the ability to use it in my react frontend build, that I deployed into django.
So, I know that to get something from the database, I would have to create an api view through DRF, and then in the frontend I would just refer to the url of the apiview
But how do I do the same thing with functions
For example if I wanted to implement logging in from a social media like facebook, and I wanted to fetch their username, to store in the database, so that the user can be controlled, remembered, etc., but I would have to display the function on the actual website, so I would have to refer to the function from the backend on my frontend

glacial yoke
#

would I just do it through views.py, and then have a straight forward binded link in urls.py

dense slate
#

I used to use a DigitalOcean Django Nginx Gunicorn tutorial for my initial setup.

#

That might work for flask if you know how to just do it in a flask environment, but it will help you get the server aspects running at least.

dense slate
#

That's basically the same thing as creating a REST api. You point the url at a specific view via its url, and it does whatever you're trying to do.

low badger
#

Hello guys, I wanna ask is MySQL good with Django, cuz a friend says its not the best choice

#

so what do you think?

dense slate
#

I thought MySQL is really only used primarily with C-based stacks or windows servers.

low badger
dense slate
#

You don't have to. I would use the best DB for your needs. But if it's a linux server, then PostgreSQL will be a better fit.

#

You can also use Postgres on windows, so you don't have to worry about later going to production on a linux server if you code on windows.

low badger
#

@dense slate thank you for help

native tide
#

figured out how to not only fix my issue but also add a html interface and use javascript to take live updates and set values instead of piping python directly in flask

worn fjord
#

Can anyone help me with flask

#

Please.

native tide
#

what u struggling with

#

i may be new ish but may be able to help

worn fjord
#

this is my whole code

#

the issue is that i cant seem to send face_detection my image paths

#

and this is really blowing me up.. been with it from 2 days and cant figure out shit and turned to discord today for help. Ive to submit it tomorrow and i cant seem to get a hang of it

#

@native tide ^

#

anyone who could help would be heavenly appreciated. thank you

gloomy wasp
#

What's the best Django tutorial (either video or text (except docs)) in your opinion?

worn fjord
dense slate
dense slate
worn fjord
dense slate
#

'D:/python_Api_try/frame_{j}_face.jpg')

#

shouldn't they be backslashes?

gloomy wasp
worn fjord
dense slate
#

That error is basically saying it can't find your image.

#

So either the path isn't right or a setting in your code pointing to a particular directory isn't right.

worn fjord
#

yes yes @dense slate you are exactly right. The thing is i know that the path is the issue, the problem is that i dont know how to fix it

#

i rewrote some things wait

#

@dense slate take a look please

dense slate
#

I'm looking at that.

worn fjord
#

thanks a lot for trying to help man! Been stuck on it from quite a while now and its 3 30 am here xD

dense slate
#

So look at all the paths and make sure they are correct. I don't know what they should be, but d:/ isn't correct syntax.

#

So I'm not sure how that worked before.

worn fjord
#

d:/ is my folder, the program never reaches there.. it pushes an error before it goes there

native tide
#

omg๐Ÿ˜ซ

worn fjord
#

@dense slate it just saves the img_cropped there

native tide
dense slate
#

Is it not supposed to be d:\?

#

back slashes instead of forward

worn fjord
# dense slate Is it not supposed to be `d:\`?

OH nooo.. thats not the problem at all.. It uses forward slash when it comes to paths here.. I Honestly dont know why.. Here take a look at this code which is just 'detect_face' and it would work absolutely fine

dense slate
#

Hrm, ok.

#

so why does the path change from forward slash to backward slash later in the path?

#

I've never seen that, so that might just be my ignorance.

worn fjord
dense slate
#

Not to mention a double slash.

#

See, here you have forward slashes
C:/Users/HP/Desktop/models/frame_{j}_face.jpg'

worn fjord
dense slate
#

Ok anyways

worn fjord
#

oh look those are the image paths.. see the img_cropped part.. there its the same way im doing it

dense slate
#

I really don't know otherwise. That feels like the issue to me.

worn fjord
#

tell me exactly what to do and ill fix it

worn fjord
dense slate
#

where are you telling it to use the WIN_...Pro.jpg?

worn fjord
#

@dense slate list.append(os.path.join(app.config['UPLOAD_FOLDER'], filename))

#

so basically it just saves it on a server if i dont put my own upload_folder in there and then i append it in list

dense slate
#

But that's not in this code

worn fjord
#

ummm it is

worn fjord
dense slate
#

Oh gotcha, sorry looking the wrong one.

worn fjord
#

not a problem man youre the only one trying to help me since 14 hours. Im thankful right now lol

#

youre the only one who showed up since i last msged in places since 14 hrs*

dense slate
#

What's your upload folder path in settings?

#

oh i see it

worn fjord
#

oh its saving it in the server

#

temporarily

dense slate
#

what does os.getcwd return?

#

I'm just trying to figure out where the path is getting corrupted

worn fjord
#

yes so i dont know let me see?

dense slate
#

you need to figure out all the things adding aspects of the path and nail down where it's giving you bad info

#

very likely that flask is pointing at something you're not expecting it to, or alters the path you anticipate, so you need to figure out where that is.

worn fjord
#

i havent used os.getcwd and dont know what its doing.

#

yes @dense slate ive been trying my ass off to do that lol. this should work fine instead its not

dense slate
#

ok, but list.append(os.path.join(app.config['UPLOAD_FOLDER'], filename)) uses whatever os.getcwd returns, right?

#

and you don't know what that is

#

can you make it like something = list.append....etc. and print it?

#

see what you're actually getting

worn fjord
#

on it boss

dense slate
#

or maybe just print os.path.join(app.config['UPLOAD_FOLDER'])

worn fjord
#

yeap gotcha

#

@dense slate its giving me the correct thing!

dense slate
#

ok, so where is "imagez" coming from?

#

as in your error

worn fjord
#

wait sending ss

#

@dense slate

dense slate
#

aha, so first of all the slashes did change, and now you have two \ at the beginning and between the path and the image name.

#

What did you do that changed it?

worn fjord
#

i didnt do anything, that's the same code

#

@dense slate

dense slate
#

Same code but different error?

worn fjord
#

no the error was for the VVEEERRRYY initial code

worn fjord
dense slate
#

You need to show current code with current errors otherwise it's impossible to correctly debug stuff.

#

You've got the idea of how to start searching out what is now causing an extra / in those two places.

#

Remove those and, if the path is accurate, it will work.

#

Like why do you have \ instead of / in the path if it is the same code. You had to change something.

snow kettle
#

Hi, can someone with Flask experience please check out #help-cookie ? Thank you!

worn fjord
dense slate
#

I have to step away as well. Good luck!

opaque vale
#

Hey guys when your mocking up a website, just basic we'll say a navbar and then a main content pane. Do you wrap flexboxes in grid boxes to get the scability to mobile? If this is a stupid question my bad.

native tide
worn fjord
native tide
#

๐Ÿ˜ซ๐Ÿ˜ฉ

opaque vale
#

Dont know django or react enough to help you, good luck friend

native tide
#

What I can't believe is that I found no one from stackoverflow to help me yet

#

this is crazy

ionic raft
#

Once I get through phase 1A of my web project I'll be onto React to build a diagramming app for this web app. But for now, I'm green when it comes to React.

native tide
#

I see

#

ok

nova pewter
#
 def registration(request):
    registered = False
    if request.method == "POST":
        user_form = UserForm(data=request.POST)
        profile_form = UserProfileInfoForms(data=request.POST)
        if user_form.is_valid() and profile_form.is_valid():
            user = user_form.save()
            user.set_password(user.password)
            user.save()

            profile = profile_form.save(commit=False)
            profile.user = user
            if 'profile_pic' in request.FILES:
                profile.profile_pic = request.FILES['profile_pic']
                profile.save()
                registered = True
        else:
            print(user_form.errors, profile_form.errors)
    else:
        user_form = UserForm()
        profile_form = UserProfileInfoForms()

    return render(
        request, 'templates/registration.html', {
            'user_form': user_form,
            'profile_form': profile_form,
            'registered': registered
        })


#
    if request.method == "POST":
        user_name = request.POST.get('username')
        pass_word = request.POST.get('password')

        user = authenticate(username=user_name, password=pass_word)
        if user:
            if user.is_active:
                login(request, user)
                return HttpResponseRedirect(reverse('index'))

            else:
                return HttpResponse('Account not Active')
        else:
            print("someone tried to login and failed")
            print('username:{} and password :{}'.format(user_name, pass_word))
            return HttpResponse("invalid login details supplied")

    else:
        return render(request, 'templates/login.html')
#

i created a register form to register users and a login form, registering a user is working fine but when i try to logging in with the user that i created i get invalid login details

#

ps. when i try to log in with the admin superuser it is working fine

nova pewter
#

after looking further into it i tried to print out the 'user ' variable and it prints out "none"

ionic raft
#

The user and profile tables from models.py would be enough

nova pewter
#
from django.contrib.auth.models import User
from django.db.models.deletion import CASCADE


# Create your models here.
class UserProfileInfo(models.Model):
    user = models.OneToOneField(User, on_delete=CASCADE)
    portfolio_site = models.URLField(blank=True)
    profile_pic = models.ImageField(upload_to='profile_pics', blank=True)

    def __str__(self):
        return self.user.username

distant flax
#

I would like to develop a widget that can embedded into a site like Weebly. Does anyone know if this is possible?

lime frigate
#

I need to install mongodb database first

#

Finallyy argghhhhhhh

nova pewter
shut bloom
#

Hello Guys,
Does Github webpage deployment support SASS?

dense ravine
#

I am trying to fetch data from a public api and store an object in my custom created models, i.e. my database. I am able to display the api data on an html page but is there a way to store it into database directly?

dense ravine
#

Django sqlite

shut bloom
#

class MyModel: ..... ....

Suppose its a class model where you want to store your API json data.

#

Now you have to make an object in API View

#

you may be did it in API View

#

obj = MyModel(a=1,b=2...)
obj.c=12;

#

obj.save()

#

that's it.

dense ravine
#

So I should be able to assign the values from the Api to the model in the views itself?

#

Upon creating the object and pulling from the json

#

I'll give it a try thanks

true violet
#

does this look good

wooden ruin
quiet valve
#

Can i do web development with python?

#

I use html css js

inland oak
#

Flask for example is web framework to do this

quiet valve
#

Ok...thanks

distant panther
drowsy rune
distant panther
#

k

#

btw yes that's my static file

#

i have css folder inside it and then img folder

#

images in html file is working

#

but i used bgimage in css file

#

that is not working

#

);

rough tulip
#

I am trying to make Online video learning platform(like Udemy). So what is the best way to store videos?

rough tulip
#

that's great option but there some problem with funds

thorn igloo
#

large storage is not free bro

rough tulip
#

yeah I know, but this clients sucks

#

so is there any platform which can be used for development purpose but later it can scale ?

ionic raft
# true violet http://indiaquizbyrishabh.ezyro.com/ hows this

I get why you chose the white, orange and blue (I see the connection with the Indian Flag). However, the neon green is a bit harsh in contrast. I would change the neon green buttons to perhaps be the orange for the Quiz banner, and shift the banner to be the background blue. I'd also change the colour of the question-font to match the blue background. This would honour your intention of aligning the colours of the Indian Flag, but would bring you to just those three colours. A tri-colour palette would actually have potential. The neon-green is murdering the visual experience AS-IS.
Search through google fonts for alternatives. There has to be a font that will have more of an Indian feel to it. If you're going with the colours of the Indian flag, pick a font that fits in. Times New Roman may be colonial, but the Brits have been gone for a long time. ๐Ÿ™‚
I would also lose the light-grey drop-shadow behind the question bubble, and tighten the radius as well.
You might want to look into css. You could align those four answer buttons with flex-box and have a lovely grid to make things look super crisp. If you're new to css then look at a Framework such as Bootstrap/Tailwinds.
And keep the hover-over of white for the buttons. No matter what button colour you go with, that's actually working as-is.

ionic raft
thorny quartz
#

I have 2 different model in django and I want to see data of model 2 using model 1 id how this can possible ?

lavish ferry
#

Anyone good with Jinja2?

    <div class="container content">
        {% block content %}{% endblock %}
        {% if self.content() == none %} {% include "other/soon.html" %} {% endif %}
#

So I load the content block, but I am trying to have it so if the content block is empty, it includes the specified html.

dusk portal
#
@csrf_exempt
def signup(request):
    if request.method=='POST':
        try:
            data=JSONParser().parse(request)
            form=RegisterForm(data.POST)
            if form.is_valid():
                form.save()
                token = Token(user=form)
                return JsonResponse({'token':str(token)},status=201)
        except IntegrityError:
            return JsonResponse({'error':'That username has already been taken. Please choose a new username'}, status=400)````
#
<title>ParseError
        at /api/signup/</title>``` in post man
lavish ferry
#

Hey Aryan, anychance you know about Jinja2?

dusk portal
#

im trying to create sign up functionality by django rest framework

dusk portal
lavish ferry
#

I shared above, I am trying to say if the content block is empty, include a html page.

dusk portal
#

ohk

#

wait lemme see

dusk portal
#

i noticed 1 thing here u ended block at the beggening

lavish ferry
#

At the moment content block empty never evaluates as true

#

Also the content block is empty because it is filled on each page template, here is an example:

#
{% extends "layout.html" %}
{% block content %}
{% endblock content %}
#

That is the about page, where the content block should evaluate as empty

dusk portal
#
<div class="container content">
{% block content %}
{% if self.content() == none %}
{% include "other/soon.html" %}
{% else %}
<p> idk</p>
{% endif %}
{% endblock %}
```here i just showed a example 2 things to notice  1st put everything between block content and endblock content 2nd put endif in list after the else
zealous lagoon
#

hi any html snippet copy site

dusk portal
zealous lagoon
#

alright ty

dusk portal
#

umm

lavish ferry
#

like this the if still doesn't evaluate as true:

   <div class="container content">
        {% block content %}
        {% if self.content() is none %} 
        {% include "other/soon.html" %} 
        {% endif %}
        {% endblock %}
#

When loading this page:

{% extends "layout.html" %}
{% block content %}
{% endblock content %}
dusk portal
#

ohh

lavish ferry
#

I also tried == none

dusk portal
#

so u want if self.content() is none

lavish ferry
#

and empty

dusk portal
#

can u know

#

i**

#

can i know what is self.content here

#

r u using backend?

#

can i see ur view for this (views.py func for this page)

lavish ferry
#

So this is in the layout.html (for every page)

   <div class="container content">
        {% block content %}
        {% if self.content() is none %} 
        {% include "other/soon.html" %} 
        {% endif %}
        {% endblock %}
#

Then depending on the page I am loading, I extend the layout.html with the necessary html for that specific page. Take the about page, where I extend it with no HTML:

{% extends "layout.html" %}
{% block content %}
{% endblock content %}
#

I want some kind of expression such that if the block 'content' contains nothing, I include some HTML.

dusk portal
#

{% if self.content() is none %}
btw this is 101% incorrect

#

u just here need to type variable name

#

like u know backend? @lavish ferry

lavish ferry
#

This is in Flask, though I just want to know what Jinja expression will work for this if it could?

dusk portal
#

umm first listen

#

wanna see a example here?

#

wait lemme send ss

lavish ferry
#

This still evaluates as false always:

    <div class="container content">
        {% block content %}
        {% if content is empty %} 
        {% include "other/soon.html" %} 
        {% endif %}
        {% endblock %}
#

Happy to see an example

dusk portal
#

this works

#

u just need to write variable name

#

not self.content() == none

#

only see those 2 line which i holded from mouse

#

just write variable name

#

web framework handles this for us

lavish ferry
#

I still don't get what the if statement expression should be?

dusk portal
#

show me ur query that flask code for this function(page)

lavish ferry
#
@app.route("/about")
def about():
    return render_template('other/about.html', title="About")
#

Renders this:

{% extends "layout.html" %}
{% block content %}
{% endblock content %}
#

Which extends the layout html, where this is:

    <div class="container content">
        {% block content %}
        {% if content is empty %} 
        {% include "other/soon.html" %} 
        {% endif %}
        {% endblock %}
dusk portal
lavish ferry
#

The what? I don't have a database.

#

All I am trying to do, is if the person goes to a page which has a route I have defined, though I haven't added any content for that page, the page defaults to containing some html content that says I am not done yet.

dusk portal
#

so what's the logic of adding if statement

#

XD

dusk portal
#

if else for and all are used while we work with databases

lavish ferry
#

Surely I can somehow check if a content block is empty?

dusk portal
#
<div class="container content">
        <--Your extends-->
        {% block content %}
<--content-->
        {% endblock %}```
dusk portal
#
<div class="container content">
        {% block content %}
        {% endblock %}```
#

done

#

lol

#

do not add anything

#

start and end it

#

same u have done in ur base.html or layout.html

lavish ferry
#

That makes no sense.

lavish ferry
#

Yes I have used Jinja2 plenty already

#

Your response to me asking if Jinja2 has a method to check if a content block is empty is what makes no sense.

#

This is the closest I found in all my Googling

#

Yet no matter how I try implement this massively upvoted answer, it refuses to work as well.

#

If I do this:

    <div class="container content">
        {% block content %}
        {% endblock %}
        {% if self.content() %} 
        {% include "other/soon.html" %} 
        {% endif %}
#

It always evaluates as true

#
    <div class="container content">
        {% block content %}
        {% endblock %}
        {% if not self.content() | trim %} 
        {% include "other/soon.html" %} 
        {% endif %}
#

This works with the desired result

#

About time

forest berry
#

Iโ€™m building a little web app w flask rn and Iโ€™m trying to learn how to use databases: Is it worth learning SQLAlchemy or should I just start learning MySQL?

versed python
forest berry
lime frigate
#

Guys if i'm using mongodb for django i have to setup the user thing and user authentication using mongodb right? The default user database cannot be used right

twilit acorn
#

Can anyone help guide me on how to use django in vs code?

versed python
#

They're both easy so won't be much of a hassle

lime frigate
twilit acorn
#

alright also have been trying to activate a virtual environment in vs code for about 20 minutes now do you know how you are meant to do it by any chance?

twilit acorn
twilit acorn
thorn igloo
#

does python work in your terminal?

twilit acorn
#

yes

thorn igloo
#

cool, so open the terminal in vs code in your project

#

then type:
python -m venv virtualenv

twilit acorn
#

ok I will try that

thorn igloo
#

after it's done, you activate the virtual environment by this command:
virtualenv/scripts/activate

#

if this works correctly, you will see something like (virtualenv) in your terminal

twilit acorn
#

wait ill dm you it shows some error

lavish ferry
#

Don't DM

#

I am learning from this as well

thorn igloo
#

i disabled DMs

twilit acorn
#

oh well

#

look at this

thorn igloo
#

full message

#

i've seen this before

twilit acorn
#

disabled on this system or something

lavish ferry
#

Sounds like it is an easy fix then. Just a question of how to enable it.

#

You are an administrator on the computer right?

twilit acorn
#

yea

versed python
#

its a pretty common problem

thorn igloo
#

Set-ExecutionPolicy RemoteSigned

versed python
#

youll find the solution

thorn igloo
#

running powershell as admin and run that

twilit acorn
#

gives me another error

lavish ferry
#

Ignis you are correct by why shit on a discussion where they are already being helped

versed python
twilit acorn
twilit acorn
thorn igloo
twilit acorn
#

ok

lavish ferry
versed python
#

yeah all cool, i wont do that then

twilit acorn
#

as admin'

thorn igloo
#

try that command i sent

twilit acorn
twilit acorn
thorn igloo
#

A

twilit acorn
#

pressed A

twilit acorn
thorn igloo
#

cool, now try activating the virtualenv again

twilit acorn
#

worked thanks for your help

thorn igloo
#

cool

twilit acorn
twilit acorn
lavish ferry
#

Thanks for the lesson as well Droid! I was wondering how to do this. Is VSCode smart and remembers virtual environments for projects? Or do you need to activate each time.

#

Lol

thorn igloo
#

the python extension by microsoft sometimes activates the virtual environment automatically if it detects it, but that's not always the case, so you'll probably have to activate it manually,

#

just run /virtualenv/scripts/activate etc, or you can create a script to do this for you and just run that

twilit acorn
thorn igloo
#

np

twilit acorn
thorn igloo
thorn igloo
#

you will see clone there

twilit acorn
thorn igloo
#

or you can just use your terminal, if you have git installed, and type: git clone url

twilit acorn
#

I dont have those options?

thorn igloo
#

maybe your account not set up, i'm not sure

twilit acorn
#

alright thanks

thorn igloo
twilit acorn
#

Cool, thanks

twilit acorn
dusk portal
#
@csrf_exempt
def signup(request):
    if request.method=='POST':
        try:
            data=JSONParser().parse(request)
            form=RegisterForm(data.POST)
            if form.is_valid():
                form.save()
                token = Token(user=form)
                return JsonResponse({'token':str(token)},status=201)
        except IntegrityError:
            return JsonResponse({'error':'That username has already been taken. Please choose a new username'}, status=400)```
dense slate
#

@dusk portal You've been here long enough to know to ask better questions about what problem you're having.

dusk portal
#

Yes

#

I'm here from

#

When I started to code

#

And promised myself that I will help everyone and will take help from everyone by teasing and being weird idc
But I will take help and give help to everyone

random finch
#

seriously, what's the difference between get and post requests if I can just replace the post function in my python code with headers and body with a get and it still works in Postman?

dusk portal
random finch
#

yup

#

they say that get is to "get" data from the server while post is to update data but I see my code works with either of those functions.

#

so why do they even exist separately?

dusk portal
#

Umm nice question and I have a better answer

#

@random finch

#

Ohk u r here I'm answering

#

Just forget about APIs and all for a sec

versed python
dusk portal
#

Now imagine u are in a website with a button named contact
When u click on that u receive the html code and response that is get request as name tells get
Which gets the data
And then u see a form there and then u fill it in left bottom corner u will se something and the page reloads as it sends the post request
So when we visit any site by our chrome or default browser it sends a get request to get the page and then if u fill any field it sends the post request
So the reason we use postman and all is in that we have to open the page in POST request but our browser opens in get request and error comes there

dusk portal
# dusk portal Now imagine u are in a website with a button named contact When u click on tha...

One more good example is imagine u r making a simple contact page u write def contact and if request.method == POST
Before the if loop iteration u have to pass any render(html page) else it shows No response /Null
So if it renders the page then as our form uses the function method name and all the things so form sends the post req and form in submitted else in api u don't render any page or any response outside the loop

#

All my exp about this packed

#

For u

random finch
#

I'm still confused @dusk portal but appreciate the effort. Are you saying browsers can't handle post requests?

dusk portal
#

Yes when u submit form it handles post request browser handle get requests

random finch
#

If the POST request does not have any headers or body, wouldn't the browser be able to handle it?

dusk portal
#

I was having same problems

#

Just work

#

Just work

#

See JustDjango ytber playlist and one more guy have some 12-13 vids see that and Udemy course

random finch
#

I'm just developing basic REST APIs at the moment, nothing like site building or anything

lime mica
#

The reason why the get and post are seperate is get shouldn't affect the data on the database.
And yes we can use get for all operation instead of post. But generally we shouldn't use get for the which can be done by post. In certain cases u might want to block some requests like post or delete in such cases if you have used get then you have to write logics manually to block some of the requests.
Or if u have used post then it is very easy to block post requests.

IT'S LIKE ROAD RULES, WE CAN GO LEFT SIDE OR RIGHT SIDE OF LANE WITHOUT FOLLOWING RULES BUT IF WE FOLLOW GENERAL RULE OUR LIFE IS EASIER TO SOLVE PROBLEMS

random finch
idle gull
#

Hi there, wondering if someone could help me (can post relevent code when asked, im not entirely sure which parts are relevent). im working with django atm, trying to use {% block <name> %}. whenever i do, i get server error 500. it works if i just write plain html, but when trying to include django stuff, it errors

lime mica
idle gull
cloud mist
#

Sry, probably just me being a noob, but why can't I webscrape <table class="accuracy_stats" ?

I am using py soup_text.find_all('table', attrs={'class':'accuracy__stats'}) To search, and it doesn't find anything ๐Ÿ˜•

thorn igloo
#

probably dynamic data, just a guess

cloud mist
thorn igloo
#

try selenium

#

beautiful soup scraps the html content it sees. i'm assuming this website was made with a framework (since there's a data-v-... attribute) like react or vue. basically, these frameworks don't put all the content into html files,. the content is appended into an element with the id #app for example, using javascript, hence the data is dynamically loaded in a sense

cloud mist
dense slate
dusk portal
#

that;s a big question im trying to make sign up functionality by django rest framework but after user is created it should create a token and ofc it can't be done in our browser so trying to do that with postman but it's showing error

#

code ^^

dusk portal
dense slate
#

So how did you try debugging it so far? Did you print data?

distant void
#

Hello Python Army, Hope you all are doing well. Anyone wants to learn Django as a pair programming? I have started to learn Django. anyone wants to join me?

nova pewter
#
class UserProfileInfo(models.Model):
    user = models.OneToOneField(User, on_delete=CASCADE)

why do we do this?

dense slate
#

Do what?

nova pewter
#

user = models.OneToOneField(User, on_delete=CASCADE) creating a OnetoOne field

dense slate
#
OneToOneField

This is most useful as the primary key of a model which extends another model in some way. A one-to-one relationship. Conceptually, this is similar to a ForeignKey with unique=True, but the "reverse" side of the relation will directly return a single object.
nova pewter
#

the User class already has a functionality to store usernames right? so when do we use this user = models.OneToOneField(User, on_delete=CASCADE) and why?

dense slate
#

Because you don't usually want to bloat one table to with a huge amount of data. So you can extend the model by having smaller tables you can reference as needed.

#

My guess is that this is less important now with frameworks like GraphQL where you can be more selective about the data you ask for, but still good practice not to bloat single models.

nova pewter
#

oh, thank you

dense slate
#

@nova pewter However in this case, you use OneToOne or a ForeignKey to tell this model that you want to get the data based on the user described in your ForeignKey.

#

This way you have the user object available to use when you reference the other model, rather than just a username or id, for example.

nova pewter
#

i see

#

i am trying to figure out what's wrong in my code and couldn't find the problem as there is no error, so i am walking through the whole code rn

dense slate
#

What's the goal and issue you're seeing?

inland oak
nova pewter
#

i have it posted up here wait i'll point out the issue to you

dense slate
#

even if you only want one piece

inland oak
#

behind this model can be the same SQL database in both cases

dense slate
#

Aha, so if I am selective in GQL, am I still making the same request as if I queried the model directly? What is the benefit of GQL in this case.

#

I know that I only get back what I ask for, but is the request load the same?

inland oak
dense slate
#

Ok I see, so just a more organized way to request data vs REST

dense slate
#

Or more efficient.

inland oak
#

better suiting for over bloated apps

#

both

nova pewter
#

smh when i try to login with the superadmin that i created from manage.py i am able to login and the user=authenticate() method is working fine, but when i try to login with the custom user that i created i get user as "none"

dense slate
nova pewter
#

yes i checked it inside the admin panel, is active is checked

#

i tried printing user_name and pass_word and it is giving the correct output

dense slate
#

do you get invalid credentials when logging in with it?

#

or just nothing and refreshes the login page

nova pewter
#

i get this ``` else:
print("someone tried to login and failed")
print('username:{} and password :{}'.format(username, password))
return HttpResponse("invalid login details supplied")

dense slate
#

but what happens when you actually login in, on the admin login page (or whatever page you're loggin in)

nova pewter
#

"invalid login details supplied"

dense slate
#

right ok

nova pewter
#

if i log in with the superuser i am able to log in

dense slate
#

I know there's an issue if you don't hash the password as well. Did you check the DB is the pw is hashed or plaintext?

nova pewter
#

hashed

dense slate
#

And for sure is_active?

nova pewter
#

yeah

dense slate
#

can you print the contents of the user model that's being logged in and show the results?

nova pewter
#

1 sec

dense slate
#

I don't see you setting is_active in reg. can you add user.is_active=true to your registration?

nova pewter
nova pewter
dense slate
#

right

#

But I realize that probably won't change anything since I'm not sure why you're getting none as your user when you log in.

#

Your authenticate function is returning none or it does return a user?

nova pewter
#

but when i pass in the superuser, it doesn't return none

dense slate
#

user_name and pass_word are correct with the normal user? @nova pewter

cerulean badge
#

any reason one should not have unique name/title field on product model for an ecommerce website?

native tide
#

More random questions from me lol if I have a flask application rendering a template that imports a python value when it renders the value of the import is the value of whatever I'm importing at the time. If the value is something that is constantly updating can I use JavaScript to then change the values as they update or does the render mean the value will always be set?

inland oak
#

Render makes initial state. Everything after that is a fair play for javascript

#

Or for additional... something like post submit requests

#

U can make requests with js, or using web sockets for constant stream of information

native tide
#

The python code is constantly checking/updating a value and when rendered what ever value it is, is rendered but I can't seem to get the js to take any of the updated values without crashing the page

#

After the render is rendered the values stop updating but I think that's because of how my loop is set up and if I take the render out the loop the page never loads

glacial yoke
#

How can I add a query set to the db through views.py?

rustic iris
#

hey guys wanted to ask which framework b/w Flask and Django should I use to combine it with React for a web app. THanks

rustic iris
glacial yoke
dense slate
#

So you should probably check out a basic tutorial and it will walk you through that.

lunar stream
#

Question
How to add preview to your website link?
Purpose
When I share the link, I want this to have an specific image preview of the website

glacial yoke
dense slate
#

No, not really. It's quite a number of steps to get that functionality working and tutorials have been created so many times that it would be literally faster to just find one of those.

#

I can tell you that you put information in a form (usually) that, after you submit it, it goes through an url/route that points at your view that then does the database work you tell it to do.

#

Why do you need an example if you don't want to learn it?

versed python
thorn igloo
#

oops, i read that wrong

glacial yoke
versed python
#

Good luck

glacial yoke
versed python
#

Not on discord

austere relic
#

This server sometimes spoils people

remote kestrel
#

Hello Guys, what's the best way to build a websocket for example for google maps? Do you advice me to install a library or I can do it with import socket? Can I use the library requests for websockets? If I can't which library is the most used?

#

:c

ionic raft
# glacial yoke How can I add a query set to the db through views.py?

That question is actually much bigger than appears on the surface. I've heard of things like REST frameworks to get at the DB through Django. For my part, I went through a number of tutorials learning how to...as I like to put it...dance with the Django DB.

The reason why this is a huge question with many answers is because you're actually asking (as I see it) how to use the application layer to access (CRUD) the DB layer, and in turn prepare the context dictionary (in Django at least) for the presentation layer.

Understanding this is actually at the heart of what (from what my 1.5 months of experience with Django) is showing me is the difference between a static one-way (information push) site, to a dynamic two-way (pull-push information site). I'm currently building a process improvement project management web application, and I can tell you first hand I'm likely over 100 hours learning, experimenting with, and expanding my understanding of how to dance with the DB in Django. And I know it's not done there. I have much more to learn (and I've got React/JS to learn yet to build another app within this web application)...

ionic raft
# glacial yoke How can I add a query set to the db through views.py?

I apologize for the long response, but the challenge with your question is that it actually is valid to answer with the suggestion that you research, and learn. I too learn through examples, but such a broad question is not IMHO a good question. Coming forward with a specific question about how to take a step in learning how to dance with the Django DB would be very helpful. Frame the question with what you're aiming to accomplish, what behaviour you already have, and what you've tried to get there. Then, as someone responding to your question we are both saved time because I don't repeat what you've already tried, and your stated expectation guides me.

I shall give an example. Yesterday, I realized that with the potential for 1,000s of Process Improvement Projects for a higher-tier subscriber I needed a way to filter on the dashboard (and there is no way a lazy single search will cut it). However, I needed to be able to filter projects by Organization, Team and Process. I managed to answer this question for myself. However, had I come to this Discord I might have posed the following as a question.
Goal: I would like to filter across a DB table/model looking at three different fields in four different tables.
So far: I have managed to filter by one attribute. However, when I try to add more I get multiple returns.

What I was doing at the time was actually adding multiple submit buttons for the form. This was creating the problem.

#

End result...

glacial yoke
#

I just don't see the logic, you know

#

And I don't think that my question was asked poorly, because I quite literally want to learn, how I can write info to the created models in the database, through the actual program/code, and not just through the admin console or the django shell

ionic raft
ionic raft
# glacial yoke And I don't think that my question was asked poorly, because I quite literally w...

We can agree to disagree. Your question is huge in scope. It's asking about how to dance between DB, Application and front-end layers. The challenge is that there are many ways to answer it. The reason I feel it was a poor question is that you've not given me a concrete expectation, what is happening or what you've tried.
You want to learn. I want to help you. However, I don't want to engage in a question where I don't even know the specifics of what you're expecting, AND where you've shown no effort to apply yourself in learning the concept.

glacial yoke
#

anyways, thanks for the replies

ionic raft
# glacial yoke well, idk, I guess I might just go learn it myself

That's the life of a programmer. ๐Ÿ™‚
Go and get lost in the concepts....get clear on a small thing that you're stuck on you'd like to accomplish on that journey, and then come back here with a specific question with your expectation, what's happening and what you've tried. I'll guarantee you it will be well received. And if I'm around and can help I will. ๐Ÿ™‚

dense slate
#

Yes that's exactly it, @ionic raft . The best help is to help you understand how to find the solution, not just give it to you. That way you get to the solution, but more importantly you learn how to figure things out on your own. That's one of the hardest things to learn.

That, or, if you have at least attempted a solution and are stuck, we can help you debug that for sure. @glacial yoke

ionic raft
# dense slate Yes that's exactly it, <@837562596231872512> . The best help is to help you unde...

My greatest growth as someone 4 months into Python and 1.5 months in Django has come from being pushed to solve problems for myself. My experience yesterday, solving a problem I've never really seen implemented (and that there certainly is no tutorial for), came directly from getting better at solving problems myself. I believe the defining difference between a beginner programmer and an intermediate one is that you can generally find most solutions yourself. Sometimes, you have to work with a snippet from Stack Overflow. Other times, you make an abstract leap from a previously applied pattern or concept. However, the beauty of the philosophy of support in this volunteer community is that we're teaching a man how to fish. These past few weeks I've never gone hungry.

lunar stream
dense slate
# nova pewter yes

Ever figure out the issue? That's a weird one. Almost as if your authentication function is messed up, but I'm guessing you haven't modified that?

nova pewter
#

took a break for a while , gonna try to fix it after an hour or so

dense slate
#

Let me know if you make progress! I'm genuinely curious.

nova pewter
#

sure

ionic raft
nova pewter
#

yeah usually when i get a error i am happy because i know what to lookup on if i want to fix it

#

last time i didn't get any error and spent like 5 hrs fixing the issue, turned out it was a small mistake in the html XD

nova pewter
#

its fun tho when it gets fixed!

ionic raft
#

Like when you refactor a field, but the refactor didn't make it to every field and it's naming.
Yes, the reward is in the fixing. The journey is in the persevering.

nova pewter
#

๐Ÿ‘

meager halo
#

hi, i have a problem to deploy a app

#

my app is a api rest

#

simple but i dont can deploy to heroku

fierce hare
#

I'm not sure if this is the place to ask about this.

https://www.youtube.com/watch?v=WMXWksdBhD0 (Skip to 18 seconds)

I was wondering what tool can be used to do this? Like I want text in the middle of the screen in a box, all blurred and have a small box go across each line unblurring so you can read the next inside the small box.

native tide
#

So I'm using django with my css file in /static/my_app/main.css and when I alter the css file it doesn't actually change the styling. Is there a way to use the edited css instead of the old file?

#

restarting the server didn't even work ๐Ÿ™ƒ

native tide
dense slate
#

Depending how it's setup sometimes you need to do that to refresh anything used in your static folder.

native tide
#

I added STATIC_ROOT = BASE_DIR / 'static' to my settings.py file and ran collectstatic but it's still using the old css values. Should STATIC_ROOT point to the app that contains the static file?

#

nevermind it was browser related. Thank you @dense slate

native tide
#

Hey, I have question regarding nodejs. I have a web server and I need to call function in javascript file. I assume that it should be done using websockets like socket.io but I have no clue how, would really appreciate a help since only thing that I can find is how to call server sided function from javascript which is completely opposite from what I need.

warm igloo
#

you may have better luck with that question on a node server? this may be #web-development but its still python web development ๐Ÿ™‚

#

not that I'm saying its ot, but more you're looking for a backend answer with a language that likely has less followers here than a node specific server

violet dock
#

what does this mean?

versed python
#

What do you actually need?

native tide
versed python
#

What do you mean by client side here?

native tide
versed python
#

If so you don't need websockets thats would be an overkill

versed python
#

What type of application are you trying to make?

native tide
# versed python What type of application are you trying to make?

I already have an application.

What it basically does is - check what is result of form once it's submitted, send it to server (node) and it makes a request to api on another site with data from the form, and it should call something on client-side upon the result of request.

#

(The request can't be done on client-side so I need to route it like this)

versed python
#

So why not make an api?

#

Websockets are for async things like chatting etc

native tide
#

Isn't that too hard?

violet dock
native tide
#

I have never made an API so

versed python
#

Websockets are just a pandoras box of difficulties waiting to be opened imo

native tide
versed python
native tide
versed python
native tide
native tide
#

(Screenshot from video, sorry for quality lmao)

#

This could be used to call server-sided actions from JavaScript, but I need the exact opposite

rustic sky
#

Need a bit of help

#

I'm new to DigitalOcean. Cloned my django project to my django droplet and pointed gurnicore to it. This is what I get now

#

Am I missing something? (Probably)

lime frigate
#

In mongodb if i have set the username and password for a database do i need to specify it when using MongoClient(...) ?

native tide
#

Hey, I have question regarding nodejs. I have a web server and I need to call function in javascript file. I assume that it should be done using websockets like socket.io but I have no clue how, would really appreciate a help since only thing that I can find is how to call server sided function from javascript which is completely opposite from what I need.

#

Sending message again since I still haven't found a solution, I heard that it can also be solved by creating an simple API but I don't know how to make the API to call the client-sided function so

versed python
native tide
#

I need to change front-end

versed python
#

What does that even mean?

versed python
proper hinge
#

It sounds like they basically need the client to do something in response to an event on the server.

#

Websockets and SSE are ways to do that.

#

Though it'd be a good idea to elaborate so you can be really sure you need to architect it like this in the first place.

gritty sky
#

heyy

#

so im messing around with some html for an amazon webpage

#

and i get here, and the value is assigned to nothing

#

any idea why?

versed python
sand glen
#

im running my flask app

#

but when i go to 127.0.0.1:3000 it doesn't load

#

it worked fine yesterday

#

and now today it doesnt work for some reason

dusk portal
sand glen
#

i restarted vscode

#

havent restarted PC

dusk portal
#

or run and try to open on the browser

sand glen
#

did

#

im so confused

#

what the hell

#

if i run it in powershell

#

it works

#

if i run it in my WSL bash

#

it doesnt work

#

huhhh

lime frigate
#

How should i get _id of mongodb in django cuz when i type user._id it says variable cannot start with underscore

dusk portal
#

why r django channels used, do any1 have good resouces to learn them and tips to be good at django channels

versed python
versed python
#

Yeah maybe wsl forwards them automatically

#

Haven't used it for a long time, so maybe there were some changes

versed python
versed python
#

Yeah that's true

#

They're very complicated

#

Can't do anything about it though ๐Ÿคทโ€โ™‚๏ธ

wraith cypress
#

anyone with django rest framework experience available?
I'm trying to make a login request that when you give it the information..
1 - the cookies are set automatically with the .set_cookie() function
2 - returns the username and the user id

I have managed to do the first one but the second one is not working with me
it's either that..
1 - the user is not serialized
2 - the keywords are not right
3 - get_queryset for the user inside the cookie view doesn't work
4 - if I try to serialize the data, it attempts to create a user rather than serializing my user

class CookieTokenObtainPairView(TokenObtainPairView):
    def finalize_response(self, request, response, *args, **kwargs):
        #the section that sets the cookies
        user = # Function that get's me the user serialized
        response.data["user"] = user.data if user.is_valid() else user.errors
        return super().finalize_response(request, response, *args, **kwargs)

what should I put in the user= to give me the user serialized, the user serializer class is called UserSerializer

eternal blade
#

started working on a drf and react.js project with very little experience for a code jam, lets see how this goes

wraith cypress
jade lark
wraith cypress
# jade lark Just extend the class and add your own functionality to return the user informat...
class UserSerializer(serializers.HyperlinkedModelSerializer):
    password = serializers.CharField(style={"input type": "password"}, write_only=True)

    class Meta:
        model = User
        fields = (
            "id",
            "url",
            "username",
            "email",
            "password",
            "groups",
            "is_staff",
            "is_active",
            "last_login",
            "date_joined",
        )
        read_only_fields = ("id", "is_staff", "is_active", "last_login", "date_joined")

    def create(self, validated_data):
        if User.objects.filter(email=validated_data["email"]).exists():
            raise Ve("this email has already been used")
        user = User.objects.create(
            username=validated_data["username"], email=validated_data["email"]
        )
        user.set_password(validated_data["password"])
        user.save()
        return user
#

so I have a create function but I don't know how to make some sort of get function. searched in the drf docs didn't find such a thing

wraith cypress
jade lark
#

You may want a separate serializer for obtaining the token. However, a "get" would be done kinda like this:

    def validate(self, attrs):
        attrs = super().validate(attrs)

        attrs["id"] = self.user.id
        attrs["first_name"] = self.user.first_name
        attrs["last_name"] = self.user.last_name
        attrs["email"] = f"{self.user.email}"
        attrs["role"] = "Admin" if self.user.is_superuser else "User"

        return attrs
wraith cypress
#

and how would I call this in the views?

jade lark
#

you create the serializer, provide the data and then call the is_valid() function

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=self.request.data)

        try:
            serializer.is_valid(raise_exception=True)
        except Exception:
            return response.Response(
                "No active account found with the given credentials",
                status=status.HTTP_400_BAD_REQUEST,
            )
#

If you're not using a generic view then you would just call the serializer directly and provide the same values

wraith cypress
#

so like UserSerializer(data=self.request.data) ?

jade lark
#

You got it

wraith cypress
#

neat! thanks

jade lark
#

No problem. Hope this helps

wraith cypress
#

one issue, when I call the serializer it stills attempts to create a user, should I type UserSerailzer.validate(data=self.request.data) ?

jade lark
#

Like I said you'll probably want to create a separate serializer for it. But yeah, you need to provide the arguments.

wraith cypress
#

{
"user": {
"username": [
"A user with that username already exists."
]
}
}

this is what returns, which is an exception in the create function

jade lark
#

I would create a separate serializer there again

wraith cypress
wet hinge
#

No one seems to know in help channels, so I'll hop into questions train if I may.. ๐Ÿฅบ

I'm making Django REST API app for books.
I want to be able to do GET /books/?authors=Tolkien.
Problem is authors is a list:

{
        "id": "1",
        "authors": [ 
            "Tolkien"   # <- I want to filter for this
        ]
    }```

If it was in form of  `"author": "Tolkien"`, then this would work:
```python
author = self.request.query_params.get('author')
queryset = queryset.filter(author=author)```
but it's nested in a list, since it can be many authors.

Do you maybe know how can I access this list?
wraith cypress
#
queryset= yourModel.objects.filter(author=author)
jade lark
#

Just to clarify do you mean it's a list of authors (strings)? Or it's literally an infinite nested list with a matrix of lists?

wet hinge
#

Book dict in JSON has "authors" parameter which is a list of authors. Can have 1 or more name strings inside.

jade lark
#

Alright so use the ORM to your advantage and just provide the list

#

so

#
queryset.filter(author__in=author)
wraith cypress
#

shouldn't he use the model objects?

jade lark
#

Not if he is using a generic view

#

the model would be globally accessible within the class

wet hinge
#

using viewsets.ModelViewSet

wraith cypress
#

nice

wet hinge
knotty garnet
#

You have to use custom filterset I think

jade lark
#

whoops

#

so

#

sorry*

wraith cypress
jade lark
#

so what value are you trying to filter by?

#

What's the author model

wet hinge
#

there is no author model, I only have Book model with "authors" list field (JSONField)

wraith cypress
jade lark
#

Oh. Well that's a bit odd to do. Why wouldn't you create a many to many relationship?

#

Also what DB as that does make a difference with JSONField

wet hinge
#

I'm new and don't know much about it. Would creating authors model fix it easily?
DB is Djangos basic, so SQLite3 I suppose, python 3.9 so JSONField works out of the box

knotty garnet
#

So do you want to filter by multiple autors like this: /books/?authors=Tolkien,King,..

wet hinge
#

I want to filter just by one author for now, but the author in database is in a list, like this:

"authors": ["Tolkien"]```
wraith cypress
#

are you trying to search books with the author query?

jade lark
wraith cypress
#
class books(viewsets.ModelViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializer
    search_fields = ["author"]
    filter_backends = (filters.SearchFilter,)
    permission_classes = [permissions.IsAuthenticated]
wet hinge
#

all I want to do is just a basic query for books written by author X, the problem is, the author of the book inside JSON is in a list

wraith cypress
#

use the search_fields and filter_backends

#

if you just go to /books/ you'll get all

#

if you /books/?author=... it will search

frozen pelican
#

If you dont know what web developement is then let me explain it simple for you:

wraith cypress
#

don't forget to import the filters function from rest_framework

frozen pelican
wraith cypress
wet hinge
#

shows me entire db

#

wait, doesn't work for simple id too, so maybe I implemented it wrong

jade lark
#

hahahha

#

Yeah man

wet hinge
#

it's just about importing filters and adding

search_fields = ["author"]
    filter_backends = (filters.SearchFilter,)```
below serializer_class?
jade lark
#

Take a look at this and implement a model for authors

wraith cypress
#

yea

wet hinge
wraith cypress
#

why did you add id?

wet hinge
#

at first I tried with authors but didn't work, so I added id so I can try querying for not embeeded thing

rain copper
#

i am learning python

wet hinge
#

"id" only doesn't work for looking for certain ids too

rain copper
#

like basic

#

oof

wraith cypress
#

did you import the filters?

#

from rest_framework import filters

wet hinge
#

they're there on the screenshot

#

line 14

wraith cypress
#

oh right lol

#

give it a read you might find why it's not working with you

#

tag me if you found out why it's not working py_guido

wet hinge
#

@wraith cypress hey I know why I didn't make your proposition work:
i was doing /books/?id=xxxxx and it should be /books/?search=xxxxx

#

i used "search" parameter and it works now, but it's not what I need: I need searching with /books/?authors=Tolkien way

#

so SearchFilter doesn't seem to do it for me. I'll try ronek22 suggestion now and try to implement custom filterset, I think I have an idea about how to make it work

#

then, if failure, I'll go for Magic's suggestion about many-to-many relationships. Thanks everyone!

#

I really appreciate your time ๐Ÿ™‚

wraith cypress
#

your welcome, I just want to add that the manytomany relations is generally better practice so I'd suggest you read this https://stackoverflow.com/questions/25386119/whats-the-difference-between-a-onetoone-manytomany-and-a-foreignkey-field-in-d

#

but for books you may not need to make an author model for each and every writer so you can use the normal search in json fields

frozen pelican
#

chattting

mint basin
#

Anyone recommend what's better with full stack development like Ruby, React.js ?

mint basin
wraith cypress
# mint basin Anyone recommend what's better with full stack development like Ruby, React.js ?

ruby and react js are two different things.
you should choose between reactjs and vuejs since they are now the top web frameworks with future
reactjs is the most famous so you will find a lot of libraries and tutorials
vuejs is the better choice since it's easier and has a very easy to understand documentation and cheat sheet, but less famous so less jobs

for backend development it's either nodejs or flask or django imo

#

nodejs for if you want to be full stack javascript

#

flask is for the more simple backends

#

django is fully loaded with libraries and options and is an easy go-to for a python programmer that wants to go into making good backend servers

#

now since you are here I'd suggest you start with flask to understand how backends work then switch to django

raven harbor
#

have created model here but when i run makemigrations i get no migrations to apply wt may be the reason?

wraith cypress
#

and for frontend it deppends, do you want to make better websites with less libraries and less jobs go for vue
if you primarily focus on jobs go for react

native tide
#

how can i add an image to an ImageField after save it (django 3.2)

wraith cypress
wraith cypress
raven harbor
wraith cypress
wraith cypress
native tide
#

but

#
class Media(models.Model):
    name = models.CharField(max_length=255,)
    file = models.FileField(null=True, blank=True)
    preview = models.ImageField(null=True, blank=True)
    category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True)
    plan = models.ForeignKey(Plan, on_delete=models.SET_NULL, null=True)

    def __str__(self):
        return self.name


def update_image(sender, instance, created, *args, **kwargs):
    
    instance.preview = create_preview(instance.file.name, instance.name) #this function return the path of the image
    instance.save()

post_save.connect(update_image, sender=Media)
wraith cypress
native tide
#

i created a function that creates the video preview, and i save it in the same folder with the video

#

i just need to add the path to the Imagefield

#

thats where im stuck

wraith cypress
#

did you apply the routes in the settings?

raven harbor
#

@wraith cypress that worked thanks actually, the model was outside the app i just moved in to check is that how it should work?

analog arch
wraith cypress
native tide
#

u can just delete the migratiosn folder and pycache then re do makemigrations, this would fix too

analog arch
native tide
#

yes he should add models and other stuff on another app, the one above maybe or create another one

wraith cypress
#

so let me explain to you how django works, every app contains it's views, urls, and models

#

but every project has a base file that contains the main urls, settings, wsgi/asgi

#

so making models in your base file is not a good idea, you should create an app for every major function in your database like posts, users, services etc

raven harbor
native tide
#

nOW CAN SOMEONE please help with that ImGEfield grrrr ๐Ÿ˜ข

wraith cypress
#

check the link I sent...

native tide
#

yes

wraith cypress
#

not just the pillow part

native tide
#

i read it

#

till the end

raven harbor
wraith cypress
#

what is the main issue?

tidal garden
#

does anyone know how to use discord oauth2 w django

wraith cypress
wraith cypress
native tide
#

i have an idea

#

ok

native tide
#

no joking

#

okay i discovered i thing

wraith cypress
#

just remember to split your projects to apps and keep the main file only for the main stuff

native tide
#

the code keep looping cause what im giving doesnt corrispond to what he asks

wraith cypress
#

damn

native tide
#

in models

wraith cypress
#

how..

native tide
#

wait

tidal garden
wraith cypress
tidal garden
wraith cypress
#

although depends on your needs you might need to create your own but for as long as I used it I never needed to

tidal garden
#

i just wanna make users login w discord

#

like bot dashboards

wraith cypress
#

yea yea you're good with the built in

tidal garden
#

also, will allauth save my access and refresh token or do i gotta do that myself?

wraith cypress
#

django is the one that takes care of this

tidal garden
#

oh

wraith cypress
#

what allauth does is create a normal user just like any django user but you have a custom user model for allauth specific models

tidal garden
#

ohh

wraith cypress
#

if you are making it in a restful framework you will need .set_cookie to set the cookies but otherwise you are ok

tidal garden
#

no im not

#

okay thanks

wraith cypress
#

welcome

native tide
#

WAIT WAIT WAIT

#

do i have to open it ?

#

the image

#

ok lemme try

native tide
#

shesh

cerulean badge
wet hinge
#

@wraith cypress I made authors filtering work with custom filter, I just made one inheriting from SearchFilter and changed search_param to "authors" instead of "search" ๐Ÿ˜

#

Thanks again! Also to ronek22 and Magic ofc ๐Ÿ™‚

wraith cypress
#

welcome, and thanks you teached me about search_param!

wraith cypress
terse vapor
#
def get(url):
  html = requests.get(url)
  soup = bs4.BeautifulSoup(html.content, "html.parser")
  return soup.find_all(class_='base-search-card__info')

get('https://ca.linkedin.com/jobs/search?keywords=python&location=Canada&geoId=101174742&trk=public_jobs_jobs-search-bar_search-submit&currentJobId=2687992426&position=1&pageNum=0')```
#

hi, does anyone know why this is not returning anything??? ๐Ÿ˜…

wraith cypress
#

what lib is this other than BSoup

#

are you using flask?

terse vapor
#

ummm, no, im trying intergrade this into flask, so its just web scraping im making rn

#

but it returns none for some reasons

wraith cypress
#

I don't have experience with beautiful soup, I prefer selenium

#

though I'm interested on why it's not returning

terse vapor
#

although my app will take in huge amount of data from internet, im not sure can my laptop run that with selenium

#

wait, as long as i dont do any input or any action, it wont overload right?

#

like this app only take a peek of the data and add into a dict

wraith cypress
#

umm pretty much overloading needs to be loaded a lot

terse vapor
#

well, i can set a range for every hour, like take in slowly

#

and store them into a cache

wraith cypress
#

also you are not hosting this app on your laptop to hundreds of users

terse vapor
#

ya ofc

#

im testing on my local host first

wraith cypress
#

so if you host it on a provider it should handle requests well

#

make sure requests are asynchronous

terse vapor
#

i will try use selenium