#web-development

2 messages · Page 89 of 1

vestal hound
#

that seems like an easy issue to debug

topaz widget
#

@opal fulcrum You should probably know a bit of HTML before jumping into Django, but you can learn both at the same time.

vestal hound
#

there are only 2 possibilities:

  1. your token is broken (meaning the source is bad)
  2. the library is buggy (doubt it)
topaz widget
#

@opal fulcrum If you want to build a nice website, you should know HTML, CSS, JS, and backend language and framework like Python/Django.

versed python
#

html is very easy to learn but as the other guy said difficult to master

opal fulcrum
#

@topaz widget ohh so it's a long learning curve i see

topaz widget
#

Yes, most definitely.

versed python
#

so you can easily learn django, and html parallelly

opal fulcrum
#

why did you say backend language and framework like django ... i thought django is backend

#

is there is something different between a framework and backend o.O

versed python
#

@topaz widget ohh so it's a long learning curve i see
@opal fulcrum just wait till you hear about django rest framework then

topaz widget
#

django is a backend framework

#

python is the backend language

opal fulcrum
#

oh

#

i see

#

this is harder than i thought

versed python
#

that backend handles logic for you

topaz widget
#

@versed python lol I haven't been masochistic enough to jump into that yet

vestal hound
#

DRF is pretty nice

#

I'm using it right now

#

I gotta say

#

building a RESTful API is hard

topaz widget
#

I started getting into it but backed off.

versed python
#

frontend is basically used to make pretty looking stuff

vestal hound
#

it's quite a different way of thinking

topaz widget
#

for the time being.

versed python
#

it's quite a different way of thinking
@vestal hound yeh it is

topaz widget
#

it's quite a different way of thinking
@vestal hound Yeah, exactly.

vestal hound
#

and recently I've been restructuring a lot of my API to be RESTful

#

the uniformity is nice

opal fulcrum
#

i know this is a weird question but how long as average can learn all django - HTML - CSS- js

vestal hound
#

but some operations are very difficult to express

versed python
#

and then I just discovered that the market is slowly shifting towards Graphql instead of Restapi

topaz widget
#

@vestal hound I was going to make a single-page application with DRF and Vue, but it was just too much when I tried to jump into it.

vestal hound
#

yeah, that's basically what I'm doing now for my startup

#

planning to launch in a couple of months

versed python
#

@vestal hound I was going to make a single-page application with DRF and Vue, but it was just too much when I tried to jump into it.
@topaz widget this is basically what I am doing rn

topaz widget
#

Can you say what the business model is?

#

understand if you want to keep downlow, though.

vestal hound
#

Can you say what the business model is?
@topaz widget what do you mean?

topaz widget
#

@versed python Then you're a little ahead of me on that front.

vestal hound
#

and then I just discovered that the market is slowly shifting towards Graphql instead of Restapi
@versed python GraphQL shares similarities with real REST

topaz widget
#

