#web-development

2 messages · Page 166 of 1

autumn hedge
#

@slow gazelle if you type pip --version in whatever console. it will tell you which python version is in use

slow gazelle
#

i found the error now, I'm starting the app the wrong way

autumn hedge
#

for me its this

slow gazelle
native tide
#

hey, im trying to host a flask webapp on docker is there a hosting provider yall recommend that isnt expensive?

slow gazelle
#

i'm using this one to start my app, for some reason, even i activate the pipenv shell in the terminal, that start button is not working

#

but when i type py app.py then it works

grand harbor
twin rampart
#

im using python and selenium. My problem is that this for loop isnt running, he comes through the if loop but not continues the for loop...

      for multiple_tasks in driver.find_elements_by_xpath("//div[@color='" + listed + "']"):
#

the weird thing is, that this is working perfectly on other loops, but not here

ivory bolt
#

Digitalocean is good too

ivory bolt
#

security is BIG in django

#

mainly the fact that it creates so much stuff for you is insane in itself

dusk portal
#

@ivory bolt oh

#

Hmm

#

Kinda complex but not hard

#

1% more complex then flask

twin rampart
native tide
native tide
amber harbor
native tide
amber harbor
ivory bolt
dusk portal
#

@ivory bolt good but
Can u guide me sometimes i have done docs that 8 parts

chilly falcon
#

anyone interested to learn django together ??

ocean notch
#

i'm down

#

how does it work? lol

ocean notch
chilly falcon
#

Ok bro

#

Check dm

runic sparrow
#

small insignificant question, but does anyone know PyCharm gave this .py file a "dj" icon?

#

I'm assuming it has something to do with django

#

but I'm working on Flask...

languid beacon
#

where can i ask js questions

runic sparrow
calm plume
#

Assuming it's related to web dev

runic sparrow
#

What is the purpose of a wsgi.py file for Gunicorn? Can you not just use the app.py file itself?

ionic idol
#

can someone help me with drf-yasg - Yet another Swagger generator?

stoic lark
#

guys can anyone tell me how to clone 1 website if i like theme ?

ivory bolt
#

asgi would be your async related stuff, while wsgi is sync, standard http

ivory bolt
ivory bolt
#

what all have you done

chilly falcon
#

Yep

dusk portal
#

@ivory bolt i will tell what i have done from where
U tell me what to do next
How
From where and help me if i have doubt or any error plz

ivory bolt
#

alright

#

I'm not overly experienced with django, but I generally have a knack for the

#

'what to do next' thing

chilly falcon
#

I have learn function base view now i want to learn class base but i can't understand it

runic sparrow
chilly falcon
#

Super() ... Is confusing 🤣🤣 dont know about mixin ... Which should i learn first

ivory bolt
#

so class based views are really good when it comes to inheritance, and there are two ways to go about them:

  1. Using the generic CBVs offered by django
  2. Creating your own
ivory bolt
#

there are things that you can freely write in function based views that you just can't in class based views

chilly falcon
#

I realy dont get this mixin ... There are lot of stuff going on and dont know where to start..

karmic flare
#

Is it even possible to use websockets for refreshing the content of an iframe?

languid beacon
calm plume
#

You can ask in off-topic

ivory bolt
ivory bolt
ivory bolt
chilly falcon
#

Thank bro still confuse i will try to do some stuff with it and if i get stuck i will ask you

runic sparrow
#

That's why I'm confused

stoic lark
#

hey guys

#

can anyone clone this website -? www.faceit.com or can do same with python ?

dreamy talon
#

Why

#

I hope you’re not trying to phish steam accounts @stoic lark 🙂

stoic lark
#

no no

#

i will create my own database

#

i need just running script like this website

#

people register to my website

#

and they find match

dreamy talon
#

I gotcha

stoic lark
#

they play on my country gameservers

dreamy talon
#

Cloning faceit would probably be very hard. Maybe something like popflash would be easier

stoic lark
#

yeah

#

popflash also well

#

i dont nee tournament etc

frosty gale
#

Why is the color property scratched off under the a.home selector?

ivory bolt
ivory bolt
#

basically, synchronous code has to make an http request every time a resource is updated -- it will not update on it's own.

Asynchronous code keeps a TCP connection open, where the server could be constantly sending information via some pipeline of sorts -- those are your websockets.

#

That's why in a messaging app, or an app like discord, you don't need to refresh the page every time the app has new information for you: a message, a server invite, ANYTHING

#

wsgi is a standard file name that deals with synchronous code

#

and asgi, async

runic sparrow
#

I still don't understand why it's being labelled as"Django" though.

ivory bolt
#

oh. that's simple

#

you must have installed an extension for python web development or some icons pack

#

since django is more recognised

#

and it is MANDATORY in django to define the wsgi.py file (though that is made for you every time the project is made)

runic sparrow
#

Oh... If I knew that, I probably would've started with Django 😅

ivory bolt
#

No I mean you don't need to

quasi monolith
#

Hi , I want to ask how can I pass the ValidationError messages from my custom validation functions to the template

ivory bolt
#

look there's no such thing as one framework being superior to the other (everything > php)

runic sparrow
#

Is there any point whatsoever in having a wsgi.py file for Flask and Gunicorn? Could I not just use app:app instead of wsgi:app or something?

quasi monolith
#

I want to use the same design for my messages as the design from django forms validation

ivory bolt
quasi monolith
#

I want to use the same design for my custom ValidationErrors as the design which is given from django

#

Just to pass the message from my validation error to the frontend and to show at the same way as the django error

#

I can't specify more

ivory bolt
#

just pass it along as context or via an api

quasi monolith
#

doesn't matter I will use HTTP message

#

thanks anyways

ivory bolt
smoky shore
#

im new to coding and want to know how to make a website

autumn hedge
#

@smoky shore
step 1: make an html file named index.html and open in notepad.
step2: type hello world and save the file
step3: double click to open the file in your browser and wallah! you have a local static website

#

to make it more exciting, follow the django or flask install guide

#

then take your hello world index.html file and place it inside flask or django template directory.
From there you can configure flask or django to serve that static index.html file.

#

To make even more exciting you can then start adding css the actual HTML markup. Try using bootstrap css as a starting point.

smoky shore
#

@autumn hedge would u prefer django or flask

calm plume
#

That's not exactly best practice

#

You should put a tag around "hello world"

autumn hedge
#

@smoky shore Flask!

calm plume
smoky shore
#

ok thank you

calm plume
#

Django is a full on web framework, Flask is a microframework

smoky shore
#

i would like to do flask cause im new and want a smaller project

autumn hedge
#

@calm plume the question is for a beginner and I later referred to using HTML markup in a later step

calm plume
autumn hedge
#

@smoky shore Start with Flask

calm plume
autumn hedge
#

good practice is developed ... not taught

calm plume
#

For the basics of HTML and CSS, Codecademy's courses are rather good

calm plume
smoky shore
#

do i install it in python?

autumn hedge
#

@calm plume yes, but that doesn't help answer the question

calm plume
#

However, you would install Flask or Django

autumn hedge
#

@smoky shore what are you asking to install?

autumn hedge
#

yes, Flask and Django are python packages that you will install to your local machine

calm plume
#

@smoky shore I recommend you learn the basics of HTML and CSS first

#

Otherwise you'll be completely lost

smoky shore
#

ok

#

do i just watch a video on that

calm plume
#

I learned them from Codecademy's courses, those were good

autumn hedge
#

@smoky shore you can watch videos, pay for online courses, or learn by reading and following docs..its entirely up to you

#

I learned by reading the docs

smoky shore
#

i would rather take the free rout

#

can u send some docs in dms if thats possible?

#

also thanks for all the help

cursive hazel
tall steppe
#