What is the business of your startup? (Understand if you don't want to say here)

vestal hound
#

but REST is more or less a buzzword that means "HTTP API" nowadays

#

oh

#

edutech!

versed python
#

i know this is a weird question but how long as average can learn all django - HTML - CSS- js
@opal fulcrum I'd say around 8 months brought me to where I am,since I started as an absolute beginner

opal fulcrum
#

@versed python you learned all that in 8 months wow

vestal hound
#

when you say "business model" I was thinking you meant like marketing strategy and stuff

opal fulcrum
#

i thought that would take me idk 3 years or something

vestal hound
#

3 years is a long time

versed python
#

no 3 years is a lot

vestal hound
#

I haven't even been in Python for 3 years

#

not even 2

versed python
#

same

#

i have been in python for 9 months probs

topaz widget
#

@vestal hound No I meant what the business is about.

opal fulcrum
#

so an average 1 year is very good to learn all that

vestal hound
#

yeah, basically edutech

#

in my part of the world

versed python
#

yeah but just the absolute basics of web development

vestal hound
#

private tutors are very common

#

so like an application to streamline the interaction between students and tutors

versed python
#

@opal fulcrum you will then have to dive into a frontend framework

topaz widget
#

Gotcha

vestal hound
#

incidentally, IMO

topaz widget
#

@versed python What front-end framework are you using?

vestal hound
#

the big frameworks are better

versed python
#

vuejs

opal fulcrum
#

so your 8 month was only for backend ?

vestal hound
#

like I'm using Angular/Django (with DRF) and it feels like if I had done React/Flask instead

topaz widget
#

Yeah, I like Vue best from what I've seen so far.

versed python
#

@opal fulcrum and very little frontend yeah

vestal hound
#

I would have a lot more problems

#

being opinionated really helps

versed python
#

React is way too difficult for my brain to grasp

topaz widget
#

@vestal hound I heard Angular is kind of showing its age. Have you experienced this?

versed python
#

vue has the gentlest learning curve

topaz widget
#

You can definitely ease into Vue

vestal hound
#

@vestal hound I heard Angular is kind of showing its age. Have you experienced this?
@topaz widget I don't have the context or knowledge necessary to give the best answer

versed python
#

especially since it can be used directly in django templates

vestal hound
#

but I personally find it quite easy to use and I have not encountered any problems on the coding side?

topaz widget
#

hm ok

vestal hound
#

however, I must say that I am getting beaten up by the CSS

opal fulcrum
#

thanks guys i will be following this Corey guy tutorials for django .. can you recommend me a way to learn HTML as well ?

vestal hound
#

mostly because everything I've been learning is ad-hoc

#

though that's not exactly an Angular problem

versed python
#

@opal fulcrum Interneting is Hard is a very good website

vestal hound
#

I really like Observables

topaz widget
#

I've used Vue instead of Django tempaltes in places.

versed python
#

I've used Vue instead of Django tempaltes in places.
@topaz widget as of now my frontend and backed are completely separated, I'm not even using vanilla django anymore. switched to drf

topaz widget
#

ah

vestal hound
#

yeah, vanilla Django is the one that is showing its age, I think

topaz widget
#

So you're using Vuex and VueRouter then?

versed python
#

idk, django is pretty good to me

vestal hound
#

like Django without DRF

#

the ORM is really nice

versed python
#

So you're using Vuex and VueRouter then?
@topaz widget i use a framework called nuxt built on top of vue, and they have nuxt router instead of vie router. so yeah that and vuex pretty much

vestal hound
#

I hear it's not as good as SQLAlchemy, but so far it does almost everything I need

#

there are some intermediate SQL things that I can't do in Django

#

but they're not hard necessities right now

topaz widget
#

Why nuxt instead of VueRouter?

versed python
#

yeah i dont even know sql that well, I still didn't find any need to learn it

#

Why nuxt instead of VueRouter?
@topaz widget look at nuxtjs.org this stuff is better explained there

topaz widget
#

Okay. How about authentication? How do you handle that?

versed python
#

nuxt has an inbuilt module

#

but it's a bit difficult to setup

topaz widget
#

Yeah, seemed like that was the hardest part.

versed python
#

i even wrote a tutorial about it for myself and then publish it later

topaz widget
#

I actually thought Vuex would have played a role in maintaining sessions. Is that the case or no? @versed python

versed python
#

partly

#

in all honesty i dont know much about it, except that it just works

topaz widget
#

lol

versed python
#

i just keep trying stuff until something works

#

i have no idea what I am doing lol

topaz widget
#

You might have some problems with that later tbh.

versed python
#

nah this is how I learn, just stumble through until I suddenly understand everything one day

topaz widget
#

I just mean not knowing how something works means you may not be using it quite right.

#

I do the same thing, though. Not judging.

versed python
#

well this strategy has worked out for me, so I'll be sticking with it

#

but I get what you mean though

topaz widget
#

Just a comment, not really a criticism.

versed python
#

yeah i understand

zinc hill
#

Hey its me again, I have 2 models customer and company. each company and customer has a onetoone realationship with User.

I am trying to do a profile pages for both. is there away for me to do @login_required(are u a customer or company)

topaz widget
#

kind of, yes.

zinc hill
#

each model have this is_customer = models.BooleanField(default=True)

topaz widget
#

but login has to do with the user model, not the other model.

zinc hill
#

ok any hint on a work around?

#

or do i have to use like UserAbstract

topaz widget
#

You need to modify the user model if you want to set the user to a company or a customer.

#

and create a field for whether it's a company or a customer.

zinc hill
#

ok gotcha ahhhhh I just got this to work now I have to play with model again

#

Thanks man

topaz widget
#

Yeah, you need to subclass the default user model.

#

no problem

#

There are other ways to do it, but that's probably the best way.

vestal hound
#

Hey its me again, I have 2 models customer and company. each company and customer has a onetoone realationship with User.

I am trying to do a profile pages for both. is there away for me to do @login_required(are u a customer or company)
@zinc hill what do you want to happen if the user is logged in but neither a customer nor a company?

topaz widget
#

lol i was thinking the same thing for admins

zinc hill
#

hmm I dont think they can logged in as that

topaz widget
#

Well, an admin will probably need to log in and be neither.

zinc hill
#

true

#

damn it idk

topaz widget
#

You can still accomplish that with subclassing.

zinc hill
#

maybe i will make something for admin as well

topaz widget
#

You can just set blank=True for the customer/company field, which will let it be blank.

#

then you just need to program the logic for that condition.

vestal hound
#

why is your model structure like that

#

what do you want to do?

topaz widget
#

I assume he(?) wants a different page to display depending on whether the user is a company or a customer.

zinc hill
#

yeah

vestal hound
#

no, I mean

zinc hill
#

and im very very new

vestal hound
#

why a one to one relationship?

#

okay, how about you talk about what you wanna do

#

from a wider perspective?

topaz widget
#

Because he was using it wrong.

zinc hill
#

ok so the project is basically like ubereat

topaz widget
#

?

zinc hill
#

you have company and customer and driver

topaz widget
#

oh

vestal hound
#

so you have different types of users

zinc hill
#

yeah

topaz widget
#

Uber Eats

vestal hound
#

how about an integer field with user type?

topaz widget
#

yeah, but that's subclassing the user, right?

vestal hound
#

nope

#

just a field

#

alternatively

#

Django has groups built in

#

you can use those too

topaz widget
#

hm

vestal hound
#

yeah, but that's subclassing the user, right?
@topaz widget unless you mean the built in class

#

then yes

zinc hill
#

i was messing around with those and it got complicating

#

this is why i was using the 1to1

topaz widget
#

@vestal hound I think we mean the same thing. Subclassing the default user model.

#

or extending, yes.

vestal hound
#

yeah

#

I did that from the start so it didn’t occur to me

#

i was messing around with those and it got complicating
@zinc hill is this your first Python project?

#

it might be good for you to do some research on SQL and how it models relationships between real-world objects

#

you don’t need to know how to write complicated queries, but you should at least understand how one would model common relationships

#

because otherwise you’ll be fighting the ORM and probably losing

topaz widget
#

fighting the ORM and probably losing
XD

zinc hill
#

ok i will into that stuff

#

thank you

vestal hound
#

ok i will into that stuff
@zinc hill btw is English your first language?

zinc hill
#

nope

vestal hound
#

okay just curious

glass sandal
#

Guys isn't there an easy way of sending data to my website with CURL?

#

Like could I create a file like .rest?

#

And use that to post/get/pull/delete the info specified?

#

Or should I use Postman?

proper hinge
#

Yes, you can use curl, though you might find it a bit cumbersome for anything but the simplest of requests

latent vessel
worn rapids
#

yo anyone up?

#

There's a DNS prop issue. I can't fix that, but I'd like to change my name server to one that reaches it

#

actually, jk, I checked DNSmap again and it's fine again, but I can't reach it on some machines still...

#

Would anyone know the reason why?

glass sandal
#

I usually find cURL to be sufficient, but some of my friends use https://insomnia.rest/
@latent vessel Thanks I'll try that out!

Design & Debug APIs like a human, not a robot

latent vessel
#

yep

snow estuary
#

any web developer can help me design my website plz

native tide
#

@snow estuary yep dm me

#

Hii anyone can u test my site made php change and added advertisements

coral raven
#

The images are far too big

#

wrap text around them and make them small

versed python
#
for index, _ in enumerate(range(100), 1):
            with tempfile.NamedTemporaryFile('rb', suffix='.jpg') as file:
                PostImage.objects.create(
                    post=random.choice(posts_list),
                    image=ImageFile(file) #  from django.core.files.images import ImageFile
                )
                print('Image file created')

This is a django management command snippet that I am using to generate some data for my database
everything works as expected- (empty) image is being created, and being uploaded too.
But since tempfile.NamedTemporaryFile() opens a file /tmp/temporaryname.jpg, the images are uploaded to my webserver with the name tmp/temporaryname.jpg and hence an extra useless directory called tmp is being created in my MEDIA_ROOT
How can I prevent this?

# what I want
media/
   - images/
       - temporaryname.jpg

# what is being created
media/
   - images/
        - tmp/
           -  temporaryname.jpg
jagged lark
#

!d tempfile.NamedTemporaryFile

lavish prismBOT
#
tempfile.NamedTemporaryFile(mode='w+b', buffering=-1, encoding=None, newline=None, suffix=None, prefix=None, dir=None, delete=True, *, errors=None)```
This function operates exactly as [`TemporaryFile()`](#tempfile.TemporaryFile "tempfile.TemporaryFile") does, except that the file is guaranteed to have a visible name in the file system (on Unix, the directory entry is not unlinked). That name can be retrieved from the `name` attribute of the returned file-like object. Whether the name can be used to open the file a second time, while the named temporary file is still open, varies across platforms (it can be so used on Unix; it cannot on Windows NT or later). If *delete* is true (the default), the file is deleted as soon as it is closed. The returned object is always a file-like object whose `file` attribute is the underlying true file object. This file-like object can be used in a [`with`](../reference/compound_stmts.html#with) statement, just like a normal file.

Raises an [auditing event](sys.html#auditing) `tempfile.mkstemp` with argument `fullpath`.

Changed in version 3.8: Added *errors* parameter.
jagged lark
#

What if you give an empty string to dir?

versed python
#
# what I want
media/
   - images/
       - temporaryname.jpg

# what is being created
media/
   - images/
        - app/     <----- instead of tmp i get app
           -  temporaryname.jpg
#

@jagged lark

jagged lark
#

I think that’s how django save files, but i might be wrong

pulsar pulsar
#

I can access my application via flask run but not via uwsgi

#
[uwsgi]
wsgi-file = wsgi.py
#wsgi-file = run.py
callable = app
strict = true
socket = :5000
http = :8090
stats = :9191
master = true
processes = 4
threads = 2
chmod-socket = 660
vacuum = true
die-on-term = true
enable-threads = true
need-app = true
reload-mercy = 5
worker-reload-mercy = 5
#
> uwsgi ./wsgi.ini
[uWSGI] getting INI configuration from ./wsgi.ini
*** Starting uWSGI 2.0.18 (64bit) on [Tue Sep 15 17:36:10 2020] ***
compiled with version: 10.1.0 on 14 September 2020 07:20:01
os: Linux-5.4.52-1-MANJARO #1 SMP PREEMPT Thu Jul 16 16:07:11 UTC 2020
nodename: foo-manjaro
machine: x86_64
clock source: unix
pcre jit disabled
detected number of CPU cores: 8
current working directory: /home/foo/ticket_dashboard
detected binary path: /home/foo/.local/share/virtualenvs/ticket_dashboard-oWsjh6kM/bin/uwsgi
your processes number limit is 63584
your memory page size is 4096 bytes
detected max file descriptor number: 1024
lock engine: pthread robust mutexes
thunder lock: disabled (you can enable it with --thunder-lock)
*** RRDtool library available at 0x5615881bb590 ***
uwsgi socket 0 bound to TCP address :5000 fd 3
Python version: 3.8.3 (default, May 17 2020, 18:15:42)  [GCC 10.1.0]
Python main interpreter initialized at 0x5615881d0550
python threads support enabled
your server socket listen backlog is limited to 100 connections
your mercy for graceful operations on workers is 5 seconds
mapped 416880 bytes (407 KB) for 8 cores
WSGI app 0 (mountpoint='') ready in 0 seconds on interpreter 0x5615881d0550 pid: 129218 (default app)
*** uWSGI is running in multiple interpreter mode ***
spawned uWSGI master process (pid: 129218)
spawned uWSGI worker 1 (pid: 129222, cores: 2)
spawned uWSGI worker 2 (pid: 129223, cores: 2)
spawned uWSGI worker 3 (pid: 129224, cores: 2)
spawned uWSGI worker 4 (pid: 129225, cores: 2)
*** Stats server enabled on :9191 fd: 15 ***
past cipher
#
class User(db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(255), nullable=False)
    email = db.Column(db.String(255), nullable=False)
    password = db.Column(db.String(255), nullable=False)

class Profile(db.Model):
    __tablename__ = 'profiles'
    id = db.Column(db.Integer, primary_key=True)
    profile_description = db.Column(db.String(500), nullable=True)
    feedback_score = db.Column(db.String(50), nullable=True)

class Image(db.Model):
    __tablename__ = 'images'
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.String(100), nullable=False)
    product_id = db.Column(db.String(200), nullable=True)
    profile_img = db.Column(db.String(200), nullable=True)
    product_img_original_name = db.Column(db.String(100), nullable=False)
    product_img = db.Column(db.String(200), nullable=True)

Since the user can create a product, I thought it was best to store all the images in one table, including the profile image. Or should I move profile image into the Profile table? What do you think?

of any other way I should setup these tables?

lethal orbit
#

Ufff

#

Maybe make a an Abstract Image model, and derive ProfilePicture, ProductImage, etc. from it?

past cipher
#

never heard of abstract model, I will look it up

versed python
#

I think that’s how django save files, but i might be wrong
@jagged lark so there's nothing I can do?

jagged lark
#

I’m not sure, but I think

past cipher
#

@lethal orbit can you give a quick explanation as to what Abstract is? I don't seem to understand it

lethal orbit
#

@past cipher first two questions is why you use __tablename__ and why you add an id .... Using the defaults should be fine in 99% of cases (as Django does give pk and id properties by default).

#

An Abstract model is essentially a mixin that lets you reuse code.

past cipher
#

because I'm using Flask

lethal orbit
#

OH!

past cipher
#

and class name shouldn't be pural

#

where as table name should

#

so thats why i use tablename

lethal orbit
#

never mind me then xD

#

This is SQLAlchemy?

past cipher
#

yep

#

I just don't understand Abstract, I can't find a solid tutorial/walkthrough online

lethal orbit
#

I havent worked with SQLAlchemy.... but normally, you would declare an Image mixin, with information about the file itself.

past cipher
#

but why would I use abstract, when I am going to create a table called Images anyway

lethal orbit
#

Then derive models from that.

#
class Image(db.Model):
    __tablename__ = 'images'
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.String(100), nullable=False)
    product_id = db.Column(db.String(200), nullable=True)
    profile_img = db.Column(db.String(200), nullable=True)
    product_img_original_name = db.Column(db.String(100), nullable=False)
    product_img = db.Column(db.String(200), nullable=True)
#

Single-responsibility principle.

#

Why do you have a profile_img and product_img together?

#

How is a product tied to a user?

past cipher
#

so i can query profile_img or product_img

#

its tied to a user by their user_id

lethal orbit
#
class Image(db.Model):
    img = db.Column(db.String(200), nullable=False)

class ProfileImage(Image):
    # inherits the `img` field from the Image class
    user_id = db.Column(db.String(100), nullable=False)

class ProductImage(Image):
    # also inheerits `img`
    product_id = db.Column(db.String(200), False)
#

Then you can add as many product images as you want... and your models are independent.

#

Not sure how you would make an abstract model in SQLAlchemy though, as I don't work with it.

#

But having the product and profile images in the same model is a code smell.

past cipher
#

but from your code above, isn't that just creating multiple tables

#

I'm new to SQL. I thought having all images in one table was best

lethal orbit
#

Nah...

#

It just adds extra complexity, tbh.

#

You definitely shouldn't mix them in the same row.

#

You could have a img_type column in your table, so you can have an image row that is a profile_image, and another that is a product_image...

#

But mixins are the cleanest way.

#

Also, more tables means smaller tables, so if you need to query all profile pictures, you can do it more efficiently.

#

select * from profile_images; <-- selects from a smaller set

#

select * from images where profile_img != null; <-- selects a larger set, and has to do an extra filtering operation.

vestal hound
#

I'm new to SQL. I thought having all images in one table was best
@past cipher if you definitely have one image of each kind per user, then yes.

#

but I'm guessing that each user definitely has one profile image?

#

if so, that should probably be on the main user model.

#

however, each product has its own image, and multiple products can belong to one user, right?

#

that's called a one-to-many relationship

#

and suggests that products should be in their own table

#

one row per product

#

and they can be linked back to their owning user with a user_id column

lethal orbit
#

You should also allow multiple images per product, IMO

solar ridge
#

How could I pass a value from the class based create view (overloaded) __init__ to the form __init__ ?

#

Right now my classbased create view is creating the form with form_class = MyCustomForm

vestal hound
#

You should also allow multiple images per product, IMO
@lethal orbit that would depend on their business logic

#

but yes, that's definitely a possibility

#

and would require a third table

pulsar pulsar
#

I'm setting up flask uwsgi and nginx and I'm getting an error ValueError: handshake not done yet

#

Anyone know how to resolve this?

dawn elm
#

Is there any difference between django-admin startapp and python manage.py startapp?

versed python
#

no there isn't

#

they call the same functions under the hood

burnt night
#

Hey hey

#

trying to use bs4... any idea what is causing this error?

raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 403: Forbidden```

this is my code
```py
from bs4 import BeautifulSoup
import urllib.parse, urllib.request, urllib.error
import ssl

ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

print("Give me link...")
link = input(": ")
handle = urllib.request.urlopen(link, context=ctx).read()

soup = BeautifulSoup(handle, "html.parser")

tags = soup("a")

alltags = [tag for tag in tags]
alltags = "\n".join(alltags[:25])

with open("taglist.txt", "w") as f:
    f.write(alltags)
quick cargo
#

@burnt night you're not allowed to access whatever youre accessing

burnt night
#

oh damn...

lethal orbit
#

HTTP Error 403: Forbidden You're not allowed to open the URL. Maybe you need credentials, maybe you need to add a user-agent header, etc.

#

Hard to say why without knowing the URL.

swift sky
#

can someone explain: if usually people store static content on a server, how does one program their website around that

#

obviously I am not developing/writing code on the cloud?

indigo moth
#

Hi! I want to use bulma in my Django application. But I don't know how. For example if I used bootstrap all I need to do was assign a variable in settings for crispy forms and I'm done. But I don't know how to do it with bulma. There are packages out there but there are either poorly documented or idk if I should use that one. Can someone help?

#

Pls ping back when ur answering

jagged lark
#

Weeeeelllll

#

This server has a django-bulma package @indigo moth

indigo moth
#

Yes I know

jagged lark
indigo moth
#

I checked that but i don't think that supports crispy forms?

versed python
#

crispy forms doesn't support bulma

#

and this does not support crispy forms

indigo moth
#

😔

versed python
#

they are two independent packages

indigo moth
#

Then what should I use for my forms?

jagged lark
indigo moth
#

Oh I haven't seen that

jagged lark
#

It is archived though lemon_thinking

indigo moth
#

This project is an early work in progress. You should not use this package yet, as it is poorly documented and is missing many important features. We'll remove this header when it's ready to use.
😔

swift sky
#

soo

#

static content

#

and deploying to server

#

does one need to code on the server to make this work? what is best practices

indigo moth
#

Can you elaborate on your question

swift sky
#

so most people have told me that serving content like pdfs is best done by allocating space on your server

#

and placing the content there

#

and in your code, pointing to that location which contains the content

#

what is confusing me, is how one is supposed to build out their website

#

and simultaneously have it point to the media content

#

since they are developing locally in their IDE and only then pushing it to cloud after.

#

like I need to build out some pages that contain PDFs

burnt night
#

how can i get all html from a page with bs4?

swift sky
#

should be in the docs, it's definitely a function of bs4

#

because you can do that with curl requests

burnt night
#

I'm reading thru the docs right now...

#

i see that the soup object itself has everything, but i also get the css and the script

swift sky
#

im not certain sir, good luck

burnt night
#
  return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u202a' in position 35877: character maps to <undefined>```
#

how can I fix this?

#

i tried .read().decode()
and just regular .read()

#
handle = urllib.request.urlopen(link, context=ctx).read().decode()

soup = BeautifulSoup(handle, "html.parser")

with open("something.txt", "w") as f:
    f.write(f"{handle}")

print("done")```
versed python
#

@burnt night This can happen sometimes if youre writing a website which does not have utf-8 characters.

#

maybe the site youre using is in a different language? or uses emojis?

burnt night
#

INteresting...

#

it was working b4 :(

#

I an print it... but not write it to a file

versed python
#

I don't have any experience working with bs4, but that was the first thing that cam to mind

#

why don't you try and see with some other website? maybe the problem is just with this one?

burnt night
#

i did

#

i tried it with youtube and google sites, and i got the same error...

#

but i wanted it for a specifc site so that is an L

versed python
#

Well if it didn't work for youtube etc, there's something you must be doing wrong

#

try and see where it is wrong

#

maybe follow the tutorial you followed again?

last sable
#

So I am getting data from an api and trying to export it to excel, but my to_excel function only uses the result of my most recent get_page function...
I might have to hit someone up on fiverr for help on this, but I thought that I would try here out first. I have problem with my function. I want to be able to use the result of my first fuction in my new function multiple times, but I keep overwriting the file I want to create. Does this sound like a difficult fix?

#
import json
import pandas as pd
from pandas.io.json import json_normalize

def get_page(url):
    global response
    payload = {}
    headers = {
  'Authorization': 'Bearer #####
}
    response = requests.request("GET", url, headers=headers, data = payload)
    return response.text.encode('utf8')

(get_page("https://us.api.knowbe4.com/v1/groups"))
(get_page("https://us.api.knowbe4.com/v1/users"))
    

def to_excel(responseName):
    responseName = response.text.encode('utf8')
    dataName = json.loads(responseName)
    data2 = json_normalize(dataName)
    data2.to_csv('Project.csv', mode='a')
    return responseName
to_excel(response.text.encode('utf8'))```
maiden kraken
#

Hi, if your function only returns last page maybe you need to implement for loop and iterate? and save each step?

last sable
#

@maiden kraken Is this comment directed to my code?

maiden kraken
#

@last sable yes, but I am beginner in python so you dont have to listen to me 🙂

versed python
#

(hint: listen to @maiden kraken)

last sable
#

It sounds like you know more than me!

maiden kraken
#

of course you have to worry about overwriting your file, ideally you want to 'append' not save over

#

some time ago I was using openpyxl to mess with excel, maybe now there is a better option

last sable
#

So are you saying to put the function in a for loop?

tranquil meteor
#

So im trying to make my bot add a reaction to the message the bot sends but i can only ever get it to send emojis by themselves, not as reactions
@true python umm its web development channel

maiden kraken
#

well... I would first debug this, try what your function returns. If it returns specific page (last) and you have multiple pages then you need to iterate through it

last sable
#

It returns the most recent API call (i.e. get_data())

maiden kraken
#

something is strange here, you write you want to use your first function inside another, but you are not using it at all?

last sable
#

I am using the response object created by the most recent function

maiden kraken
#

you maybe meant this responseName = getpage(url)?

#

sorry I think that's beyond my skills right now

strange briar
#

hey guys, which framework would you advise to build a graphql backend ?

#

I thought of django but i saw that fastapi also support it

lethal orbit
#

Django with ariadne work great, @strange briar

#

Can't speak for fastapi, as I never tried it.

swift sky
#

im tyring to follow this

#

however

#

im trying to serve a pdf

#

and i place it in static/pdf

#

i tried to do a

#

{{ url_for('static', filename='pdf/filename.pdf') }} inside of the html

#

ive tried every combination I can think of

#

and it's either trying to print out the filepath

#

or just not serving anything

native tide
#

Does anyone know how to use ionicons in a flask application?

#

I have a template that uses ionicons but i dont know how to install them properly. I added the ionicons.js and the ionicons.css but it does not work like it should

#

any suggestions?

#

it comes with flask, you just need to import it

light flame
#

how to use the gmail's api plz ?

versed python
#

how to use the gmail's api plz ?
@light flame are you using django?

light flame
#

django ?

#

no

versed python
#

Sorry can't help you then

light flame
#

and what is django ?

maiden kraken
#

The web framework for perfectionists with deadlines.👀

light flame
#

O.K

native tide
#

Flask is the easiest to start with

versed python
#

I think they just need to commuinicate with gmail api, they aren't looking for any integration into a webapp

maiden kraken
#

@light flame I cannot explain it better, you have docs on linked page. You need to authenticate to gmail and also you have to give access to less secure apps

light flame
#

ok else what is the import early

#

and im french

high jacinth
#

Does webscraping count as webdev or should I take my question elsewhere? Bs4

lavish prismBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

snow estuary
#

any web dev can help me design my html pages plz

twilit dagger
#

Ok I'm getting this error when I'm trying to send an email through Django -

SMTPAuthenticationError at /contact/
(530, b'Invalid username or password')
#

settings.py

EMAIL_HOST = 'smtp-relay.sendinblue.com'
EMAIL_HOST_USER = '<tejasm01@gmail.com>'
EMAIL_HOST_PASSWORD = 'xxxxxxxxxxxxxxx'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
#

Can anyone help

stone hedge
#

Hey, I'm having some issues with pytest & flask-login
When I run my test, I can login my user, but after I make a request with the test client (client.get('/someurl')), current_user reverts back to the AnonymousUser within the same context manager 🤔
Snipped test in here: https://pastebin.com/Q8tQWVcF

#

I've seen examples that use the test client to post a form in order to login, but I dont think I can do that; my site authenticates against Azure AD with msal; hence forcing a login with flask_login.login_user in the test. I did have an if statement in my authentication route to check the current app config for 'testing' flag which just passed through the auth without hitting msal, but that seems like pretty poor security practice to me

burnt night
#

Do i NEED a backend to handle POST/GET requests from forms?

valid sandal
#

thats the purpose of them

burnt night
#

🤔 :/

#

Would i need one for the google sign in thing?

vestal hound
#

Do i NEED a backend to handle POST/GET requests from forms?
@burnt night well, if you didn't have a backend, where would the requests go?

burnt night
#

i just meant if they had to be attached like with flask etc

#

or if they could be separate

vestal hound
#

what do you mean "attached"?

#

okay I'm not sure if this is the best place to ask since it's more deployment than development, but...anyone ever got a 502 from a deployed Django app on GCP, but logs are empty?

#

not sure if something is wrong with my gcloud because logs are literally showing nothing

native tide
#

hey guys

#

how would i export an array that I already created in javascript

#

I tried this

#

and got this error

#

I have to go soon

#

so if you have a solution and I'm not here, just ping me and I will take a look tomorrow

versed python
#

@native tide try export var custom_blacklist; also, how did you take that cool screenshot? is that a theme?

burnt night
#

what do you mean "attached"?
@vestal hound i mean like... yk how you'd normally have them in the same folder, and they'll be like in the static folder and use that with flask etc?

#

i was wondering if it can be done without that...

#

cause i want to send an email right, was just wondering if i needed to have it set up

zealous cloud
#

Does anyone know if there is a method to paginate items that aren't being stored in a database or are part of a model? Im using this route below to make an api call and then passing the response object directly to my jinja template and creating bootstrap cards for each item in the response object. This data updates daily so I dont want to save it in a db. I have about 100 cards on the page, so it'd be nice to be able to paginate this info into 20 per page. Everything I've seen however seems to show pagination with queried items. My flask route is below

@app.route('/search/member/<member_id>')
def get_member_info(member_id):
    """Retrieve individual government official data on link click"""
    
res_object = []
    offset = 0
    while offset <= 60:
        res = requests.get(
            f"{MEMBER_VOTE_POSITION_API}{member_id}/votes.json?offset={offset}", headers={'X-API-Key': key})
        data = res.json()
        res_object.append(data)
        offset += 20

    members_data = res_object

    # page = request.args.get(get_page_parameter(), type=int, default=1)
    # page = request.args.get('page', 0, type=int)
    # page_size = 20
    return render_template('search/officials_voting.html',
                           members_data=members_data,
                           member_id=member_id     
                           )
#

And my jinja template where I'm creating the cards for each item.

{% for record in members_data %}
    
    {% for item in record['results'][0]['votes'] %}
    
      <div class="row justify-content-center mt-3">
        <div class="card bg-white w-75 my-4">
          <div class="card-header font-weight-bold">         
            <a href="/search/bill/{{item['bill']['bill_id']}}">{{item['bill']['bill_id']}}</a>
          </div>
          <div class="card-body bg-info">
            <h5 class="card-title">Bill info - <span class="text-primary">{{item['bill']['title']}}</span></h5>
            <p class="card-text"><strong>Vote description: </strong>{{item['description']}}</p>
            <p class="card-text"><strong>Date of vote: </strong>{{item['date']}}</p>
            <p class="card-text"><strong>Vote result: </strong>{{item['result']}}</p>
            <p class="card-text"><strong>Latest action: </strong>{{item['bill']['latest_action']}}</p>
            <p class="card-text"><strong>Voting position: </strong><strong><u>{{item['position']}}</u></strong></p>
          </div>
        </div>
      </div>
    {% endfor %}
  {% endfor %}
solemn igloo
halcyon meteor
#

Hi I wanted to scrape some Google maps for testing purpose, unlike static pages I believe google map has a wrapper of some sort. Because if I manually type the whole link with page=2 on the address bar it's going to the next page, however when my scrapper pases the link it just reads the same page again. I am using beautiful soup only for this. Please ping me if you know the solution

versed python
#

you are doing nothing wrong @solemn igloo . Did you start the development server? If yes, can you tell us what the output in the terminal was?

solemn igloo
versed python
#

@solemn igloo show me your polls/urls.py

solemn igloo
#

@versed python

marsh canyon
#

Hi guys, im making the django tutorial part 3 using psql as my database, i just wrote that view, and http://localhost:8000/polls/ shows just a 404, the console show no error, what am i missing here?
@solemn igloo why did you name ur function index?

#

name the function get which translates to GET request view

#

and

#

as_view is a method

#

it missed the ()

versed python
#

^

solemn igloo
#

@marsh canyon so, just rename the function and ad the "()" to the as_view function.
like that?

marsh canyon
#

aand

#

ur get method is a method inside the calss

#

class*

#

so u need the self param too in the starting

#

or you can convert ur method into a staticmethod by adding @staticmethod decorator

#

@solemn igloo

#

also, using render() will be cleaner imo instead of HttpResponse

versed python
#

I suppose since they are following the official docs, the render method hasn't been introduced uptil tutorial 3

#

so they will learn it soon enough

marsh canyon
#

oh okay 👍

opaque sail
#

Quick question

#
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="post" method="POST">
        {° csrf_token %}
        {{ form }}
        <button type="submit">Submit</button>
    </form>
</body>
</html>
#

this gives me error when I try to submit

#
"GET /post?name=
#

not found /post

#

Why is it still doing get when I declared it as post

strange briar
#

hey guys can anyone tell me what are his thoughts about fastapi ?

vestal hound
#

whose is "his"?

zealous moth
#

@opaque sail remove post from action

opaque sail
#

I did

#

now it is only in method still does not work

#

[16/Sep/2020 09:09:01] "GET /post?name=Test&email=a%40b.c&category=question&subject=&body=hey HTTP/1.1" 404 2180
Not Found: /post

#

This is what I get

zealous moth
#

{% in csrf

opaque sail
#

changed that as well

#

still does not work

#
<body>
    <form method='post'>
        {% csrf_token %}
        {{ form }}
        <button type="submit">Submit</button>
    </form>
#

This is my contact from views

#
def contact(request):

    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():

            name = form.cleaned_data['name']
            email = form.cleaned_data['email']

            print(name, email)

    form = ContactForm()
    return render(request, 'form.html', {'form': form})
zealous moth
vestal hound
#

by default forms are POST

#

you shouldn't need anything more than <form>

opaque sail
#
class ContactForm(forms.Form):
    name = forms.CharField(max_length=40)
    email = forms.EmailField(label="E-Mail")
    category = forms.ChoiceField(choices=[('question', 'Question'), ('other', 'Other')])
    subject = forms.CharField(required=False, max_length=30)
    body = forms.CharField(widget=forms.Textarea)
#

ok imma gonna try holup

zealous moth
#

but it doesn't affect i think

vestal hound
#

yeah, it shouldn't make a difference

opaque sail
#

[16/Sep/2020 09:16:44] "GET /?csrfmiddlewaretoken=n7V4B7sHoQOSCJtjeaCSK6BuUIyWgxxvHPOSbVc9pKbEkR7BbZs6YkrDuW7nvgS4&name=dasd&email=a%40b.c&category=question&subject=asd&body=asd HTTP/1.1" 200 1058

vestal hound
#

just saying

zealous moth
#

are you getting csrf error in web page

opaque sail
#

nah

#

it just refreshes the page and in terminal it gives me the last error above

zealous moth
#

what is showing in web page after form submission

opaque sail
#

empty form

#

now it does not give me error but it does not print name and email in form

#

it just happened like magic

#

wtf

#

this is supposed to be some easy stuff im completely lost in this form thingy jeezus

zealous moth
#

name and email will print in terminal

opaque sail
#

will not 🙂

#

[16/Sep/2020 09:26:32] "POST / HTTP/1.1" 200 1072
[16/Sep/2020 09:26:49] "POST / HTTP/1.1" 200 1072

#

at least it is a post method

zealous moth
#

u did write print inside views

opaque sail
#

yes

zealous moth
#

Ok

opaque sail
#

This is simple stuff why is not working is beyond me 😄

zealous moth
#

may be the changes are not reflected instantly in the web browser it happens to me sometimes

opaque sail
#

i restarted the server and still no print in terminal

#

it is a post method tho, so I kinda made it work somehow

zealous moth
#

Hey guys how can we create a form to input a directory and store it in project media directory.?

native tide
#

anyone that uses django?

jagged lark
#

A lot of us do, you can just ask your question right away, no need to ask to ask

native tide
#

i ask because nobody answers my questions 🙂 . So, i have this urls.py that contains multple apps with different views. I m trying to call those views like that:
path('', cos.views.home, name="HOME")

#

but I get an Attribute error that my module has no views.

zealous moth
#

create a view

native tide
#

what

#

in that 'cos' module

zealous moth
#

create a function inside it

native tide
#

i don t understand :))

#
# this is the home function
def home(req):
    products = Product.objects.all()
    return render(req, 'cos/home.html', {'products': products})
#

what function are you talking about

zealous moth
#

did u import views in urls

native tide
#

yes

#

or not

#

i did it like that

#
import cos
import noutati
#

because i have multiple apps

#

if i do

#
from cos import views
#

it will not see the views from the another app

zealous moth
#

the urls.py is main urls or app urls

native tide
#

the main

#

one

zealous moth
#

try creating urls for app and call from there

native tide
#

how do i do that

zealous moth
native tide
#

hmm i guess i will use one app to do all the things

#

i only need one path

#

from that another app

#

create urls.py inside app
@zealous moth sure bud but how do i import it in the main urls

zealous moth
#

like the admin urls is imported

#

url(r'^',include('appname.urls',namespace='given_namespace'))

#

you can search in google

native tide
#
import noutati
in urlpatterns:
path('noutati/', noutati.urls , name = "vezi_noutati")
#

like that?

#

okay

zealous moth
#

yes

native tide
#

should i add the static thing from the main urls?

zealous moth
#

dont think so

#

this is app urls

#

it is old project but works

native tide
#

what does app_name do

#

i never used that url('r') thing

zealous moth
#

it like namespace

#

this is main url

#

Hope this will help you👍