Hello, I have a question there is a way to do a "contol S" in a python script? Other than with urllib.request... to save an image on a web browser

devout coral
#

Anyone here pretty familiar with the Django ORM? I need some help.

vestal hound
scenic vapor
#

Hey friends, i'm launching my MVP soon. We are testing with 1000 users. Im hosting the front and backend separately on digitial ocean. Will the 5$ droplet for both front and back end be sufficient? It's an ecommerce app

devout coral
vestal hound
#

that's interesting

#

why do you want to do that

#

what do you mean by "disconnect"?

#

by default if everything has been loaded it won't hit the DB any more

#

if I understand what you mean

devout coral
#

I want have a long running celery task

vestal hound
#

like you need to explicitly call .refresh_from_db()

devout coral
#

But I get max connections when I run a few of those

vestal hound
#

ah

#

okay

devout coral
#

Changing to updating with redis

#

Pushing updates to redis then having one thing that reads from redis and updates everything as needed.

vestal hound
#

hm I'm not sure if Django will support this easily

devout coral
#

However, I want to access everything like normal as their objects.

#

When does django "disconnect" an object? I do not seem to find anywhere where that is stated.

vestal hound
#

I have no idea offhand

#

I would have to look through the source code

#

but having a long-lived model instance

#

is probably not something that is contemplated

#

and...I don't think each instance holds on to one connection...?

#

the connection pooling should be handled by the driver

#

AFAIK

devout coral
#

Like, the idea is get everything from the database and make it static and disconnected from the db. Then when I need to update the database I put something in redis and have another celery task that reads from redis to update the database.

#

The second part I got figured out

devout coral
vestal hound
#

hm.

#

I'm actually not sure about this

#

sorry

devout coral
#

Alright

mild bridge
#

Maybe you could just use the builtin JSON serializer on the model, store that, and immediately do a del instance?

#

I'm not sure what Django does on model __del__s but I'm fairly sure the DB connection will close once it's garbage collected

primal thorn
#

how do i fix this heroku error, ive tried everything and it dosent work, at=error code=H10 desc="App crashed" method=GET path="/

opal leaf
#

hiiiiiiii

#

I am pretty good in python and still learning django but I need to training on my skills there's a group or smth can help me?

devout coral
#

You can ask here

#

So if I have that model object unless I do a refresh_from_db it is not connected to the db?

celest sinew
#

i need help

devout coral
devout coral
celest sinew
# devout coral What do you need help with?

this thing keeps saying:
Ignoring exception in on_message
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "main.py", line 57, in on_message
options = options + db["encouragements"]
TypeError: can only concatenate list (not "ObservedList") to list

devout coral
#

Looks like db["envouragements"] is an ObservedList. You need to turn it into a regular list to concatenate.

dusk portal
#

How can i master Django
I have readed those 8 parts but cant so something' like post req and fetching stuff

#

Can't get that logic

#
def index(request ,question_id)
    n1=get_object_or_404(pk=question_id)```
primal thorn
#

im using the python auth_views.LoginView.as_view in my projects urls.py for a login, how do i make a custom view where i can pass custom variables to it

mild bridge
#

Assuming you're referring to template vars, you can subclass LoginView and override the get_context_data method to add variables to the template's context

ivory bolt
#

can I see the project you've worked on

dusk portal
#

@ivory bolt sure

#

I have done that on project but can't do it on my own project

#

😭😭

primal thorn
#

i made a custom user model but when i try to make a superuser with my cli it does not hash it
so i cant login to my superuser account
but normally registering works

grand harbor
#

Hey guys, I want to make a lucky draw in my website, First I thought that I should use random to show one random item in the list

#

but then I thought I should make it like after rolling this many times a probability of getting a good item should be higher

#

so then i thought that after rolling 9 times the tenth item should be that good item and I make it fixed

#

but It will become odd that every 10 times you roll the 10th item will be that item

#

so is there a way to add probability on items like every 10 times you draw you will get that item one time. I hope You are understanding what I am trying to say

primal thorn
#

how do i fix this error, im getting this after i created a custom user model (1146, "Table 'app.auth_user' doesn't exist")

dusk portal
#
<a class="nav-link active" aria-current="page" href="{% url /'app1:index' %}">Home</a>```
#
def index(request):
    return render(request,'app1/index.html')```
#
app_name = 'app1'
urlpatterns =[
    path('',views.index,name='index')```
foggy fiber
#

maybe I don't know what I'm talking about but url /'app1:index' probably thinks you're trying to divide

cloud bone
#

anybody can help me for making dynamic database in using django

dusk portal
#

this was not issue XD

#

but tq

hollow apex
#

Hey so

#
@app.route('/logs')
def view_logs():
    contents = []
    with open('logs.txt','r') as logs:
        for line in logs:
            contents.append([])
            for item in line.split(' | '):
                contents[-1].append(item)


    titles = ('Entered Value','Result','IP','Browser')
    return render_template('viewlog.html',
                            the_title = 'Logs',
                            the_column_titles = titles,
                            the_data = contents)
``` this is the piece of the code
#

and this is the txt file it reads from

#

but the problem is

#
{% extends 'base.html' %}
{% block body %}
<h2>{{ the_title }}</h2>
<table>
    <tr>
        {% for column_title in the_column_titles %}
            <th>{{ column_title }}</th>
        {% endfor %}
    </tr>
    {% for log_row in the_data %}
        <tr>
            {% for item in log_row %}
                <td>{{ item }}</td>
            {% endfor %}
        </tr>
    {% endfor %}
</table>
{% endblock %}
``` with this html code, it does not show any table or any column
#

see, it is supposed to form a table, im quite sure I have passed all the variables correctly but got 0 idea why it would not work

cloud bone
#

anybody can help me for making dynamic database in using django

gray falcon
#

how can i use variables in python in a html code?

rugged charm
hollow apex
#

nvm I figured it out

#

programming is so tricky

#

one little mistype and you have to figure the whole thing out

hollow apex
#

Flask users, is there a way to make an exception and hide an html object from displaying from the main html file from which we extend our templates?

grand harbor
#

use if else and try except thats it

#

jinja template if else that is

hollow apex
#

so

hollow apex
# hollow apex

in here, this object ('smallest divisor of a number') and its background are in the main html file

#

I want to hide it in a specific html file

#

can you be more specific

primal thorn
#

how do i change the name of the tables so it dosent become like this in my db

opal canyon
#