native tide
#

not working

#

path('noutati/', noutati.urls , name = "vezi_noutati"),
AttributeError: module 'noutati' has no attribute 'urls'

zealous moth
#

it is using regex expression but for path() i dont know how to call urls

native tide
#

and my urls.py:

from django.urls import path
from . import views
urlpatterns = [
    path('', views.vezinoutati, name="Noutati")
]
#

django is really a pain in the ass

zealous moth
#

check this

native tide
#

i don t think that s the problem

#

i mean it doesn t see my urls.py file

zealous moth
#

use include() func

native tide
#

ok what the fuck happened

#
Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    main()
  File "manage.py", line 13, in main
    raise ImportError(
ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?
#

oh i m an idiot

zealous moth
#

path('noutati/', include('appname.urls'))

native tide
#

forgot to activate virtualenv

zealous moth
#

nice

native tide
#

include not defined

zealous moth
#

you forgot the first step

#

import include

#

show above pic

native tide
#

it works now

#

thankies

zealous moth
#

wlcm

#

just search in google its all there.👍👍👍

native tide
#

now it doesn t see any style apparently

#

yeah my fault

iron cliff
#

How can I get resources loaded in the web-page with selenium (F12->Network->loaded resources) ?

worn cove
#

Hello guys
Anyone good at designing website?
Need some guidance
it's URGENT!

native tide
#

@native tide try export var custom_blacklist; also, how did you take that cool screenshot? is that a theme?
@versed python I will try it when I am done with school. That is the atom editor's theme

hearty ingot
#

Hello guys

#

is there a dedicated channel for Django?

surreal vigil
#

this is the channel @hearty ingot

#

read the channel info on top

hearty ingot
#

This one is mixed for every Python web library/framework, that's why I asked if there's a dedicated Django channel :/

surreal vigil
#

ohh ok ok, there isn't, this is the only one...

versed python
#

@hearty ingot there's a django server though

#

you can find it on r/django

marsh canyon
hearty ingot
#

cool thanks

twilit dagger
#

My Django messages aren't showing up

#
messages.success(request, 'Email Sent')
            return redirect('contact')
marsh canyon
#

are you including them in ur templates?

twilit dagger
marsh canyon
#

html

twilit dagger
#

I haven't included anything in my html templates relating to message

native tide
#

hi, how can i use redirect(url_for('')) on a template on flask?

#

i mean a html doc

hallow jacinth
#

anyone good with using the bootstrap framework mind helping a pleb out a bit?

twilit dagger
#

I know some bootstrap

hallow jacinth
#

I am trying to format my page to have a navbar at the top, and a 3 column page underneath that. The left column is going to be kind of another navbar with some hyper links

#

I can't seem to get a column working on the left side

#

it keeps trying to stack ontop of my middle column

twilit dagger
#

flexbox

#

Put all 3 columns in a flexbox should work I think

hallow jacinth
#

okay I will try

twilit dagger
#

@marsh canyon Uh my message appears at the top of the navbar and with no colour

marsh canyon
#

that depends on how u style it, lol

#

place it whereever u want

#

just like a html thing

twilit dagger
#

Isn't it already styled

marsh canyon
#

na

hallow jacinth
#

hmm, that didn't work. I also am using .nav .flex-column to make it vertical, but it isn't doing that either 🤔

twilit dagger
#

@hallow jacinth Do display:flex and flex-direction:column on the parent element only

#

Also if you want them side by side you need to do flex-direction: row

dapper heath
#

@hallow jacinth put it in a separate div and it will be column wise, nothing else

#

display: block

twilit dagger
#

Yeah he is right

#

For a vertical navbar

wanton ridge
#

how ccan i get the sentence below the picture, i tried with flexbox but doesnt seems to work

#

its for mobile view

broken briar
#

Im currently using the following filter with DRF:
But when i filter it will be always using an AND condition how can i change this schema to support OR conditons?

class SystemFilter(djfilters.FilterSet):
    id_v = djfilters.filters.Filter(field_name='id', lookup_expr='icontains')
    system= djfilters.filters.Filter(field_name='system', lookup_expr='icontains')
    deputy = djfilters.filters.Filter(field_name='deputy, lookup_expr='icontains')
    deputy_2 = djfilters.filters.Filter(field_name='deputy_2', lookup_expr='icontains')

   class Meta:
        model = System
        fields = ['id_v', 'system', 'deputy', 'deputy_2']

class SystemAPIViewSet(viewsets.ModelViewSet):
    queryset = System.objects.all()
    permission_classes = [IsAdminOrReadOnly]
    serializer_class = SystemSerializer
    pagination_class = DynamicPageSize
    filter_backends = [django_filters.rest_framework.DjangoFilterBackend, filters.OrderingFilter]
    filterset_class = SystemFilte
twilit dagger
#

@wanton ridge Did you try flex-direction:column?

wanton ridge
#

@twilit dagger yes didnt work

twilit dagger
#

Maybe you're doing it on the wrong element

#

It should be the parent element of both pic and text

wanton ridge
#

yes i did it too but no

twilit dagger
#

sometimes it helps if you put flex:none on the picture and text

wanton ridge
twilit dagger
#

but display:flex on the parent

wanton ridge
#

here is my code

twilit dagger
#

put it on picture1

wanton ridge
#

ah ty mate@twilit dagger

hallow jacinth
#

when creating a settings page, would it be best to make a new model for user settings or include n user model?

#

I am thinking new model

#

so that user model doesn't get too inflated

twilit dagger
#

what do you mean user settings?

#

But yes typically there is a new model Profile made along with User

#

And the Profile model handles pfp and bios and stuff

hallow jacinth
#

ok ill do that. right now my user model holds the bio and some things similar

native tide
#

who can help me with flask?

lethal orbit
tacit comet
#

Hey guys i have a problem ☹ as you see my output photo i can create model but i cant use auth.user’s values. I want to create external values but for example i want to use into auth.user name , last_name, last_login values..

class student(models.Model):
    authority = models.ForeignKey(Group,on_delete=models.CASCADE,verbose_name="Yetki Tipi")
    avatar = models.ImageField(upload_to = 'media/profile_image', blank=True,verbose_name="Fotoğraf")
    name = models.CharField(default='',max_length = 50,verbose_name = "Adı")
    surname = models.CharField(default='',max_length = 50,verbose_name = "Soyadı")
    birthday = models.DateField(blank=True, null=True,verbose_name = "Doğum Tarihi")
    email = models.EmailField(default='',verbose_name = "E-Posta")
    phone = models.CharField(default=0,max_length=11,verbose_name = "Telefon Numarası")
    parent_phone = models.CharField(default=0,max_length=11,verbose_name = "Veli Telefon Numarası")
    gender_choice = (
        ('Erkek', 'Erkek'),
        ('Kadın', 'Kadın'),)
    gender = models.CharField(max_length = 30,blank=True, null=True,choices = gender_choice,verbose_name = "Cinsiyet")
    created_date = models.DateTimeField(auto_now_add=True,verbose_name="Kayıt Tarihi")

    def __str__(self):
        return self.name ```
versed python
#

You haven't added a models.ForeignKey to User, and also don't store the users last_name etc in this Student model. That's why youy can't access these properties.

#

@tacit comet

#

Two ways to solve this:

#
  1. add first_name = models.CharField() etc to Student. I don't recommend this method.
#
  1. Add a user = models.ForeignKey('auth.User', on_delete=models.CASCADE, related_name='user') to your Student model.
#

Then you can access these attributes via Student.objects.get(pk=1).user.first_name etc. Like that.

past cipher
#

No idea if anyone gonna find this useful, but I created something to help with setting up Flask for development. I had the trouble of having to manually setup db, models, forms, login etc. So decided to create a quick script that does it in 30 seconds.

https://github.com/MrNaughtZero/flaskCreate

tacit comet
#

Then you can access these attributes via Student.objects.get(pk=1).user.first_name etc. Like that.
@versed python how can i show admin panel this without click edit button

#

in admin.py ?

marsh canyon
#

that is where ur __str__ method comes in

versed python
tacit comet
marsh canyon
#

wait

#

you want to change the representation of model instance displayed in the admin?

#

the page where it lists all the instances?

lethal orbit
#

No idea if anyone gonna find this useful, but I created something to help with setting up Flask for development. I had the trouble of having to manually setup db, models, forms, login etc. So decided to create a quick script that does it in 30 seconds.
@past cipher neat... but any reason you didn't use https://github.com/cookiecutter/cookiecutter ?

tacit comet
#

i added models name surname as you see but i want to use auth.user 's first_name , last_name methods

marsh canyon
#

ur prolly looking at a custom user admin

#

from django.contrib.auth.admin import UserAdmin
find this in the docs

past cipher
lethal orbit
#

Oh. It's a pretty great tool to do exactly that 🙂

past cipher
#

also good to add to my github for when i do eventually start looking for work in a year or so

lethal orbit
#

I'm sure there are flask cookiecutters out there already.

past cipher
#

yh probably xD

lethal orbit
#

But you can always write your own. I have one for my stack...

#

Not quite thorough, because I don't start new projects that often.

past cipher
#

I have a couple of jobs on the go, and I hate rewriting code that I've already used, usually takes me at least 30 minutes, especially when creating auth pages etc

#

thanks for the SQL help yesterday btw, I had to dash so didn't say thanks

wicked basalt
#

Hello, I know it may not be related completely to web dev but in SQL I'm trying to SELECT the 2nd highest element in a CASE WHEN clause. I don't know how to do it. Anyone has an idea ?

uncut spire
#

has anybody ever done a salesforce integration to pull data out regularly? seems like one good approach would be cron jobbing a script that uses simple-salesforce to SOQL all data in some date range. has anybody done that/something similar and have an opinion?

warped acorn
#

hola.

#

is this the right channel to ask for some web scraping help?

past cipher
#

probs not

warped acorn
#

thanks man.

topaz finch
#

I am using flask.

I want to have a variable in my base template (parent of all the others) that will always be set, so that I do not have to render_template("example.html", variable=variable)
every time i render a template. Am I able to set a default variable somehow?

@ me when responding, please.

tight pilot
#

I can't connect to my flask server from another computer via LAN unless I specify host='0.0.0.0'. Does anyone know why? Does flask do some sort of port forwarding magic?

vague ibex
#

Guys, can you suggest me a good IDE for nodejs which will run smooth in 4gb ram/lower devices

lethal orbit
#

vim

#

That's what I use on my laptop.

#

Install some plugins, though.

vague ibex
#

is vim free?

dapper tusk
#

yes

versed python
#

good luck lol

hearty birch
#

anyone familiar with flask and specifically flask_sqlalchemy?

lethal orbit
strange briar
#

hey guys

#

is this the right syntax to index a column with django ?

#

email = models.EmailField(unique=True, db_index=True)

limber laurel
#

I am past the basics and I want to advance but I also dont want to get ahead of myself, but I also dont want to end up making projects from the things that I have done 20 times before, any recommendations?

verbal obsidian
#

email = models.EmailField(unique=True, db_index=True)
@strange briar Seems right

#

I can't connect to my flask server from another computer via LAN unless I specify host='0.0.0.0'. Does anyone know why? Does flask do some sort of port forwarding magic?
@tight pilot Not flask, 0.0.0.0 and :: means to listen to every available interface, more in https://serverfault.com/questions/21657/semantics-of-and-0-0-0-0-in-dual-stack-oses/39561#39561

#

I am using flask.

I want to have a variable in my base template (parent of all the others) that will always be set, so that I do not have to render_template("example.html", variable=variable)
every time i render a template. Am I able to set a default variable somehow?

@ me when responding, please.
@topaz finch https://flask.palletsprojects.com/en/0.12.x/templating/#context-processors

bitter saffron
#

Hi friends
I'm trying to deploy my flask app on heroku ... but I get such an error like this :

<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="utf-8">
<title>Application Error</title>
<style media="screen"


And when I check logs , I see this :
2020-09-16T18:06:04.000000+00:00 app[api]: Build succeeded
2020-09-16T18:06:04.112017+00:00 heroku[web.1]: State changed from starting to up
2020-09-16T18:06:19.687897+00:00 heroku[web.1]: Restarting
2020-09-16T18:06:19.690781+00:00 heroku[web.1]: State changed from up to starting
2020-09-16T18:06:20.754799+00:00 heroku[web.1]: Stopping all processes with SIGTERM
2020-09-16T18:06:20.786718+00:00 app[web.1]: [2020-09-16 18:06:20 +0000] [13] [INFO] Worker exiting (pid: 13)
2020-09-16T18:06:20.786741+00:00 app[web.1]: [2020-09-16 18:06:20 +0000] [14] [INFO] Worker exiting (pid: 14)
2020-09-16T18:06:20.787149+00:00 app[web.1]: [2020-09-16 18:06:20 +0000] [4] [INFO] Handling signal: term
2020-09-16T18:06:20.988269+00:00 app[web.1]: [2020-09-16 18:06:20 +0000] [4] [INFO] Shutting down: Master
2020-09-16T18:06:21.577505+00:00 heroku[web.1]: Process exited with status 0
2020-09-16T18:06:23.713913+00:00 heroku[web.1]: Starting process with command gunicorn run:app --preload
2020-09-16T18:06:28.686751+00:00 app[web.1]: [2020-09-16 18:06:28 +0000] [4] [INFO] Starting gunicorn 20.0.4
2020-09-16T18:06:28.688185+00:00 app[web.1]: [2020-09-16 18:06:28 +0000] [4] [INFO] Listening at: http://0.0.0.0:11808/ (4)

State changed from starting to up
2020-09-16T18:08:02.420945+00:00 heroku[router]: at=error code=H12 desc="Request timeout" method=POST path="/api/auth/admin/signup" host=agile-basin-93374.herokuapp.com request_id=fadb7827-cc2e-460d-98ae-d22efa3614dd fwd="2.179.42.45" dyno=web.1 connect=0ms service=30001ms status=503 bytes=0 protocol=https

could anyone help me?

bitter saffron
weary bough
#

plz help

twilit dagger
#

Sort of strange but my hover classes don't work in Heroku

quick cargo
#

@twilit dagger you sure heroku is actually serving the css file if you have a seperate file for that

twilit dagger
#

No it is serving CSS

#

But the btn:hover is the only thing not working

quick cargo
#

@twilit dagger whats the full class list?

twilit dagger
#

This is all -

.navbar-nav .heading{
    color: white;
}

.navbar-nav .heading:hover{
    color: #444444;
}

.navbar-nav .header-btn:hover{
    color: #333333!important;
}

.header-btn:hover{
    color: #333333!important;
}
quick cargo
#

thats css

#

not the class list

twilit dagger
#

"btn btn-outline-light float-right text-light header-btn btn-lg"

#

I sent CSS so it makes sense

#

This is with bootstrap

quick cargo
#

you know you havent defined the base css for it first right?

#

cant apply a hover varient to a css element that doesnt exist 🙃

twilit dagger
#

what are you saying

quick cargo
#

everything todo with the button you have as hover varients

twilit dagger
#
<div class = "text-right float-right">
                    <a href = "{% url 'contact' %}"type = "button" class = "btn btn-outline-light float-right text-light header-btn btn-lg">
                        Contact</a>
                </div>
quick cargo
#

look at your css

#

you need to have a standard:

.header-btn {
  background: #fff;
}
twilit dagger
#

Doesn't bootstrap handle that

quick cargo
#

no idea

twilit dagger
#

it works on localhost just not on heroku

quick cargo
#

yikes

#

how are you importing the css then

twilit dagger
#

whitenoise

quick cargo
#

does any of the css work

twilit dagger
#

yes all of it works

#

just not :hover

#

I assume its some bootstrap problem

quick cargo
#

that is a yikes tbh

#

i dont know heroku so i cant really help you with much more of that im afraid

#

So im looking for some feedback on a router im making and wondering if others might find it useful.
The general idea is to make it easier for you to layout your applications with fewer global varibles using true class instance views regardless of the framework.

Example of a view file:

# ./views/my_view.py
import router

from sanic import Sanic
from sanic.websocket import WebSocketConnection
from sanic import response
from sanic.request import Request

class MyEndpoint(router.Blueprint):
    def __init__(self, web_app: Sanic):
        self.app = web_app

    @router.websocket("/")
    async def my_func(self, ws: WebSocketConnection):
        pass

    @router.endpoint("/hello")
    async def hello(self, request: Request):
        return response.text("Hello world")


def setup(web_app):
    web_app.add_blueprint(MyEndpoint(web_app))

Example main.py

# ./main.py
import typing as t

from sanic import Sanic
from sanic.websocket import WebSocketProtocol

from router import Router, Endpoint, Websocket

app_files = [
    "views.my_view"
]

app = Sanic(__name__)


def submit_route(_, endpoint: t.Union[Endpoint, Websocket]):
    if isinstance(endpoint, Endpoint):
        app.add_route(handler=endpoint, uri=endpoint.route, methods=endpoint.methods)
    elif isinstance(endpoint, Websocket):
        app.add_websocket_route(handler=endpoint, uri=endpoint.route)


router = Router(app, app_files, submit_route)

if __name__ == '__main__':
    app.run("127.0.0.1", port=8000, protocol=WebSocketProtocol)

In this example im using Sanic but this will work with any ASGI or WSGI framework, using a simple callback for you to tailer your route setting to the framework's design.
This should help anyone stuggling with laying out their apps with lots of global varibles gain a bit more control over their layout.

Please let me know of any feedback you have for this and if you think it would be useful to make public 🙂

valid sandal
#

hey if anyone is familiar with django

#

and can give me a hand with a filter system

#

pleaseeeee

turbid fox
#

Post your code

brave bolt
#

Hello there

#

So I have an SSO login at my office...I can direct to it and get the key and refresh key back...how does flask separate that info from the next person loggint in 5 seconds later?

fleet sorrel
#

can someone help me convert python script to exe file

plucky tapir
#

What framework would be best to start web development

#

Django?

warped timber
#

flask is easy and lightweight

plucky tapir
#

Nice thank you though. I wasn't aware of this I always thought they were created though html/css or javascript

zealous siren
#

Vue and either Flask or FastAPI

vestal hound
#

I started with Django

#

I liked it

fleet sorrel
#

is it possible to do front end in django or flask?

zealous siren
#

Yes but it’s not industry standard

versed python
#

uggh that's why I hate the industry

#

why can't it just accept vanilla django

#

now I am having to learn all this Javascript shit

zealous siren
#

Because More responsive

versed python
#

ik the reason why it's industry standard. doesn't mean i like it

zealous siren
#

Sure but there is damn good reason for it

versed python
#

i know it. I'm using Vuejs now, and can see how websites look better right out of the box

#

I guess it's kinda a tradeoff. You either choose beauty with more time spent or, ugliness but with less time spent

valid sandal
#

hi

#

just trying to add a filter

#

for all the different atributtes from a model

#

and all the atributtes have different kind of values

#

some are boolean, some are charfield, some are intFields

#

etc

#

so every filter has to be unique

#

and I don't know how to join them

#

if someone has a clue or an example to share

#

:c

versed python
#

@valid sandal django or flask? Share your model structure here please.

valid sandal
#

django

#

@versed python

warped timber
#

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

versed python
#

!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!')
warped timber
#

@valid sandal

valid sandal
#

here it is

versed python
#

What language is that btw?

#

Spanish?

valid sandal
#

spanish

#

xoox

#

yep

#

I'm from Argentina

versed python
#

Don't you find it difficult to write code both in English and Spanish?

valid sandal
#

spanglish ftw

versed python
#

lol that sounds like a dog

valid sandal
#

it's shared code with my team, so I have to do it

scenic otter
#

Does django help

versed python
#

Not with that attitude

scenic otter
#

huh

versed python
#

@valid sandal What help did you need?

valid sandal
#

I need to filter every atributter in a big search

#

atributte*

versed python
#

Can you give an example?

valid sandal
#

this is a filter from another proyect

#

where I only apply a simple filter by a category called "rubros"

dapper tusk
#

it does not run all of the code for each request

#

it does run a bit to check if there is a request

#

but the actual request handling happens once

mystic wyvern
#

guys who is better change something in admin panel or in database?

tawdry magnet
#

heres the answer your going to hate

#

"it depends"

#

if your going to be doing it a lot maybe its easier to do it in the admin panal

lethal orbit
#

guys who is better change something in admin panel or in database?
@mystic wyvern If you mean Django, the admin panel should not be used by too many users. It's meant specifically for administrators, not end-users.

tawdry magnet
#

if its going to be rare and only you know how to do it then maybe its not worth the effort and u can just do it in the database

lethal orbit
#

If you mean a one-time change to your models, nothing wrong with using admin

mystic wyvern
#

ok guys thx

zealous moth
#

Hey guys i created a new directory inside media directory from views.py file now how can i cd to the new created directory..

versed python
#

Wdym @zealous moth ?

zealous moth
#

??

jagged lark
#

I’m pretty sure that’s against their ToS

zealous moth
#

Wdym @zealous moth ?
@versed python Ok i got it...😆

versed python
#

I’m pretty sure that’s against their ToS
@jagged lark Who was this for?

jagged lark
#

For @zealous moth, about the tiktok ToS

zealous moth
#

@jagged lark idk

versed python
#

You guys still have TikTok?!?!

zealous moth
#

Nope i dont use that shit😆

#

whys the django did not apply the changes instantly sometimes. I did restart the server 3-4 time but the changes are not taking place

versed python
#

That shouldn't happen

#

What kind of changes are you making?

zealous moth
#

changing css

#

now it fixed

#

it happens sometimes

native tide
#

hi everybody 😊,

my english is bad so please be kind.

i use python since 1 month, my background in web development 5 month in php.

i win a stage and the begin of diffuclt is here ! my brain 🧠 have no connexion with the unit-test ( pytest)
perhaps some of you have a good hints or tips to helps me ! i need a success small one but one 😊😊😊

thanks

#

ps: i work with the framework piramid ! python3

lethal orbit
#

perhaps some of you have a good hints or tips to helps me ! i need a success small one but one 😊😊😊
I find using functional programming paradigms makes writing unit tests easier. Don't try to keep too much logic tied to your data models, but write logic in small, easily testable functions as much as possible. As a bonus, you can easily reuse those functions across different modules and models.
Also, check out #unit-testing , and read as much as you can about the topic. I recommend these 2 books, even though they are not related to pyramid in any way:

mystic wyvern
#

'function' object has no attribute 'objects'???

high jacinth
#

Help pls, if I have an app that does something that takes like ten seconds to work hosted on heroku, does that mean each user who sends my app a request has to wait ten seconds or do they join a queue and have to wait for ten seconds*the number of users ahead of them? Or does it simply crash?

#

Sorry if the question doesn't make sense

versed python
#

Probably the first especially if your app has a lot of good looking stuff

#

An easy way to check is by trying to access the website through your pc, laptop and a few phones from your family members @high jacinth

high jacinth
#

@IgnisDa I'll do just that actually

lethal orbit
#

oof

#

What are you doing that takes 10 seconds @high jacinth ? Why not pre-calculate it?

jagged lark
#

No, doff

high jacinth
#

@lethal orbit I'm webscraping and wrapping the result up in an epub. I also wanted to know how heroku would deal with blocking code if there was any

jagged lark
#

Maybe you should cache your result then

#

Of you aren't using any *wgi system, they will just end up on a queue, yeah

lethal orbit
#

If it is one file, you are probably better off indexing it.

high jacinth
#

I'm not scraping the same thing repeatedly. What's *wgi??

lethal orbit
#

If you are letting people pass a URL, then it is definitely more complicated.

#

If it is a set of epubs, you probably also would want to process them all and index them.

jagged lark
#

They are tools made to dispatch the requests to many instance of your server

high jacinth
#

@lethal orbit I'm not keeping any epubs, I just want to consume the url then spit out an epub

#

@jagged lark pls give me hint

#

And by that I mean direction to documentation. Do I just google wgi?

jagged lark
#

I'm not sure if that's possible with heroku

high jacinth
#

Oh. 😢

native tide
#

@lethal orbit thanks 😊

mystic wyvern
#

'function' object has no attribute 'objects'???

#

why?

verbal obsidian
#

because fucntion object does not have attribute objects.

#

you are probably looking for a model object

#

and got something else

#

if we are talking about django of course

mystic wyvern
#

yep django

#

ok

verbal obsidian
#

I could perhaps help you a bit more if you shared the snippet that triggered the error

mystic wyvern
#

look i write this in my views

def new_topic(request,boerd_id):
board=get_object_or_404(Board,pk=boerd_id)

if request.method =='POST':

    mes =request.POST['message']
    sub= request.POST['s']
    user=User.objects.first()

    Topic = topic.objects.create (                         subject=sub,
    created_by=user

    )
verbal obsidian
#

the issue is with topic

#

are you importing it correctly?

#

and is it a class that inherits from models.Model?

mystic wyvern
#

yeh i do all of this

#

and i import it and i inherits from models.Model

#

look class topic(models.Model):

woeful swan
#

in drf how to pass a non model field of any type and get it back in response ?

marsh canyon
#

i think u mean SerializerMethodField() @woeful swan

woeful swan
#

i tried that but after .is_valid() call it is not present in the validated_data

marsh canyon
#

do you read-only set on those fields by any chance?

#

nvm

#

SerializerMethodField() is by default read only

woeful swan
#

i have read that field is read_only by defautl

#

yeah

marsh canyon
#

then

#

u can define fields in the serializer

#

custom fields

#

just outside ur Meta class

woeful swan
#

ok

#

but when i run .save() it gives error

#

some attribute type

#

error

marsh canyon
#

show

#

code

woeful swan
#

for now

#
class QuerySerializer(serializers.ModelSerializer):
    # q = serializers.CharField(required=True, max_length=512)
    extra_params = serializers.SerializerMethodField()
    q = serializers.SerializerMethodField()

    def validate_q(self, value):
        return value

    def get_extra_params(self, *args, **kwargs):
        print(self.initial_data, 'extra params')
        return self.initial_data.get('extra_params')

    def get_q(self, *args, **kwargs):
        return self.initial_data.get('q')

    class Meta:
        model = SessionInfo
        fields = ('q', 'bot_id', 'session_id', 'extra_params')

        # extra_kwargs = {
        #     'bot_id': {'write_only': False},
        #     # 'q':  {'write_onlyr: False},
        # }


class QueryResponseSerializer(serializers.Serializer):
    session_id = serializers.CharField()
    response = serializers.ListField()
    status = serializers.DictField(required=False)
    extra_params = serializers.SerializerMethodField()

    def get_extra_params(self, *args, **kwargs):
        return self.initial_data.get('extra_params')
#
class QueryApiView(views.APIView):
    def post(self, request, *args, **kwargs):
        # print(request.data, 'berfoer')

        ## session validation
        try:
            session_obj = SessionInfo.objects.get(session_id=request.data.get('session_id'),
                                                  bot_id=request.data.get('bot_id'))
        except SessionInfo.DoesNotExist:
            return Response({'error': 'session does not exists for given bot'}, status.HTTP_404_NOT_FOUND)

        # serializer with instance
        serializer = QuerySerializer(instance=session_obj, data=request.data)
        print(serializer.initial_data, 'initial')

        # checking validation
        if serializer.is_valid(raise_exception=True):
            print(serializer.validated_data, 'validated')

            # fetching response
            resp = bot_response(serializer)
            finalize_data = {
                'session_id': serializer.validated_data.get('session_id'),
                'response': resp,
                'extra_params': serializer.initial_data.get('extra_params')
            }

            serializer_output = QueryResponseSerializer(data=finalize_data)
            if serializer_output.is_valid():
                serializer.save()
                return Response(serializer_output.data, status.HTTP_200_OK)
            return Response(serializer_output.errors, status.HTTP_400_BAD_REQUEST)
        return Response(serializer.errors, status.HTTP_400_BAD_REQUEST)
#

using this

#

i just want the extraparams in request and return as it is while saving the data

marsh canyon
#

what are you passing in

woeful swan
#

i am very new to drf so it is confusing me?

#
{
    "session_id": "SUq50ChnZjRiZ5rb",
    "bot_id": "MGZI6EE3",
    "q":"hiii",
    
    "extra_params": {
        "amit": "bisht"
    }
}```
marsh canyon
#

u have SerializerMethodField() defined, they are read only

#

make those char field

woeful swan
#

ok

#

on more question. how can i accept any type of data . not just char from that field

#

?

marsh canyon
#

well you can use a charfield and take in whatever you want and later parse it

#

there is even Json field

#

and u can pass anything with the json

woeful swan
#

but it has to be string right?

marsh canyon
#

mostly, yes

woeful swan
#

i want it to accept int, list, dict and str

marsh canyon
#

its good have a data type assinged, to not confused the API user

#

then make 4 fields for those

woeful swan
#

well setting as charfield worked now. I don't know why it was not working before?

marsh canyon
#

u use SerializerMethodField() before, right?

woeful swan
#

then make 4 fields for those
@marsh canyon i mean extraparams can be of any of those type?

marsh canyon
#

params are always string

#

params are attached to the url

#

after a question mark ?

woeful swan
#

u use SerializerMethodField() before, right?
@marsh canyon no first i used charfield, but it was giving error so after researching i used SerializerMethodField but that was not coming in validated data.

marsh canyon
#

like path/?name=iceman
here name is a param and the value is iceman
you can get these by doing either request.GET or request.get_params -> these 2 are query dicts

woeful swan
#

no non no . extra_params is just a key name. it can be optional data. which api user can pass and will be returned same in response

#
{
    "session_id": "SUq50ChnZjRiZ5rb",
    "response": [
        {
            "sender": "SUq50ChnZjRiZ5rb",
            "message": null
        }
    ],
    "extra_params": "amit"
}```
#

response sample

marsh canyon
#

so maybe a dict will be good for extra params

woeful swan
#

yeah i have considered that

marsh canyon
#

or just have explict names for all the extra params

woeful swan
#

in dict field there is child argument

marsh canyon
#

i mean havea field for each extra param

woeful swan
#

what does it checks

#

i mean havea field for each extra param
@marsh canyon i understand

#

BTW thanks man for helping

marsh canyon
#

the child arg is to set the data type for values

#

the keys are assumed to be string

#

docs

woeful swan
#

ok ok.

#

i will try that

marsh canyon
#

oki

woeful swan
#

👍 👍 👍

marsh canyon
#

lemme know how it goes, cuz i have never used DictField

woeful swan
#

sure. i am just now rewriting a single serializer for this. two are confusing me.

marsh canyon
#

oki

woeful swan
#
    {
        "session_id": "SUq50ChnZjRiZ5rb",
        "bot_id": "MGZI6EE3",
        "q":"hiii",
        
        "extra_params": {
            "amit": "bisht",
            "roman": 34,
            "texas": {
                "smash": "yes"
            }
        }
    }
{
    "session_id": "SUq50ChnZjRiZ5rb",
    "response": [
        {
            "sender": "SUq50ChnZjRiZ5rb",
            "message": null
        }
    ],
    "extra_params": {
        "amit": "bisht",
        "roman": 34,
        "texas": {
            "smash": "yes"
        }
    }
}```
yeah it worked man
marsh canyon
#

cool 👍

woeful swan
#

i didnot provide child argument.

#

thanks again...

marsh canyon
#

i guess the default is charField

#

oh nvm, if you dont provide one, then it will not bother checking

woeful swan
#

ok

marsh canyon
#

@zinc hill maybe post ur question down here again, just so its noticed

zinc hill
#

ok thanks

#
view.py
class RestaurantLoginView(LoginView):
    template_name = 'accounts/restaurant/login.html'

    def get_success_url(self):

        url = 'company_profile'

        return super().get_success_url()

how do i redirect to something else instead of LOGIN_REDIRECT_URL

marsh canyon
#

right

#

so instead of returning the Super() implementation, you can return url instead

#

lemme check what format the url is in

#

you have to set url to the full path

#

and not the url name

#

or you can import resolve_url from django.shortcuts and pass in the url name to resolve_url to generate the url for you

zinc hill
#

yeah I tried setting the url = 'company/profile/' and return url but it keep adding on to the path

marsh canyon
#

use resolve_url

zinc hill
#

ok I will look into that

marsh canyon
#

from django.shortcuts import resolve_url

#

return resolve_url(<your url name>)

#

this is how django does it internally

#

django uses resolve_url

zinc hill
#

ohhh perfect

#

thanks so much

marsh canyon
#

which editor are u using?

#

vscode, pycharm?

zinc hill
#

Vs

marsh canyon
#

awesome

#

if you hold ctrl and hover over LoginView

#

it should be highlighted, when you click it, it will take u to the source code

zinc hill
#

yeah I saw that and I didnt think to replace the "settings.login_...." to something else

marsh canyon
#

settings.login.. is just the url name, if you remember

zinc hill
#

I was trying to think of something stupid like setting settings.login.... to something my url instead...

#

instead of just replacing that smh

marsh canyon
#

its fine, you know now

zinc hill
#

thanks alot

marsh canyon
#

👍

zinc hill
#

thats enoguh for today smh

marsh canyon
#

django does burn ur energy fast 😬

zinc hill
#

yep got stuck for so long today because I realised that I didnt need AbstractUser so I delete the database and makemigration, but it keep saying auth table doesnt exist

marsh canyon
#

u need to migrate

zinc hill
#

turns out one of the terminal was open and was in manage.py shell

#

yeah I did

#

once I quit the shell... and do the migration again than it work

marsh canyon
#

also, you need to reconfigure the auth model in settings

zinc hill
#

that was 2hrs of googling wasted

#

aaight thanks again for helping me out

#

have a great night

marsh canyon
#

u too

woeful swan
#

@marsh canyon you there

#

Got AttributeError when attempting to get a value for field extra_params on serializer InitSerializer.
The serializer field might be named incorrectly and not match any attribute or key on the SessionInfo instance.
Original exception text was: 'SessionInfo' object has no attribute 'extra_params'.

#

getting error. but model is saving data

#

in DRF

cold grove
#

Is there a way to exclude an attribute from being serialized by json.dump?

mystic wyvern
#

Cannot assign "<Board: 1>": "post.topic" must be a "topic" instance.

#

what this is?

dense slate
#

Is there a way to use something like:
rating_dict = sorted(rating_dict, key=rating_dict.get, reverse=True)
but for larger querysets? Especially when scaling. It's taking like 4-5 seconds so far for 500 entries.

#

I'm essentially needing to sort a user directory by rating, which is devised by a method on the user object that does some stuff to determine the rating.

#

I considered just having a rating field on the user, and updating it whenever the user does "something", but that makes it less accurate over time.

fair light
#

why do i get this error and how do i fix it? please ping me in reply