Hello friends, I am building a website with Django, I decided to create a filter for my items, you can filter items like this: Item.objects.filter(type=item_type), so basically I created an url which takes a slug:item_type, and returns a JsonResponse with the items parsed as JSON.
Then I created an Ajax call in my js file and when I wanted to call the url I keep getting an error:
function filterItemType(type) {
$.ajax({
type: "GET",
data: $(this).serialize(),
url: "{% url 'boring:filter_items' type%}"
The Error:
Not Found: /boring/{% url 'boring:filter_items' type%}
[21/Jun/2021 11:32:54] "GET /boring/%7B%%20url%20'boring:filter_items'%20type%%7D HTTP/1.1" 404 6103

So basically JS is not parsing the Django {% url .... %} 😦 I have no idea how to do it in order for JS to build the route...
PS: I also tried to build the route with the type separated as -> url: "{% url 'boring:filter_items' %}" + "/"+ type;
But it's not working either, same error.

dusk aspen
#

does anyone know why this produces a index out of range error?
return cursor.fetchall()[0][0]
If i were to just print the cursor.fetchall() i would get this: [('admin',)]

surreal portal
#

Do you believe it's possible to make a Colab clone?

#

Using Jupyter's docker stack?

solar epoch
solar epoch
surreal portal
#

I suppose models.ImageField doesn't deal with bytearrays of pngs immediately does it?

solar epoch
surreal portal
#

When I use models in the shell, it shows a memory object

#

<memory at 0x7f5067ca0e80> like so

solar epoch
#

oh do you mean forms.ImageField? For validation?

surreal portal
#

No, I'm trying to show them through DRF

solar epoch
#

Well, what do you plan to display?

#

some encoded version of the image?

surreal portal
#
"creation_date": "somedate",
                "img": null,

This is what happens when I use a simple serializer.

surreal portal
solar epoch
#

Ah ok, I'd suggest you use BinaryField then

#

for your API you could have some explicit conversion function in your serializer to handle the encoding

surreal portal
#

I generated the bytearray using PIL

#

When I inserted records in the db

solar epoch
#

ok but you're still using Django's models, right?

surreal portal
solar epoch
#

well it should be a BinaryField.

#

For DRF the best thing is probably to write your own serializer field to do whatever encoding you need.

surreal portal
solar epoch
#

you should override to_representation() and do your encoding there.

surreal portal
#

Also I've seen a guy implementing methods within the models that takes the image and creates it through PIL.Image. He imported them as a field.

#
class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = (
            "id",
            "name",
            "get_absolute_url",
            "description",
            "price",
            "get_image",
            "get_thumbnail"
        )
#
class Product(models.Model):
    category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE)
    name = models.CharField(max_length=255)
    slug = models.SlugField()
    description = models.TextField(blank=True, null=True)
    price = models.DecimalField(max_digits=6, decimal_places=2)
    image = models.ImageField(upload_to='uploads/', blank=True, null=True)
    thumbnail = models.ImageField(upload_to='uploads/', blank=True, null=True)
    date_added = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ('-date_added',)
    
    def __str__(self):
        return self.name
    
    def get_absolute_url(self):
        return f'/{self.category.slug}/{self.slug}/'
    
    def get_image(self):
        if self.image:
            return 'http://127.0.0.1:8000' + self.image.url
        return ''
    
    def get_thumbnail(self):
        if self.thumbnail:
            return 'http://127.0.0.1:8000' + self.thumbnail.url
        else:
            if self.image:
                self.thumbnail = self.make_thumbnail(self.image)
                self.save()

                return 'http://127.0.0.1:8000' + self.thumbnail.url
            else:
                return ''
    
    def make_thumbnail(self, image, size=(300, 200)):
        img = Image.open(image)
        img.convert('RGB')
        img.thumbnail(size)

        thumb_io = BytesIO()
        img.save(thumb_io, 'JPEG', quality=85)

        thumbnail = File(thumb_io, name=image.name)

        return thumbnail
solar epoch
#

so what's happening here is that the image isn't saved as a bytearray, it's uploaded through django's file upload system... so the image is generated, converted to an in-memory file and then added to the image field

#

so the field here isn't byte array or anything, just the path to the file.

#

and the API is just showing the URLs, not the whole encoded image.

violet dock
#
Traceback (most recent call last):
  File "C:\Users\User\PycharmProjects\Johnnypricer\venv\lib\site-packages\flask\app.py", line 2447, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Users\User\PycharmProjects\Johnnypricer\venv\lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\Users\User\PycharmProjects\Johnnypricer\venv\lib\site-packages\flask\app.py", line 1821, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Users\User\PycharmProjects\Johnnypricer\venv\lib\site-packages\flask\_compat.py", line 39, in reraise
    raise value
  File "C:\Users\User\PycharmProjects\Johnnypricer\venv\lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\Users\User\PycharmProjects\Johnnypricer\venv\lib\site-packages\flask\app.py", line 1936, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "C:\Users\User\PycharmProjects\Johnnypricer\main.py", line 28, in decorated_function
    return view_function(*args, **kwargs)
  File "C:\Users\User\PycharmProjects\Johnnypricer\venv\lib\site-packages\flask_limiter\extension.py", line 702, in __inner
    return obj(*a, **k)
  File "C:\Users\User\PycharmProjects\Johnnypricer\main.py", line 74, in update_item
    return jsonify({"success": True, "name": data['name'], "sku": sku})
TypeError: 'Response' object is not subscriptable
127.0.0.1 - - [21/Jun/2021 22:55:45] "POST //items/5703;6 HTTP/1.1" 500 -``` how to fix this error?
surreal portal
#

Ok I see. Probably because the author wants to get them with axios through his Vue frontend

solar epoch
#

That's much more efficient that storing binary blobs in the database and streaming them out to the server, then to the user

#

generally you should avoid storing binary data in a database

desert estuary
#

im following this guy and while he does this it feels like something is off like why he does it in terminal instead of the flaskblog module also shouldn't he extract that data from the template

desert estuary
surreal portal
#

With Flask-SQLAlchemy you have to create it manually

#

He didn't cover an important section from server-db interactions called migrations. You have a separate module handling each change done to your models called alembic.

opaque rivet
surreal portal
opaque rivet
#

well, the issue is that data = jsonify(pricer(sku)) is a Response object which isn't subscriptable, so data['name'] is invalid.
also - pretty sure jsonify serializes the dictionary into a JSON-string instead of the other way around.

Instead of using jsonify(pricer(sku)) just use json.loads(pricer(sku))
@violet dock

gray falcon
#

how do i get the value of a textbox using a button in html?

#

im working with python and html

surreal portal
#
TypeError: 'DefaultAdminSite' object is not callable

Got this while adding the models to django's admin part

#

oh nvm I forgot register

opaque rivet
#

what specifically?

violet dock
quick cargo
#

ObjectId types are BSON

#

you gotta either remove the id key from the data

#

or you use pymongo's helper converter

violet dock
opal canyon
quick cargo
obtuse sedge
#

Hi guys,
Does django provide integration with aws??

quick cargo
#

what is your actual code

#

better than making a guess

opal canyon
violet dock
opal canyon
quick cargo
#

and an example mongodb document

violet dock
#

return json.dumps(sku_listing) or return x == data

quick cargo
#

and is that where the error arises from

violet dock
violet dock
quick cargo
#

what is the pricer function

violet dock
quick cargo
#

and is sku when you send that post request 5021;6

violet dock
#

yes

#

i did remove all the _id right?

quick cargo
#

from what i can see

violet dock
#

mhm what is causing it?

quick cargo
#

same error?

#

can you do print(repr(sku_listings))

violet dock
#

oh nvm

opal canyon
#

Django question: Why, if I render a view from another view, the path does NOT change!?

#

Im under this path, then I make a "transaction"

violet dock
#

but i removed_id in x = mycol...

quick cargo
#

out of curiousity

#

do "_id": 0 instead of "_id": False

opal canyon
#

I end up with this path

#

Shouldn't the return to "profile_page_view" reset the path?

violet dock
quick cargo
#

well mongo only accepts ints for that

#

so it may be a behavioural thing

violet dock
violet dock
quick cargo
#

mmm nothing massively sticks out

violet dock
#

how to add a if statement to check if _id exist or not?

#

find sku_listing['_id'] and del sku_listing['_id']

#

does the find works like that?

#
del sku_listing['_id]``` or this @quick cargo
quick cargo
#

well you could just use dict.pop("key", None) so it removes the key if it exists otherwise does nothing

violet dock
quick cargo
dusk portal
#

Pycharm
My old love

quick cargo
#

data is apparently a string

violet dock
quick cargo
#

I mean that will require a bit more debugging on your behalf

mystic wyvern
lilac nest
#

Do you guys know how to serve static files with django using cyber panel?

I used the guide provided https://cyberpanel.net/blog/2019/01/10/how-to-setup-django-application-on-cyberpanel-openlitespeed/

I know when I hosted it with IIS I would need to add a virtual host and put my static files there to be served, but I don't see that option here, and the static files aren't being served

DJANGO is a web application framework built with Python. DJANGO seen a tremendous growth recently, and a lot of developers are moving towards this framework.

ocean notch
#

Why even when using django rest framework do most companies embed the frontend into django instead of being standalone back and front ends?

obtuse sedge
#

How to integrate my discord to my website??

inland oak
#

a small addition of javascript into django template looks less thing to learn than alternative

ocean notch
#

I’m new to django so it’s weird seeing several tutorials use embedding

#

Almost all of the ones I’ve seen

inland oak
#

Django makes SSR by default

#

regular front end frameworks are usually CSR only

#

Next.js combines both types at the same time

ocean notch
#

Ahh yes I’d probably use next for Ssr

inland oak
#

it depends on the context of the project

ocean notch
#

Thanks sir

inland oak
#

I will prefer using CSR when possible

#

because it is faster and easier scalable in my opinion

#

but SSR sometimes is a must to have

ocean notch
#

Maybe for SEO right

inland oak
#

yup

ocean notch
#

You sound like a full stack?

inland oak
#

when we have a lot of dynamic data, extracted from database

#

nah, just learning

#

or more like... I am only responsible for backend
but at the moment partially responsible for front end decisions too, due to imcompetence of our front end person%

ocean notch
inland oak
#

I am wishing to learn being full stack as soon as possible though

#

planned already learning materials

#

to dive into front end)

ocean notch
#

Nice react is fun but I feel easier than backend?

inland oak
#

in order for search engines to index them, they should be pre rendered on the server side

#

with Django or with SSR front end frameworks like Next.js

#

and we are having like Dynamic hundreds amount of tutorials

#

which are made by users all the time

#

If those tutorials would be made only by our developers, as often as we produce commits to front end

#

we could manage with pre-rendering them, instead of going full SSR

#

it would allow us remaining in CSR way, while having server side builds only during project building into bunch of those static files

supple vault
#

anyway to make a websocket server in python without using the async lib / an alternative lib

inland oak
#

so... if tutorials are written by users = we should use Django or Next.js
if tutorials are written only as often as commits to front go with our developers, we can use React(with React-snap?), or Gatsbi

#

just recently researched this topic

#

Next.js is universal frontend framework though

ocean notch
#

That sort of makes sense :x though i don’t fully comprehend the part about doing CSR when commits to front by developers

inland oak
#

Next.js can be used as SSR, as CSR with prerender or as purely CSR
in any way mixing all those three paths

#

universal thing to use

quick cargo
#

Next is nice

#

but its definitely orientated for vercel to host

#

not saying vercel does a bad job as a host

inland oak
#

yeah I noticed that too

quick cargo
#

but it made geo deploying with other cloud systems more awkward than say a regular react app

#

its not a big issue, but it can cause issues

inland oak
# ocean notch That sort of makes sense :x though i don’t fully comprehend the part about doing...

for example we are using react, with pre render with react-snap
we keep updated three tutorials about A,B,C stuff.

due to pre-render, when we would write 'npm run build` command
those tutorials would be compiled into bunch of html/css/js files

which will not be changed until we next time re deploy our web site
that makes updating those tutorials for search-engines not more often than we make commit in essence

ocean notch
#

Ah I understand you explain really well

#

Kinda killed my existing questions about CSR vs SSR with regards to SEO

quick cargo
#

generally the fact it complies to 'static' assets makes life much easier with deployment in terms of latency

#

things like github, cloudflare etc... all offer geodeployed static content serving

#

which is a bigggggg plus for user experience

inland oak
#

yeah. that's why I would prefer always CSR over SSR

#

when I can

quick cargo
#

SSR has it's place, if you have a page which changes often but is easy to cache e.g. it's rendered once then served hundreds / thousands of times before rendering again, it makes more sense to SSR it and stick it on a edge worker or just let cloudflare cache 90%+ of the requests

worn shale
#

Not sure if this is relevant to the conversation but are the .xyz domains free?

worn shale
ocean notch
#

Yo dark if I know JS and react pretty well would it be hard to transition to django? I’m asking this knowing everyone learns at different pace but in general wondering about what you think transitioning to backend would be like if I already know a language and can pick up python decently fast

#

I know backend is trickier and there’s a ton to it

#

I have a year and a half in job exp only

#

In front end lol

#

Like I’m sure basic CRUD stuff and basic relationships can be learned easily and there’s even an ORM for queries

#

But there’s much more to backend

#

So ya..idk

inland oak
#

I can say that experience in backend would be much smoother, if you are friendly with Linux

ocean notch
#

Ahah you can pick up front end easy as long as you dive into JavaScript deep

inland oak
#

like a lot of back end things require easy navigation in Linux%

ocean notch
#

I use zsh same cli as Linux not sure if that’s what you mean

inland oak
#

in my opinion back end person should be able doing small stuff like
installing database for himself, setting webserver like nginx, able to attach ssl certificates, or getting domain for web site on his own
later goes stuff with caching through redis/memcached, celery which goes into redis database too, ci/cd with github/gitlab/jenkins piplines
docker with its many variations, docker-compose and e.t.c

#

all this stuff is easier when you are in linux

ocean notch
#

I’ve done a bit of node so I know how to do simple stuff other than like redis haven’t look into that yet

#

But some of those sound like dev ops stuff

inland oak
#

oh you worked with Node?

ocean notch
#

I’ve worked with micro services

inland oak
#

that would make transition to Django much easier

ocean notch
#

But not too In depth

inland oak
#

Node is basically backend like Django

ocean notch
#

Yeah but just the basics

inland oak
ocean notch
#

I can build api end points am familiar with some lingo

#

Ahh ok

#

I have it book marked hah

inland oak
#

like frontend person could be improvied with design ui/ux

ocean notch
#

Ohh

#

I see

#

Yeah I’m not too into uiux stuff that’s why I wanna get into backend now that I’m in between jobs

#

That makes sense

#

Can I add you? Maybe we can exchange two different sides of the coin sometimes

ocean notch
#

I’m no expert but I know js and react

#

Thanks

ocean notch
inland oak
#

we are using standalone react with django rest framework, both are completely separated

#

react, we are using Create React App verison

ocean notch
#

Oh sweet I was starting to feel like seldom any company does standalone

#

With django

inland oak
#

perhaps if I'll be knowing both things together

#

I'll consider going with embedded too ;b

#

may be

ocean notch
#

Ahaha I know there’s some benefit to embedded

#

But I prefer standalone

#

Easier to separate the logic

#

Like being able to use react router instead of relying on backend

#

For the URL’s

inland oak
#

well, I would go as first step for learning standalone front anyway

#

because it would make better dive into frontend

#

once I'll learn standalone, I'll consider using other ways

ocean notch
#

Nice that’s probably good to know both

inland oak
#

I am going to start on learning frontend on the next weekends probably

#

on thursday going to arrive book which I plan to use getting started

#

Head First O'Reilly Html + CSS

#
  • Head First O'Reilly Javascript
ocean notch
#

Haha nice dude like I said I’m in between jobs so hit me up anytime

#

For JS

#

Or React

inland oak
#

heh, it would be probably not the super fast learning

#

like I am having a big queue to learn of backend + devops things%

ocean notch
#

I’m reading effective python and doing some tutorials on django

inland oak
#

plus working at the same time

ocean notch
#

Ahh

#

That sounds like a load

#

I’m doing full on backend right now

slow gazelle
#

is flask being used in production?

inland oak
slow gazelle
#

or should i go straight in django

#

oh ok

inland oak
#

flask is nice to learn and getting started though ;b

slow gazelle
#

yeah i got bored thou xD

inland oak
#

Django is full battery included framework

#

a lot of things pre setup for you

#

a little bit... easy to get used to it%

slow gazelle
#

when do you think is good for using flask? in my observation i think its good to used for simple services like firebase

ocean notch
#

Ya also a lot more magic to understand and gotta dive in the source or docs a lot haha

slow gazelle
#

or still django

inland oak
#

shrugs
I am not sure what for flask is useful. I did not get it tbh.

#

before its major upgrade it was not useful in my opinion

#

because any framework had some feature that made it better than flask in every way

#

with last major flask upgrade, perhaps it will stop being this way

slow gazelle
#

yes , i'm only concern is the job market

#

so django it is

inland oak
#

then go for django 😉

#

I heard Fast API is useful too though

#

noticed often enough in job positions
quite popular to be used in commercial too

warm igloo
#

I use Flask a lot. I really like FastAPI as well. Django often is just way more magic than I want to deal with.

manic frost
#

but it seems that Django is more popular.

native tide
#

hiii guys

#

i want to ask u if web scraping legal or no????????

snow cosmos
#

it will vary depending on the website

snow cosmos
#

if you see "are blocked/disallowed" next to "User-agents" then it's illegal

gentle jasper
#

What is Class Meta used for?

class Category(models.Model):
    name = models.CharField(max_length=255)
    slug = models.SlugField()
    
    class Meta:
        ordering = ('name',)```
surreal portal
primal thorn
#

i made a custom users model but the "groups" and "permissions" are not there, how do i add them

#

this is what i mean

violet dock
#

how to run a function once my api server is started in flask?

ionic raft
#

Anyone here have experience using PyCharm and bootstrap grid?

#

Because while I can get grid to work in Codeply....even with copy/pasted html I simply CANNOT get columns to stack properly...

<div class="row">
    <div class="col-lg-6">Col</div>
    <div class="col-lg-6">Col</div>
</div>```
#

prints
col
col

no matter how wide the browser...and it's breaking my brain. Like I said, this works in Codeply...but Pycharm? Not a sign of it working. I also have```html
head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="../static/css/bootstrap-grid.css" type="text/css">
<link rel="stylesheet" href="../static/css/bootstrap.css" type="text/css">

</head>```

#

So I know I'm calling the stylesheets. I've been following a video tutorial and even copy/pasting this isn't working! I'm getting to the point of ditching PyCharm to be quite frank

#

I really need Grid to work, and Pycharm refusing to render is driving me nuts

cerulean vapor
#

what do yuo mean by getting this to work in PyCharm? are you using some kind of HTML previewer?

ionic raft
#

Well, Flask...but while I'm building out the page and learning Grid in Bootstrap Pycharm has a browser function

cerulean vapor
#

also what version of bootstrap

ionic raft
#

4.6.

cerulean vapor
#

I would just open the flask app in whatever browser your nomally use

#

I have no idea how PyCharm does web rendering

ionic raft
#

I've got the right version of css file. And I know I do because I copy/pasted css from codeply...where GRID works!

#

Doesn't work in Flask either!

#

But codeply...perfect. Copy pasted html and css files...works on Codeply. Pycharm, no dice! GRRR

cerulean vapor
#

open your inspector and make sure the css files are loading

ionic raft
#

Good idea...

cerulean vapor
#

you might want to use nonrelative URLs for them

#

e.g., href="/static/css/...."

ionic raft
#

Yes....loading

#

Showing css in "Styles"

#

Hm....bootstrip-grid.css isn't showing tho

#

OMG!

#

So, yeah....you have to make sure that bootstrap-grid is in the header

#

Thank you @cerulean vapor
I'd already checked for the loading css file, but missed that they separated out grid as it's own css file!

cerulean vapor
#

YW

violet dock
#

!hlep

primal thorn
#

is it better to have a seperate "profiles" table that is a one to one to the users or just put everything in one table

ocean notch
#

i think its better to put profiles in a separate table and use signal to create it upon user creation

inland oak
native tide
#

hey, anyone wanna help me in making a website?
Dm me

austere glen
#

anyone knows how to make mcq (multiple choice questions) quiz with html?

obtuse trout
#

Hello ppl, I'm pushing django website on Heroku, only one of my webpages - 'dashboard' throws Server Error 500. I checked the templates correctly according to WhiteNoise configs, set debug=False, migrated the db. Can anyone help me with this?

#

I suspect line 13 is probably the cause of 500 error

surreal portal
#

Although it must use Django v2

ivory bolt
obtuse trout
obtuse trout
#

is there something I'm possibly missing out..?

ivory bolt
#

I'm not entirely sure, though I guess it is
return redirect('dashboard/<int:{}>/'.format(request.user.id))

#

check this out

#

I'll get back to you with a better answer

grand harbor
#

if it was flask i would use it like this @app.route("/post/<string:slug>"

obtuse trout
obtuse trout
#

url is like this now, it doesn't take <int:> / reads it as a string

ivory bolt
#

check out the url parameters for django in their documentation

obtuse trout
#
@login_required(login_url='login')
@ninja_only
def dashboard(request, pk):

    total = Project.objects.all().count()

    # Completed Projects - count()    
    scratch_completed = Activity.objects.filter(user_id=pk).filter(topic_id=1).count()
    circuits_completed = Activity.objects.filter(user_id=pk).filter(topic_id=2).count()
    robotics_completed = Activity.objects.filter(user_id=pk).filter(topic_id=3).count()
    lego_completed = Activity.objects.filter(user_id=pk).filter(topic_id=4).count()
    typing_completed = Activity.objects.filter(user_id=pk).filter(topic_id=5).count()

    data = {
        'circuits_total': circuits_total,
        'robotics_total': robotics_total,
        'lego_total': lego_total,
        'typing_total': typing_total,
        'total': total,
    }
    return render(request, 'webpages/dashboard.html', data)
#
def ninja_only(view_func):
    def wrapper_function(request, *args, **kwargs):
        group = None
        if request.user.groups.exists():
            group = request.user.groups.all()[0].name

        if group == 'admin':
            return redirect('scorecard')

        if group == 'ninja':
            return view_func(request, *args, **kwargs)
            
        else:
            return redirect('login')
    return wrapper_function
upbeat umbra
#

can I use flask application builder (F.A.B) as admin panel for my project?

inland oak
covert kernel
indigo vessel
#

hello

digital hinge
#

Does anyone know how to get this working with A SAMACCOUNTNAME?

ivory bolt
#

and is there a way to change the url to uuid or something

#

I'll check it out and let you know in a bit

obtuse trout
#

like we use in password-reset-confirm?

#

path('reset/<uidb64>/<token>/'

obtuse trout
native tide
#

thats why

#

i felt stupid

obtuse trout
#

@ivory bolt can we use HttpResponseRedirect instead of redirect ?

surreal portal
#

Has anybody else manipulated django-filter with DRF? Because I'm kinda lost at a filter's creation

#

All i want is to have options to filter on the date

primal thorn
#

i followed the docs for the phonenumbers field and imported it like this ```python
from phonenumber_field.modelfields import PhoneNumberField

but it still says ```ModuleNotFoundError: No module named 'phonenumbers'```
#

i installed it like this pip install django-phonenumber-field

obtuse trout
#

just write - pip install phonenumbers

scarlet kiln
#

does anyone know how flask's url_for() works? My understanding is that it supplies the route in the function decorator after searching for a function with the name you supply to url_for() but flask/jinja keeps insisting it can't find it

surreal portal
scarlet kiln
#

I did

#

and I believe I don't actually have to

#

since it's supplied automatically by flask when reading templates

#

or something like that

surreal portal
obtuse trout
#

Anyone - what would you write @ here in url(r'^dashboard/<here>') so that it accepts all positive numbers?

scarlet kiln
#
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>test</title>
    <link href="{{url_for(send_stylesheet)}}" rel="stylesheet"/>
</head>
<body>



waow
</body>
</html>```
#

gives me jinja2.exceptions.UndefinedError: 'send_stylesheet' is undefined

#

wait

#
from flask import Flask, abort, redirect, render_template, request, send_file, jsonify, url_for

app = Flask(__name__)


@app.route("/")
def index():
    return render_template("test.html")


@app.route("/static/styles.css")
def send_stylesheet():
    return send_file("static/styles.css")


if __name__ == '__main__':
    app.run(debug=True)

#

this is the correct py file

#

how can jinja not find the send_stylesheet?

opaque rivet
scarlet kiln
#

oh so even within django I need to denote it as a string

#

doesn't help

#

wait

#

mb it didn't reload because

#

I didn't add the auto reload parameters

opaque rivet
#

same error?

scarlet kiln
#

nono it worked

#

now I need to figure out

#

why it didn't work in the main project even after making that adjustment

#

never mind you just solved my problem

#

I was chasing my tail on this for so long

#

because I transferred this from a google colab to my local environment

#

and was sure I'd gotten some esoteric configuration wrong

#

that I didn't consider the obvious

#

thank you <3

#

can I ask a follow up question?

opaque rivet
#

sure

opaque rivet
scarlet kiln
#

I am not trying to regex

obtuse trout
#

is it correct? @opaque rivet

scarlet kiln
#

I am having trouble getting something from request.form

opaque rivet
scarlet kiln
#

oh you weren't answering me

#

mb

opaque rivet
scarlet kiln
#
function onDomLoaded() {
                    document.getElementById("filterbutton").addEventListener("click", function() {
                      var weekdays = [];
                      $("#dayfilter input:checked").each(function() {weekdays.push($(this).val())});
                      $.post("{{url_for('filter_map')}}" , JSON.stringify({"weekdays": weekdays}), onAjaxResponse, "html" );
                    });
                  }```
#

I use this code to post the values of checked checkboxes in an array

#

and used jquery post to send it

#

but it somehow seems to be the incorrect format for flask

#

it sends the request with the form data

#

but when I try to use request.form["weekdays"] I get a KeyError

#

is stringifying it wrong?

#

it sends a different error if I don't stringify it

#

but it has an error in either case

opaque rivet
#

hmm, seems that request.form is empty because flask doesn't recognize that you submitted a form.
I'm pretty sure you could access request.data and your data will be there. Looks more like an API call than a form submit to me

scarlet kiln
#

so am I doing something stylistically wrong?

opaque rivet
#

not sure. Have you checked if request.form is actually empty? It could be that Flask is detecting a form, but the payload is a string because you did JSON.stringify({"weekdays": weekdays}) so there are no keys to be accessed

obtuse sedge
#

Oh my gosh today all the channels are full

primal thorn
scarlet kiln
#

@opaque rivet the thing is there is something in request.form

#

and I figured it would be empty if it wasn't recognized

#

lemme trying it now

obtuse trout
primal thorn
opaque rivet
#

check the type of its contents, it might be a string since you're doing JSON.stringify({"weekdays": weekdays}) @scarlet kiln

obtuse trout
#

make sure its activated when you install

primal thorn
opaque rivet
primal thorn
obtuse trout
#

probably

primal thorn
#

i tried using the command pip install django-phonenumber-field[phonenumberslite] but it says the package does not exist

scarlet kiln
#

this is what's in request.form

#

I am not sure how to work with it

#

and I feel like I'm doing something wrong in terms of style

#

I removed stringify

#

let's see what happens if I put it back

primal thorn
scarlet kiln
#

this is with stringify

opaque rivet
# scarlet kiln

yeah, my guess was right. Your request.form payload is a string

#

your error lies here JSON.stringify({"weekdays": weekdays})

scarlet kiln
#

so you're saying I should remove stringify?

#

either way it doesn't seem to enter request.form correctly

#

or do I need to modify the js object I'm sending as the payload?

opaque rivet
#

that's up to you. You can do: json.loads(request.form)['weekdays'] to convert the str into a dict

scarlet kiln
#

so I was sending valid json

#

but flask doesn't know what to do with it

#

because as far as it knows it's just a string

#

the issue is

#

request.form is a ImmutableMultiDict

#

not a string

#

and I'm not sure how to access what's inside the object

#

and I get keyerror if I try to do request.form['weekdays']

#

so I think I have to supply something different in the jquery post

#

can I index into a dict?

#

keyerror

opaque rivet
#

yeah, supply something else in the jquery post. request.form is a ImmutableMultiDict but its contents is a string...

maybe you could do something like:

mutable_arr = [data for data in request.form]
json_string = mutable_arr[0]
data = json.loads(json_string)
#

if request.form is an iterable

#

I don't work with flask so I don't know too well

primal thorn
#

how do i remove the first name, lastname, and email fields from the user model

#

but i want to keep all the other fields like email, password and permissions

surreal portal
#

Trying to follow this

obtuse trout
obtuse trout
autumn yoke
#

does anyone know about any android app development course

subtle frost
autumn yoke
#

yeah ikk
i just thought if by anychance anyone knew

subtle frost
autumn yoke
#

ahh thanks
see asking here wasnt a bad idea

glacial sky
#

aoba

#

someone?

subtle frost
#

what's the error?

glacial sky
#

idk

subtle frost
#

mouse over it

glacial sky
#

look

subtle frost
#

yea you can't do it

#

maybe try python self.botao1.place = (2.0, 2.0)

glacial sky
#

nice

#

work, but wheres my button??

subtle frost
#

maybe check the docs for Button. Dunno how tkinter works.

ripe lodge
#

did anyone do corey schafers django series, and if yes did you like it?

subtle frost
#

@ripe lodge you tried the Django docs and getting started tutorial? There's enough info on there to be a pro 💪

glacial sky
#

whats the difference of tkinter of django?

ionic condor
#
self.botao1.place(relx=2, rely=2.0)```
subtle frost
#

tkinter is a gui (like desktop apps)

#

django for making websites with a backend

subtle frost
ripe lodge
glacial sky
subtle frost
subtle frost
#

django/python for the backend

glacial sky
#

i just wanted my button ):

subtle frost
ripe lodge
calm plume
# glacial sky like html?

No, it works alongside html. You use html, css, and maybe js for the frontend, and you could use django for the backend

subtle frost
glacial sky
#

its working but my button it disappeared

subtle frost
glacial sky
calm plume
#

I'm not really sure how to explain it

ripe lodge
#

but i hear the corey schafer series is supposed to be good

subtle frost
ionic condor
calm plume
#

He's a wonderful teacher

ripe lodge
#

ah that's good to hear, i'll start rn. ty!

glacial sky
ionic condor
ivory bolt
#

wouldn't recommend that

viral ember
#

Hi
i don't know if this is the right chanel, but anyways:
I have 2 apache webserver and want to redirect from the first to the second server everytime someone gets on the website. Also show some basic text so that a user can see that is was redirected to another site.

(it's nothing serious, just for fun 😄 )

#

but within a network and ip's (like i said, just for fun)

inland oak
#

Then add simple html syntax to this index.html for delayed redirect, I think there should be one

viral ember
#

thx 🙂 i'll try it out

upbeat umbra
#

Thanks

viral ember
#

it works, but when it tries to reidrect, it just puts the text infront of the other which leads to a wrong adress... 😄

upbeat umbra
#

Is there a way around that?

upbeat umbra
viral ember
#

btw do you know how i can add some text (sorry i'm a complete noob at this 😄 )

upbeat umbra
#

Sorry I was not keen, I am replying to the wrong message

shadow holly
#

Tho I found it easier to start with Flask... it helped me understand the necessary concepts in web development without having to start a project full of 10, 15 files that I didn't know anything about

grand harbor
#
def statement():
  if a:
    a=False
    statement()
  else:
    a=True
    statement()
statement()
if a:
  print('Flask is better than Django')
else:
  print('Flask is still better than Django')
dusk portal
#

@inland oak hello bro , i feel like i'm stuck not learning anything new or just learning same thing's im different framework's as u and many suggested me when i was Doing Flask if u wanted to go to advaned get to Django is it structured and stuff like that now i have done , 1 yt video 8:30 hrs and 8 docs and made 1 that docs project and 1 todo app from yt and what should i do , i wanted to learn how can i use react with django that api i want to learn i want to learn postgresmysql and to use it on django how can i use phpmyadmin on django stuck bruh feeling like i cant make progress

#

plz help

ivory bolt
#

You can try building a simplified twitter clone

dusk portal
ivory bolt
#

I mean, yeah you don't, but you also kind of do

#

You already know how to handle authentication, create models and fields

#

linked tables

#

and managing requests and urls right?

#

Do you know how to create an API?

#

See -- here it is! Try to look at the things you know and those you DON'T. In your case, I assume it's:

  1. Creating an API
  2. Writing asyncrhonous code -- using websockets or updating data real time
  3. Creating a frontend
#

I can hook you up with all the resources needed to do just that -- I also have a tutorial SPECIFICALLY for just that (react and Django twitter clone app)

#

I'll send it to you separately if you want @dusk portal

#

I suggest you try to do something you've always wanted to and RESEARCH how to do it -- it's how I learnt and I honestly think it's the best approach

dusk portal
#

yes plz @ivory bolt

#

idk api and stuff

#

yes ik databases urls and stuff

ivory bolt
#

see, there you go!

#

I'll send you whatever you need to get started tomorrow morning, so stay tuned on the server!!

misty goblet
#

Using the Django rest frameworks's serialisers is there a way to call a nested objects update and create methods?

#

that would let me do something like this:

class GuildSerialiser(ModelSerializer):
    snowflake = IntegerField()
    channels = ChannelSerialiser(many=True)
    roles = RoleSerialiser(many=True)

    class Meta:
        model = DiscordGuild
        fields = ['snowflake', 'channels', 'roles']
        list_serializer_class = CreateUpdateDeleteListSerialiser

    def update(self, instance, validated_data):

        self.channels.update(instance.channels, validated_data["channels"])
        self.roles.update(instance.roles, validated_data["roles"])```
#

it seems that the serialiser fields get removed when they are created

#

and there you can access them through self.fields.channels that doesn't work properly

inland oak
#

it is possible

#

but I cheated

misty goblet
#

I have 'cheated' as well now

misty goblet
# inland oak um yeah

I have this horrid function ```python
def create_update_deleteList_serialiser_update_substituation(model, instance, validated_data):
# Maps for 'snowflake->guild instance' and 'snowflake->guild data' item.
instance_mapping = {item.snowflake: item for item in instance.all()}
data_mapping = {item['snowflake']: item for item in validated_data}

# Perform creations and updates.
output = []
for snowflake, data in data_mapping.items():
    item = instance_mapping.get(snowflake, None)
    if item is None:
        output.append(model.objects.create(**data))
    else:
        output.append(item)

# Perform deletions.
for snowflake, item in instance_mapping.items():
    if snowflake not in data_mapping:
        item.delete()
return output```
misty goblet
#

that isn't using the nested serialiser though

#

it is creating the nested object in the parent

inland oak
#

link surely uses nested serializer

misty goblet
#
    def create(self, validated_data):
        tracks_data = validated_data.pop('tracks')
        album = Album.objects.create(**validated_data)
        for track_data in tracks_data:
            Track.objects.create(album=album, **track_data)
        return album```
#

where is the link?

#

it doesn't call the nested create

#

it is only using the nested serialiser for validation

#

because this is horrid: ```python
def create_update_delete_listserialiser_update_substituation(model, instance, validated_data):
# Maps for 'snowflake->guild instance' and 'snowflake->guild data' item.
instance_mapping = {item.snowflake: item for item in instance.all()}
data_mapping = {item['snowflake']: item for item in validated_data}

# Perform creations and updates.
output = []
for snowflake, data in data_mapping.items():
    item = instance_mapping.get(snowflake, None)
    if item is None:
        output.append(model.objects.create(**data))
    else:
        for i, value in data.items():
            if i == "snowflake":
                continue
            setattr(item, i, value)
        item.save()
        output.append(item)

# Perform deletions.
for snowflake, item in instance_mapping.items():
    if snowflake not in data_mapping:
        item.delete()
return output```
#

especially when this functionality is already implemented in the nested serialiser

#

now it is saving correctly

#

but I cannot access the serialiser's .data

#
AttributeError: Got AttributeError when attempting to get a value for field `snowflake` on serializer `GuildSerialiser`.
The serializer field might be named incorrectly and not match any attribute or key on the `NoneType` instance.
Original exception text was: 'NoneType' object has no attribute 'snowflake'.```
misty goblet
native tide
#

I am trying to send an object via WebSocket and am unable to do so. I want to send an object to js WebSocket on a page

#

How to convert to string this object, or something what prevent to send

desert estuary
#

https://www.youtube.com/watch?v=44PvX0Yv368&list=PL-osiE80TeTs4UjLw5MM6OjgkjFeUxCYH&index=6
i couldn't get what and why he's doin so and what's that thing is doin is called cuz when i googled it with flask it gave me the application structure

In this Python Flask Tutorial, we will be learning how to restructure our application into a package rather than running from a single module. This has major benefits in terms of importing modules across our application. Let's get started...

The code for this series can be found at:
https://github.com/CoreyMSchafer/code_snippets/tree/master/Pyt...

▶ Play video
#

when im calling the first module so i can use it in the second and vice versa in the vid he used main and it did work but didn't get his explanation also i googled it and people used a different method

if TYPING_CHECKING
  import xxxxx or something idk

but that one ssems a bit tricky well both of those seemed tricky

dusk portal
#

viewspy def contact(request): if request.method=='POST': name=request.POST.get('name') email=request.POST.get('email') phone=request.POST.get('phone') message=request.POST.get('message') entry=Contact(name=name,email=email,phone=phone,message=message) entry.save() return render(request,'app1/contact.html') urlspy path('contact/',views.contact,name='contact')

#
ValueError at /contact/
The view app1.views.contact didn't return an HttpResponse object. It returned None instead.
Request Method:    GET
Request URL:    http://127.0.0.1:8000/contact/
Django Version:    3.2
Exception Type:    ValueError
Exception Value:    
The view app1.views.contact didn't return an HttpResponse object. It returned None instead.
Exception Location:    C:\essentials\python\lib\site-packages\django\core\handlers\base.py, line 309, in check_response
Python Executable:    C:\essentials\python\python.exe
Python Version:    3.9.4
Python Path:    
['C:\\Users\\91834\\PycharmProjects\\dj_todoapp\\TODO',
 'C:\\essentials\\python\\python39.zip',
 'C:\\essentials\\python\\DLLs',
 'C:\\essentials\\python\\lib',
 'C:\\essentials\\python',
 'C:\\essentials\\python\\lib\\site-packages',
 'C:\\essentials\\python\\lib\\site-packages\\win32',
 'C:\\essentials\\python\\lib\\site-packages\\win32\\lib',
 'C:\\essentials\\python\\lib\\site-packages\\Pythonwin']
Server time:    Tue, 22 Jun 2021 17:12:33 +0000```
#

error

#

done!! working now

ivory bolt
#

oh k

#

did you change your url? Curious to see how you solved it

dusk portal
ivory bolt
#

I don't see an iteration…do you mean the if statement?

#

ohh yea

#

wow k yea you didn't specify anything for a GET request so

nimble radish
#

is there any way to interact with a django database model outside the app

#

ex. i'd like to add some entries to the database from a separate python script

dusk portal
#

my first question is why u wanted to do that @nimble radish

#

cez it doesn't make any sense ;-;

nimble radish
#

I'm trying to figure out if for the separate part if I need to use actual SQL queries, and if I do, then maybe I shouldn't use the Django models at all. I'm not too sure, it's my first time using Django.

dusk portal
#

I shouldn't use the Django models at all. why

nimble radish
#

Are you reading my posts? I said I don't know what I'm doing, I'm using Django for the first time, and I'm just trying to get ideas on whats possible.

native tide
dusk portal
#

any django exp. dev?

#

show code and error

#

i was pretty good in flask

#

post.description= updateoriginfo.description.data #after this line where db.session.add line where is var u passing all the items

#

are u sure u r doing right?

glacial sky
#

tks @subtle frost I managed to finish my mini project for today , if you can give a star please

native tide
# dusk portal

its like the db didnt receive an email value because the null value not allowed by default

native tide
# dusk portal so what should i do

if u dont want the email to be required
u need to provide default value for email field, like default=''
or allow the the db to store it as null, by doing null=True

#

also to tell the html its allowed to be blank, put blank=True

dusk portal
#

ohk

obtuse trout
supple vault
#

is there a library for websockets that isnt async

#

server not client ^

ivory bolt
# dusk portal

you can't leave email empty OR you are using an email field right now

mellow stone
#

Hi does anyone have any idea on how to fix this error ?
at=error code=H10 desc="App crashed" method=GET path="/"

#

this occurs when I deploy my app

#

through herkou

warm igloo
#

did you specifically look at your heroku app's logs?

#

You should be able to get more traceback info there

spare dragon
#

weird question just having trouble finding an answer

#

anyone know Kotlin in here?

naive rock
#

So I have an async routine, that sometimes works and other times fails.
Couple of time when it failed it returned 500 status code, which means the server is temporarily down?

#

This async routine worked fine when it made around 600 async api requests. But now it's making around 800 async api requests. Could the increase in async calls be a problem?

gritty cloud
#

you may have unintentionally overloaded the server

#

or the service the api runs on may be overloaded bc of ur requests

#

also a 500 means the server went and did something weird

naive rock
#

It's moments like these I just think to myself programming is more about hacks then programming.

I felt more so this way about Frontend. Python and backend for the most part is well thought out logic with fewer "hacks".

vestal hound
#

some servers will return 503 in case of overload

vestal hound
#

then you can interact with the database using the ORM

#

ultimately it's just SQL tables so you can write raw SQL if you want, but I don't see why you'd want to

nimble radish
nimble radish
#

i'll look into that though, thank you.

vestal hound
#

you know how you can run, for example

#

./manage.py makemigrations?

#

that's a management command

#

defined in Python code

#

that just does stuff with the Django framework loaded

#

you can do the same thing in your own code

#

so you have access to all of Django's capabilities

#

including the ORM, so you can work with model instances and save them etc. and it'll take care of writing to the database for you

naive rock
thorny hollow
#

Hey I have a question, if I know that I can create a whole website using Django, I have no experience in this library, but what I know about it that we can create websites on it, my question is, so when we inspect the web page of it we will get a python code ? Or how ?

wooden ruin
#
function addStar() {
    const geometry = new THREE.SphereGeometry(0.25, 24, 24)
    const material = new THREE.MeshStandardMaterial({ color: 0xffffff})
    const star = new THREE.Mesh(geometry, material)
    const [x, y, z] = Array(3).fill().map(() => rand(50)) // random float from -n/2 -> n/2
    star.position.set(x, y, z)
    scene.add(star)
}
Array(200).fill().forEach(addStar)

currently messing around with three.js, but there's some weird array stuff that I'm seeing when I follow a tutorial. what does Array(200).fill() do, and how does map work?

primal thorn
#

what is the opposite of the @login_required method, i want to do it so that if the user is logged in

inland oak
#

or you mean is_authenticated?

#

anyway, it depends on used library

violet dock
#

i have a question about flask apscheduler. is the time get trigger once the function executed(which means it triggers the time once it executed the first line of the function) or after the function executed(which means it triggers the timer once it finished executed the last line of the function)?

dusk portal
#

unable to fix it

trail crest
dusk portal
#

I am using default sqlite 3 @trail crest

trail crest
#

can u expand the local vars thing?

#

or show ur sql query code

dusk portal
#

@trail crest sorry for late reply

#

def contact(request):
    if request.method=='POST':
        name=request.POST.get('name')
        email=request.POST.get('email')
        phone=request.POST.get('phone')
        message=request.POST.get('message')
        entry=Contact(name=name,email=email,phone=phone,message=message)
        entry.save()
    return render(request,'app1/contact.html')
        ```
#
path('contact/',views.contact,name='contact')```
#
class Contact(models.Model):
    name=models.CharField(max_length=50)
    email=models.CharField(max_length=50)
    phone=models.CharField(max_length=50)
    message=models.TextField()

    def __str__(self):
        return self.email```
west mulch
#

@dusk portal can you explain me how to POST using forms

dusk portal
#

i also learned something's in very difficult way and learned myself and some ppl helped in between , so that day i promised if anyone will ask me anything im gonna explain himm clearly and with full concepts and my 101% efforts

west mulch
#

i followed some youtube tutorials and they all seem to use postegresql for post but i want to do it in sqlite

#

if you can share a project with me i could learn from it

eternal flower
#

I am getting this error,can somebody help?(django)

dusk portal
eternal flower
#

bruh

dusk portal
#

r u new to django? @eternal flower i mean less then 1 month?

dusk portal
#

lol

dusk portal
eternal flower
#

youtube

dusk portal
#

👀

eternal flower
#

docs are boring

dusk portal
#

do u made any todo app? @eternal flower

#

todo project

eternal flower
dusk portal
#

ohh

eternal flower
#

but now I got this error

dusk portal
#

let's make together in vc , with vs code live share extension will be fun learning together i can help u so i will revise and u can help me

#

how's the plan?

eternal flower
#

good

dusk portal
#

and i can show u docs power

eternal flower
#

:D

dusk portal
eternal flower
#

yea

dusk portal
#

add friend

#

yay!!!

#

u from?

unreal badge
#

Python can be used for web dev ??

#

If yes How ?

#

And in what

raw compass
#

Yes

#

Do the flask, django or fast-api tutorial depending on your needs.

#

You still need to use html, css and js for the front end . Or is that what you want to avoid

stark tartan
#

||how to get the value of previous that object have in update form for further validations of field ||

inland oak
stark tartan
inland oak
stark tartan
inland oak
# stark tartan for django

https://stackoverflow.com/questions/6862250/change-a-django-form-field-to-a-hidden-field
google hidden fields for django

https://docs.djangoproject.com/en/3.2/topics/forms/
they are described in their official wiki as well

{# Include the hidden fields #}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{# Include the visible fields #}
{% for field in form.visible_fields %}
    <div class="fieldWrapper">
        {{ field.errors }}
        {{ field.label_tag }} {{ field }}
    </div>
{% endfor %}
inland oak
#
from django import forms

from .models import Player


class PlayerForm(forms.Form):
    name = forms.CharField(widget=forms.HiddenInput())
#

Actually scratch it

#

hidden fields probably will not work for this case

#

better or may be it will

#

if it will not work, store previous values in query params or cookies or smth

#

storing in cookie sounds actually the easiest way

#

cookie can be well managed with backend

stark tartan
#

i plan to manage it from views

#

and send messages for error is it good??

edgy sable
#

can someone help me and tell me how to get my flask app to work with my domain?

inland oak
#

is it just domain and nothing else?

#

a regular solution... would be getting vps server

#

getting ssl certificates for your domain

#

and deploying on the vps server, your app with attached ssl certificates

#

while setting in your domain provider, things to point to your VPS ip address