#web-development

2 messages ยท Page 191 of 1

past cipher
#
for i in teacher_courses:
        fetch = CourseWork().fetch_course_work_by_id(i.course)
        course_name = str(i.linked_teacher.course_name)
        
        for cw in fetch:
            for x in grade_info:
                for p in x:
                    if(course_name) in x:
                        course_exists = True
            
            
            if(course_exists == True):
                new_dict = {}
                new_dict['student'] = f'{cw.submission.user_submissions.first_name} {cw.submission.user_submissions.last_name}'
                new_dict['coursework'] = cw.name
                new_dict['status'] = cw.submission.status
                try:
                    new_dict['comment'] = cw.submission.submission_grade.comment
                except:
                    new_dict['comment'] = ''
                try:
                    new_dict['grade'] = cw.submission.submission_grade.score
                except:
                    new_dict['grade'] = ''
                grade_info[0].update(new_dict)
                print(grade_info)
                input()
            else:
                y = {}
                y[course_name] = {} 
                y[course_name]['student'] = f'{cw.submission.user_submissions.first_name} {cw.submission.user_submissions.last_name}'
                y[course_name]['coursework'] = cw.name
                y[course_name]['status'] = cw.submission.status

                try:
                    y[course_name]['comment'] = cw.submission.submission_grade.comment
                except:
                    y[course_name]['comment'] = ''
                try:
                    y[course_name]['grade'] = cw.submission.submission_grade.score
                except:
                    y[course_name]['grade'] = ''

                grade_info.append(y)
#

I need to check if the course already exists in the dict. For example "English"

#

if it does, it should create a new nested dict, and attach it to "English"

#

grade_info[0].update(new_dict) causes the problem of incorrect Syntaxt. It doesn't add the new_dict as a nested dictionary

#

I feel like banging my head against the wall haha. Been stuck on this for several hours now

opaque rivet
#

What is grade_info[0]

past cipher
#

well grade_info is list containing all the dicts that it loops through

glad egret
#

I have created a text form in HTML and now I want to export the text typed there to my Python code from where I will store them in a MySQL database. which framework is the best for this task.

#

?
I have heard name of Django, but in it's introductory video every thing they said was about managing multiple pages, urls classes parsing etc. which I dont need now

#

so can you guys tell me the specefic things I need to know from Django to acheive my goal?

native tide
# glad egret so can you guys tell me the specefic things I need to know from Django to acheiv...

use flask, its newbie friendly and will help u learn concepts and understandings https://www.youtube.com/watch?v=mqhxxeeTbu0&list=PLzMcBGfZo4-n4vJJybUVV3Un_NFS5EOgX&index=1

Welcome to the first flask tutorial! This series will show you how to create websites with python using the micro framework flask. Flask is designed for quick development of simple web applications and is much easier to learn and use than django. If you are less experienced with python and want to learn how to make websites flask is the right to...

โ–ถ Play video
native tide
#

that can handle more traffic

glad egret
#

(how can I pronounce your name), according to you, learning what is necessary is a good practice or we should learn everything about a thing?

#

also I have already written the code for my page using HTML, so can I use it directly or I have to rewrite the entire code again in flask's code?

plucky wadi
#

how many django projects can I deploy on heroku's hobby dyno ?

chilly falcon
#
def put(self,request,pk):
        serializer = StockModelSerializer(data = request.data,partial=True)
        if serializer.is_valid(raise_exception=True):
            stock = self.get_object(pk)
            print("working")
            print(request.data)
            print(serializer.data)
            print(serializer.validated_data['quantity'])
            serializer.update(stock,serializer)
            
            response={
                "data": StockModelSerializer(stock).data 
            }
            return Response(response,status=status.HTTP_200_OK)

output

{'quantity': 5000, 'rate': 45, 'manufacture_date': '2020-5-10', 'expire_date': '2022-5-10', 'company_id': 1, 'medicine_id': 1}
{'quantity': 1, 'rate': 45, 'manufacture_date': '2020-05-10', 'expire_date': '2022-05-10', 'company_id': 1, 'medicine_id': 1}
True
True
1
True
45
#

why my quantity is taking boolean value

#

it in intergerfield in django

#

models.py


class Stock(models.Model):
    company_id = models.ForeignKey(Company,on_delete=models.PROTECT)
    medicine_id = models.ForeignKey(Medicine,on_delete=models.PROTECT)
    quantity = models.IntegerField()
    rate = models.IntegerField()
    manufacture_date = models.DateField()
    expire_date = models.DateField()
#

can anyone help me

dense slate
#

How would I open a single Django endpoint for an external service to point at if I am using a FE front end? Since I am not using URL routes generally in this situation, is there a best way to open an endpoint? Do I need to just open the port and point at the django route/path as usual?

#

I have the BE port blocked via firewall at the moment.

#

Should I route a specific url through nginx, or just open the port and access that directly?

glad egret
dense slate
glad egret
tall plaza
#

anyone here using django

#

?

#

guys like i am sending image as response into base64 using django. image already are above the 100 mb. but when i see its response in thunder client. thunder client is hanging. though i am getting output

sonic island
#

a week is enough to learn from basics to making a simple CRUD API

ionic raft
ionic raft
glad egret
ionic raft
# glad egret what is dynamic? related to CSS based animations?

CSS is about style (form). Dynamic is another word for...I have data that I want to render on the page that changes. In other words, if I have a copyright footer with the year, and I want to keep the year always up to date every time the page opens, then that data changes. In other words, dynamic text that changes depending on the user's context.

glad egret
ionic raft
glad egret
ionic raft
# glad egret my goal

Either Flask or Django is an option. However, if you've got just the one main application, I'd recommend Flask.

glad egret
#

in flask do we need to include sql commands in python code? or flask has some included things>

ionic raft
#

Flask is much easier to get setup with, and provides all the functionality (based on what you've shared) that you'd need.

ionic raft
#

"In Flask web applications, to manipulate databases, we can use SQL and Object Relational Mapping (ORM). An ORM makes writing SQL queries easier for a programmer, because it enables us to write queries in an object-oriented language, and then ORM automatically translates it to SQL and retrieves the result as an object."

glad egret
ionic raft
#

Django also uses ORM. I've used ORM quite a bit. There is still a learning curve.

glad egret
#

what if I wish to use sql exclusively

ionic raft
#

In my experience, it's very powerful. I've been working with ORM since July. You can check the url in my profile to see the end result

glad egret
#

like storing user's input in the HTML page into a variable and then work with it normally like a simple sql and python hybrid code. Actually I am a bit experienced in SQL,

glad egret
ionic raft
#

And I have no SQL experience to speak of

glad egret
#

so now you know my goal, I want to bring user's input myfrom html page into my code. my html page just act as a simple front end, it doesnt needs to be hosted on web. considering this what all topics of Flask should I study, so that my job is done?

ionic raft
past cipher
#
webapp
  /models
    /user.py
    /user_details.py

each .py has a table inside. User has a relationship to user_details.

I get this error Mapper mapped class UserDetail->user_details could not assemble any primary key columns for mapped table 'user_details'

#

how can I split up my models, and not have this issue?

ionic raft
#

LanesFlow is built on Django. But then LanesFlow already has some 10 applications with more planned

past cipher
#

nvm thats not my issue ๐Ÿ˜„

glad egret
#

I have planned to go till Tutorial section in the documentation, as i think that would teach me how to bring the data from html page to code

ionic raft
#

FLask is great if you want to develop very quickly and the web application is simple (1-3 apps)

ionic raft
glad egret
#

now I have only one page designed, and m working on it's backend

#

when all the pages and their backend are ready i will transform the code to .exe and release it for everyone's use

ionic raft
glad egret
ionic raft
glad egret
#

and it is one of the reason I don't want to lewarn unnecessary things as I have already have too many things to study

ionic raft
glad egret
ionic raft
#

A web app requires hosting it though. Challenges with each approach.

glad egret
#

instead of .exe I may release a flutter app that uses my python code as backend

#

based on server-client architechture

ionic raft
glad egret
ionic raft
# glad egret yes, personally I am not a big fan of web apps

Irony is, I am a fan of web apps...for complex applications. They're OS agnostic. Plus, when it's online, an API means it is accessible by any internet connected app. And if I build offline caching functionality into the app, then users can upload/download information when their device comes online

glad egret
#

only web apps have apis?

ionic raft
#

If you build an .exe application (for windows) you have to recognize that Python is an interpreted language, and building a windows client for Python comes with hurdles. Plus, you're locked to the OS, and have to manage how it ages

ionic raft
#

A web application is OS agnostic. It doesn't care...Win/Mac/Linux? All good.

glad egret
#

yup, so my modified plan now is to transform all my code on which I am working now to API which I will access from a flutter app

ionic raft
#

Also, an .exe is generally built on a client-server architecture. Are you building the DB into the app? So it is local? Or are you looking for data to be shared?

glad egret
ionic raft
glad egret
ionic raft
glad egret
ionic raft
#

Trade offs for all approaches. Depending on the complexity of data collection, presentation and manipulation, a smartphone app could quickly become a big constraint.

glad egret
#

once I have considerable amout of data then I would work on how to share it

ionic raft
#

Plus, the UI formfactor of a smartphone could also be a constraint

glad egret
glad egret
ionic raft
ionic raft
glad egret
ionic raft
glad egret
ionic raft
glad egret
ionic raft
#

And the more complex the datasets, along with the great requirement for manipulating/presenting the data, the greater the challenge becomes.
However, I'm back to data collection and your use of the word "tedious"

glad egret
#

every great idea has trade offs

ionic raft
#

Sorry...hit enter ๐Ÿ™‚
If you want to prototype an app, Flask offers rapid value to explore. When you have a DB then you can build an API. With an API you can connect to an app

rotund perch
#

Hello guys ive never used JWT with DRF, can someone simply explains my questions.

  1. Why there is refresh token + access token? does that mean if the access token expired the user is not authorized until he goes to the refresh token url? if yes how would a user using the website knows if the access token expired + how he will know how to refresh it or how to do it automatically in django if thats not the case.

2.Why logging out blacklists tokens? my main goal to use JWT is to not store tokens in db and take more storage.

ionic raft
ionic raft
rotund perch
ionic raft
rotund perch
glad egret
#

@ionic raft according to you which approach is correct:

  1. study everything about a library before reading it?
ionic raft
dense slate
#

Refresh tokens "refresh" them to be good for another period of time.

ionic raft
glad egret
#
  1. studying only as much required at the moment and remaining when it is needed?
ionic raft
rotund perch
dense slate
ionic raft
ionic raft
dense slate
#

Well, yea.

#

So is any security protocol.

#

Doing it wrong = bad.

ionic raft
#

JWTs had the feel of a hybrid of front-end and application security. I'm for an application-only authentication model personally

dense slate
ionic raft
#

I don't want permissions being applied on the front end. I want to have the application do the logical work to build the template, and send the built template. Fundamentally, JWTs feel flawed.

glad egret
#

@ionic raft thanks for the nice talk. good night everybody, its 15 minutes past midnighht here

dense slate
#

I guess? It's one field extra. I can't imagine that is detrimental to an app.

dense slate
#

You don't need tokens in that case.

rotund perch
ionic raft
rotund perch
#

But anyone knows what type of tokens is basic token in django?

ionic raft
#

I suspect my impression was influenced by the idea that, I don't want logic on the front end. That's what the application layer is for.

rotund perch
ionic raft
# dense slate What's your reason for that?

When I saw the hacker sniff/intercept the JWT (token), inject a different value into the subscription level, and then release the token back to the server to bypass paying for subscription...yeah...that

#

Like I said...limited knowledge, and more questions than answers

stark tartan
#

Is I can get job only with django and html css js with jQuery or shall l learn React and django rest freamework

dense slate
ionic raft
ionic raft
#

The irony is, one app will need a FE framework. That's the research dance I've begun....

dense slate
#

httpOnly tokens specifically do not allow you to modify them on the client-side.

ionic raft
torpid folio
#

can anyone suggest me some good tutorials on django?

ionic raft
torpid folio
ionic raft
torpid folio
#

Yes I have seen

ionic raft
torpid folio
ionic raft
torpid folio
#

great

torpid folio
ionic raft
#

I also did a UDemy bootcamp (for Python/html/css/Flask) and read a book....plus other tutorials...but Corey's series was where I started with Django

torpid folio
uneven radish
#

Hi. So I'm working on a Django project.
In that let's say I have this endpoint, "/account/register/", which displays the form for register on the website.
Now, when the user is registered (successful POST request), I want to display user name for that user saying "Hey, username you are registered".
So I know I have to use HttpResponseRedirect when dealing with POST. Can anyone suggest how to do that?
How can I display this info on that same endpoint "/account/register/" and not creating a new view for that or new endpoint.

ionic raft
ionic raft
torpid folio
ionic raft
uneven radish
#

I already did that.
If POST.
CREATE user.
ELSE.
DISPLAY blank form.

#

Now, lets say user is successfully registered.

ionic raft
torpid folio
ionic raft
uneven radish
#

I can write message. That's a good idea.

#

But how to send CONTEXT with HttpResponseRedirect?

torpid folio
#

isnt django a backend technology?

ionic raft
uneven radish
#

To render HTML page saying "Hey username, registered correctly".

ionic raft
uneven radish
#

Something like that.

ionic raft
uneven radish
#

But isn't using render with POST calls a bad practice?

#

If users refresh the page, the form gets resubmitted again right?

ionic raft
uneven radish
#

Really?

ionic raft
# uneven radish Really?

Really. At no point in any tutorial or even reading Two Scoops of Django have I seen render + POST being a bad practice. I can't see why it would be. But I've only been using Django for a few months

uneven radish
#

Okay. I'll try this once. Thank you for this!

ionic raft
uneven radish
#

Messages can be sent via request right, or do I have to send it via context?

ionic raft
#

Bear in mind, I'm using bootstrap css to colour the p tag based on alert class

uneven radish
#

Okay! Thank you! ๐Ÿ™‚

#
def post_display(request, year, month, day, slug):
    # Display all the details of the post
    post = get_object_or_404(
        Post,
        slug=slug,
        published__year=year,
        published__month=month,
        published__day=day,
        status="published",
    )

    # A list of active commnets on a particular post
    comments = post.comments.filter(active=True)
    new_comment = None

    if request.method == "POST":
        comment_form = CommentForm(data=request.POST)

        if comment_form.is_valid():
            new_comment = comment_form.save(commit=False)
            new_comment.post = post

            new_comment.save()

            return render(request, "blog/post/display.html", context={
                "post": post,
            })
            # return redirect(
            #     reverse(
            #         "blog:post_display",
            #         kwargs={
            #             "year": year,
            #             "month": month,
            #             "day": day,
            #             "slug": slug,
            #         },
            #     )
            # )
    else:
        comment_form = CommentForm()

    context = {
        "post": post,
        "comments": comments,
        "new_comment": new_comment,
        "comment_form": comment_form,
    }

    return render(request, "blog/post/display.html", context)
#

Hey @ionic raft this is one of my app. Can you just check if my POST render is okay?

#

Because if I do this, I'm able to post multiple same comments with refresh.

#

Please @ me, if you can tell me how to avoid this if I'm using render?

#

Please check this!

pliant shadow
#

I'm having problem integrating Beaker for session management in flask. Can anyone share a snippet on how to integrate SessionMiddleware with flask?

dense slate
#

To use the person's name or username, the page view should be returning the user in the context so you get all your info to display from that.

#

Or maybe you can even grab it from the session cookie / request header if you want to get it that way.

solar patio
#

(for po in pos:
browser.find_element_by_xpath('//*[text()[contains(.,{})]]'.format(po)).click())

#

sorry, i think i pasted it wrong.

vestal hound
#

nothing to do with render

#

which just fills a template

ionic raft
vestal hound
vestal hound
ionic raft
# uneven radish Please check this!

@uneven radish I'm using a similar comment approach but differently (screenshot helped). Specifically, I am using a class based view (CreateView) and calling the function form_valid to return the form itself. I'm not clear on how to prevent what you're experiencing with a functional view. However, that does inspire me to test what I do have to see if a refresh of the page will create the same problem.

    def form_valid(self, form):
        form.instance.article_id = self.kwargs['pk']
        return super().form_valid(form)```
native tide
#
<!DOCTYPE html>
<style>
    body {
        background-image: url('bc.gif');
    }
</style>
```Should this not render the gif as the background for the web page?
dawn island
#

Hello, I'm new to Django. I learned the basics of the framework by watching YouTube videos. Now that I'm interested in learning more about Django, what would be the best place to start?

native tide
civic crater
#

You don't have head tag

#

Does your body have content

dawn island
civic crater
#

Gif will be stretched or repeated if u use it in this way

civic crater
civic crater
#

What's the issue @ashen crescent

ashen crescent
#

it doesnt work as in transistion is ignored

civic crater
#

I'll try helping you

#

Your image is unable to load
Resend?

ashen crescent
#
transition: translate 2s ease-in-out;
    -webkit-transition: translate 2s ease-in-out;````
#

so it translates just not as a transistion as shown

#

@civic crater

civic crater
inland oak
# ionic raft Thanks for the clarity. The original question was based on an assumption that us...

POST is actually best practice for sensitive requests which change some database data. Because it is auto semi protected against CRSF attacks.

Tricks like

<img src="url/delete account at site X">

will be automatically more difficult and requiring for attacker to have attack hidden in javascript at least

Further protection with CSRF tokens or two auth is made to have better protection in this direction

plush pivot
#

hi guys

#

for what reasons would i rather use a windows server than linux?

random sand
#

note taking app

#

I want to make a note taking app

native tide
#

what is the {% %} in html

random sand
#

this is jinja templating

uneven radish
#

@ionic raft
May be I'm overthinking this but Django Documentation Tutorial Part 4 says:

After incrementing the choice count, the code returns an HttpResponseRedirect rather than a normal HttpResponse. HttpResponseRedirect takes a single argument: the URL to which the user will be redirected (see the following point for how we construct the URL in this case).

As the Python comment above points out, you should always return an HttpResponseRedirect after successfully dealing with POST data. This tip isnโ€™t specific to Django; itโ€™s good Web development practice in general.

#

I can use redirect() because I think I read somewhere it is a wrapper around HttpResponseRedirect.

native tide
#

can someone send me a tutorial on creating a Emailing service
dm me

tall plaza
#
like i am sending the  over 100 mb of image in base64. but as response is containing bytes which freeze the browser itself
please tell me how to do it without freezing the browser
anyone got my question?```
candid meteor
#

welp im done with my site, where do i host

vestal hound
uneven radish
glad egret
#

can anybody help me here. I am trying to install Flask according to the steps given in the documentation website of Flask

uneven radish
#

Remove $

glad egret
#

before pip?

candid meteor
#

im not looking for the free services

uneven radish
#

Yes.

uneven radish
glad egret
#

but website says to write $

uneven radish
#

It doesn't.

#

$ is a notation used when any commands needs to be executed with sudo. In bash.

glad egret
#

what does sudo mean

uneven radish
#

It's not related to Python Django Flask.

#

It's a program in UNIX with which we can elevate our privilege and run bash commands.

glad egret
#

is it necessary to upgrade pip whenever a new version is available or I can manage with older version

rain wasp
#

can i create a website with react as front end and django and backend??

uneven radish
#

Never upgraded. If you encounter any errors. Maybe you should.

rain wasp
#

please help

uneven radish
#

Check DRF.

glad egret
#

no errors but only warning

rain wasp
uneven radish
glad egret
#

okay

uneven radish
rain wasp
glad egret
#

now i have created a folder so now I can open it in VS and start working as normal or not?

uneven radish
#

Build an API with Django RF and feed it to your Frontend.

rain wasp
#

is these any python framework for font end like react or angular ?

uneven radish
glad egret
#

learning flask

uneven radish
#

So follow the tutorial. What does it say to do next?

glad egret
#

directly it provides a code for a minimal app

uneven radish
#

I don't know anything about flask so can't really comment on that.

glad egret
#

then i have to hit & trial

uneven radish
#

Or find a new tutorial? Just sayin'

glad egret
#

good idea

#

I opened the flask folder I created before hand named flaskproject and installed flask within it. then I made a new file named project.py having following code inside flaskproject :

from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello_world():
    return "<p>Hello, World!</p>"
#

then I saved it and wrote the following commands

#

as you can see I have the following error

#
Import "flask" could not be resolved from source```
#

please help me here

glad egret
native tide
#

should i learn django or flask?

glacial yoke
#

If I wanted to pass information from my react frontend app to my django backend, would I have to do a post request using something like axios, or could I use request.get(data=data) in a view in my backend?

glacial yoke
#

For example if I had some articles on my site, and they were displayed from the db in django backend, and displayed on react frontend. And if I wanted to change the article on the site, I would have to pass the article id to my backend, so that it could be edited and saved in db. Therefore the article id, and the new text should be passed to django and the db, how could I do that

steep spire
# native tide should i learn django or flask?

surely go for Django in 2021

I recommend to you to take CS50 Web this Course is Incredibly awesome ( especially Projects )

https://cs50.harvard.edu/web/2020/

native tide
#

i already know programming basics and i know programming languages like python javascript i dont think i need cs50

#

i wonder why people learn flask if everyone says that django is better

dusk portal
#

flask is kind of simple and ezz for api and more widely used for things like web automation making api's n all @native tide

wooden dagger
#

hello guys, I'm new in django and I want to practice by some projects but I don't know where I should start, for example Is there any website that gives free project for practice?

dusk portal
#
  • django god CodingEnterpreneur
wooden dagger
#

Mm thanks i will check

lethal trellis
#

Hello guys, how would I go about automating fifa 22 transfer market trading?

#

aka just do stuff id spend hours on doing except get python to do it

#

I have not dealt with automation of websites before

grave raft
#

How can I download a file from google drive in python like dropbox gives a access token and file Id, now how to get such access token for google drive .
I got to make a upload feature like upload from drive like google forms but can't figure it out.
Thanks

viscid forge
#

guys what should I learn for web development django or flask?

final meteor
#

Hi, I need some guidance with django

I have a multiselect checkbox table in index.html tied to a submit button
Once i select rows and click on submit, it generates a query string like this

http://127.0.0.1:8000/?btSelectAll=on&id=0&id=1&id=2&id=3&id=4&id=5&id=6&id=7&id=8&id=9

I want that when the GET has id in query_dict, it should be redirected to another page and show the content of 'id' in that page

The redirection works fine as long as i dont attempt to pass the variables like this

def index(request):
    x = request.GET.getlist('id')
    if x:
        context = {'data' : x}
        return redirect('devicedetails')
    else:
        context = {}
        return render(request, 'app/index.html', context)


def devicedetails(request):
    return render(request, 'app/devicedetails.html')

However, the moment i want to do something like this, it doesn't
i dont know what is the correct way of achieving this

and i get error message like this

Reverse for 'devicedetails' with keyword arguments '{'context': {'data': ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']}}' not found. 1 pattern(s) tried: ['devicedetails$']

hoary yacht
#

guys i receive a json file as a string, however it's show the code of the unicode

<class 'str'>
{
    "Name": "turicas",
    "Location": "Curitiba/PR - Brazil",
    "Workfor": "Pythonic Caf\u00e9",
    "Website": "http://dolaeor.py/",
    "Twiter": "@oneoneo"
}

how can i treat this for every case of unicode that could appears to me

cursive pine
#

Anyone here who has integrated Metamask connect with a front-end?

uneven radish
native tide
#

Any tutorials on how to make a lite emailing service

#

please dm the link

topaz finch
#

How can I get SSL going for an aiohttp server? I have an ssl cert from letsencrypt and have apache up and running, do I just need to plug and play?
@ me when responding please.

rotund perch
#

Hello, If I have a model which have a Foreign Key such as a user_id. When doing a Queryset to get all objects in the db in that table(model) but instead of only getting the user as an id, I want to include the user name in the response. Something like this:

#in Models
class Post(models.Model):
  title = models.CharField(max_length=200)
  creator = models.ForeignKey(User, on_delete=models.CASCADE) #This Will Get me the user id.
#In Views
Posts = Post.objects.all()
print(Posts)
#Printed Value of Posts:
#{
# 'id': 1 ,
# 'title': 'First',
# 'creator': 1 ,
# 'creator_name' : 'user' #What I Want to Include with the response
#}
#...etc
glad egret
uneven radish
#

Do that activate command again.

#

And then run Flask command.

tranquil fossil
#

Guys anybody familiar with CKeditor

#

I'm Unable to uplaod images from templates usingit

tranquil fossil
#

anyone here ?

pastel knot
#

how do i toggle the class of another element on button click

#

in vue

chilly falcon
graceful flax
#

Hi, Iโ€™m building an app and here Iโ€™ve users, I read in few places itโ€™s better to keep user profile information separate from the main user credentials table. Iโ€™m using django and Postgres, is this followed practice?

chilly falcon
#

u can customize the user model of django so that u can use inbuild django authentication and permission

pastel knot
#

how do i pass data from Django to a Vue spa inside a template

rotund sierra
#

hey hello

#

needed some help urgently

#

i am trying to host a flask website suing sqlite database on pythonanywhere but it is showing errors taht tables dont exist while it was working perfectly fine on localhost

#

any suggestions

#

?

outer apex
wooden dagger
#

Hi, I want to create a search box, but it doesn't work.
This is my views.py:
โ€œ`
from django.shortcuts import render
from .models import Products

def index(request):
product_objects = Products.objects.all()
item_name = request.GET.get('item_name')
if item_name != '' and item_name is not None:
product_objects = product_objects.filter(title__icontains=item_name)
return render(request, 'shop/index.html', {'product_objects':product_objects})โ€œ`

This is my index.html:
โ€œ<form class="card card-sm"> <div class="card-body row no-gutters align-items-center"> <div class="col"> <input type="search" name="item-name" placeholder="Search for products" class="form-control form-control-borderless"> </div> <div class="col-auto"> <button class="btn btn-success" type="submit">Search</button> </div> </div> </form>โ€œ
For example I have a product called "Laptop", when I search Laptop nothing happens and it still shows me all products (just the URL changes to "http://127.0.0.1:8000/**?item-name=laptop**" )
any suggest?

outer apex
wooden dagger
#

ohhh thank u i'm stupid it was silly question ๐Ÿ˜….worked

native tide
#

Hi, anyone here successfully developer python web apps on Windows? With postgresql. I just want to know if you recommend buying a Mac instead?

dense slate
#

Anyone use Next.js with a Django backend? I can't quite figure out how to use next.js api routes to send an incoming Stripe request to Django.

snow sierra
#

Hi Gurus!

#

I am getting data, but On Line response.json() is better?
how can i go forward? need this data dynamicly to front, it's Django.

#

If this will be on database i will do something like this
objects.all() and then for .

how can i do it on dicts?? on json?

runic lodge
tawny anvil
#

hello can someone explain the difference between geodjango and django?

cerulean laurel
#

hello there, i really wanna create a custom user model in django, but using the django.auth it requires me to use the username field which i don't need in my project

cerulean laurel
#

done, just change username to None

#

well it was working.. but it doesn't work anymore...

#

okay i fixed it, just override it in the _create_user() method in the usermanager class

orchid fox
#

Hello may I ask , what are web framworks ? Like Django and Flask ?

#

frameworks*

warm igloo
#

Well, think about the word, framework.

Imagine you want to build a house. Would you rather start on dirt, with just a pile of supplies? Or maybe at least the foundation, plumbing, wall studs and roof are on. You just gotta do the windows, doors, electricity.

That is what Flask and Django are. Frameworks for you to build your app on.

orchid fox
#

Ahh I see, well explained . Thank you, but I guess it's possible also to do web apps without these framworks am I right ?

#

Which I mean is full python

warm igloo
#

Yes, but you'll end up recreating a lot of what they do.

#

Flask is much lighter than Django for instance. Django is said to include everything and the kitchen sink as a joke.

#

I prefer Flask for most of my web work.

#

or FastAPI

orchid fox
#

Ahh I see, haha understood . May I ask what your web work is about ? I would like to understand more deeply . By that I mean what projects do you do as example ?

#

So basically Flask and Django are tools to help .

#

Oh yeah I also search up about these 2 framworks software and it is said that flask is lighter

#

framework*

warm igloo
#

Oh sure. Well, personally I build web apps for like dashboards or tools inside my homelab. I also have a blog that is statically output from the pelican static site generator (it's written in python but not me). I also wrote a short-lived website called warcache.com that was for one of my hobbies (wargaming).

Professsionally I use it to write and read APIs, glue systems together, do system admin work cause I hate writing bash scripts, have a few spiders running at any one time scraping data from websites. Hmm, oh, when we were testing out building apps for the Amazon Alexa devices, I did all that voice work in python. Originally in nodejs, but I found the python way better and rewrote it all.

orchid fox
#

I see, what's a homelab

warm igloo
#

Ah, sorry. I have professional grade networking switches, servers, a small kubernetes cluster built from raspberry pis, and such. Basically, I mess around with hardware, networking, and software as a hobby.

orchid fox
#

I see . Do you get paid for these hobbies if I may ask ?

warm igloo
#

No. Hobbies are for fun. ๐Ÿ˜„

orchid fox
#

Oh wow I see . Well that's interesting

warm igloo
#

I am an engineer though and do get paid for that. Or more now, my role is less making stuff and more overseeing growth, development, and careers of other engineers.

orchid fox
#

If I may ask, I would like to make educational websites, what would you recommend to me to start using to achieve my website ?

#

I'm currently learning HTML, CSS and JAVASCIRPT. Also Python .

warm igloo
#

Great start. You don't need much more than that. One of the trickiest pieces you'll run into is setting up hosting but I'm sure you can figure it out. There are tutorials out there to help you.

#

Why is what?

orchid fox
orchid fox
warm igloo
#

Gotcha. I'm 20+ years in so I make less stuff for work because most of my time is as an engineering manager. I oversee teams. And currently my role is all about continuous learning, mentorship, and growing the company.

orchid fox
#

Wow I see, what tips do you have for a University student then ? Since I am one . I would like to know what you would love to see from a University student before going in the workforce life

warm igloo
orchid fox
warm igloo
orchid fox
#

Ahh alright then thank you for your responses then . Good night !

mystic vortex
#

Guys does django load the things faster

#

?

wooden ruin
mystic vortex
#

I mean does django load the pages faster

#

??

#

@wooden ruin

#

Guys can u suggest me a backend framework?

wooden ruin
mystic vortex
#

@wooden ruin is it possible to use async with django?

#

And what about falcon is it good

wooden ruin
#

you can certainly use async with django, both through async views/middleware or even through websockets. and i've never head of falcon before

mystic vortex
#

Ok

native tide
#

yeah why not!

#

share code and issue.

#

and what is issue?

#

you mean video is getting loaded tho?

#

also your src is right, right?

#

show me screenshot?

#

shows something in console?

#

also show me the directory view, I'd like to see, where exactly is your video. i think you're fucking up with the path.

glad egret
#

I have installed flask on a virtual environment in a folder and I am coding in a file inside that folder but when I run it according to the way given by the documentation, it says that flask isn't installed. can you help me how to solve this

jovial cloud
# glad egret

You need to activate the venv and don't put any of your python files inside the venv(they should be at the same level like siblings)

glad egret
#

so i must create a new folder to write code instead of writing code inside Scripts subfolder of venv?

#

how is venv activated

#

can you give me an screenshot of a flask project to understand more clearly @jovial cloud

jovial cloud
jovial cloud
glad egret
#

how to activate venv?

jovial cloud
#

On Windows, venv\Scripts\activate
While on Mac/Linux

source venv/bin/activate
glad egret
#

I am getting same error which means the problem is that my venv isn't active

glad egret
#

and in ther terminal of VS code?

jovial cloud
#

Use command prompt, I don't know the command for powershell

desert cradle
#

How can I use flask's request.form.to_dict() in django?

raw compass
regal fossil
#

hi guys how I can create something like this using html and css?

glad egret
#

a text box with 2 buttons, you must know html,css for the looks and JS is required to bring functionality

dusty moon
#

i get weird render differences in CSS between Linux and Windows. any ideas?

left ridge
dusty moon
#

nope.

#

google chrome to google chrome at the same version

vapid haven
vapid haven
#

AttributeError: module 'wsgi' has no attribute 'application'

#

I get this error while deployment can some1 help

dusty moon
#

?

native tide
#

you will see changes between OSs. you will see bit different in certain elements in MacOS too.

#

also define, weird, what exactly?

dusty moon
#

Layout of one of my divs doesnโ€™t load correctly

#

Text appears much larger than my Linux system on Windows

native tide
#

oh just Text than right?

dusty moon
#

Yeah

native tide
#

have you given font-size?

dusty moon
#

Yes

native tide
#

i mean in dev console view

dusty moon
#

How do I do that?

native tide
#

you know like this

dusty moon
#

Oh, nice

#

Iโ€™ll do that.

native tide
#

yeah my assumption is that it may be because of changes of font.

dusty moon
#

Btw, Iโ€™ve heard a term called CSS reset. Can that help?

native tide
dusty moon
#

Me too. Just wondering

native tide
#

but i mean to be very honest, some minor changes will be there when you switch OSs.

dusty moon
#

Yeah I see.

#

Also, margin of an <hr/> doesnโ€™t change on windows too.

#

Windows sucks ๐Ÿ˜ฆ

native tide
#

being a web dev you gotta see everything, especially the OS which gets used most.

dusty moon
#

I know

native tide
#

you can either complaint or just move on with divs lol.

dusty moon
#

Iโ€™ll just see what I can do with it. Itโ€™s a problem when my pc is trash and canโ€™t run VMs. If I could run VMs, I could test the site on Windows too.

#

For now, Iโ€™ll just ask my friend to run it on his machine for me.

#

Anyway, thanks for the help @native tide !

vapid haven
#

AttributeError: module 'wsgi' has no attribute 'application'
I get this error while deployment can some1 help

inland oak
dusty moon
#

yeah, guess i got that.

inland oak
#

you can set fonts in way like...

dusty moon
#

CSS book?

inland oak
#

For thing one: use font1, font2, font3, and if nothing else use font_family_x

dusty moon
#

oh, yeah the fallbacks

inland oak
dusty moon
#

what an oldschool looking book

#

it reminds me of the old interned ads from the 90s

inland oak
#

if we zoom the book cover closer

dusty moon
#

lol

inland oak
#

I like it

#

I read it only once

#

and never applied at practice

#

and still I remember it after many weeks/months

uneven radish
#

Head First books are cool

dusty moon
#

i learnt my css from a youtube video. works fine imo

#

still needs some googling from the side tho.

fallow meteor
#

their are some websites where form fields appear one at a time. Like first they say to fill Field A, then we click Next, and then Field B appears after reloading or something and so on. How can i create a such a system in flask ??

fallow meteor
native tide
fallow meteor
#

can u pls explain more about this?

native tide
#

Well I would need more info on your app? What it's using for the frontend?

fallow meteor
#

well i use normal html and bootstrap for frontend

#

i guess thats not what u were hoping

native tide
#

Umm yep I will have to search for how it works in vanilla js and get back to you.

fallow meteor
#

thanks for the doing

native tide
fallow meteor
#

okk

#

also i think i gotta learn about js front end with python back end (if its possible)

spiral blaze
#

should i learn django after a few months of learning? i heard its pretty hard

fallow meteor
#

learn flask

dire urchin
#

hey so I'm doing some basic contact form stuff with django's send_mail(subject, message, from_email, recipient_list)
I set it up and it works, but I can't figure out what's it supposed to do with the from_email parameter. Is it supposed to appear somewhere in the body/subject of the sent email?

#

I ended up just jamming message_email into the message parameter like this

    path = request.path[:-1]
    context = {'path':path}

    if request.method == "POST":
        message_name = request.POST['message-name']
        message_email = request.POST['message-email']
        message_text = request.POST['message-text']
        context['message_name'] = message_name

        send_mail(
            f'prtfl - Message from {message_name}',     #subject
            f'{message_text}\n\nFrom: {message_email}', #message
            message_email,                              #from_email (this thing here)
            [str(os.getenv('email'))]                   #recipient_list
        )

        return render(request, 'main/contact.html', context)
    else:
        return render(request, 'main/contact.html', context)```
But is this the correct way to go about it?
junior vale
#
2021-09-23T12:24:42.734186+00:00 app[web.1]: [2021-09-23 12:24:42 +0000] [17] [INFO] Starting gunicorn 20.1.0
2021-09-23T12:24:42.734469+00:00 app[web.1]: [2021-09-23 12:24:42 +0000] [17] [ERROR] Connection in use: ('0.0.0.0', 23194)
2021-09-23T12:24:42.734516+00:00 app[web.1]: [2021-09-23 12:24:42 +0000] [17] [ERROR] Retrying in 1 second.
2021-09-23T12:24:43.062713+00:00 app[web.1]: [2021-09-23 12:24:43 +0000] [7] [INFO] Worker exiting (pid: 7)
2021-09-23T12:24:43.662675+00:00 app[web.1]: [2021-09-23 12:24:43 +0000] [4] [INFO] Shutting down: Master
2021-09-23T12:24:43.662722+00:00 app[web.1]: [2021-09-23 12:24:43 +0000] [4] [INFO] Reason: Worker failed to boot.
2021-09-23T12:24:43.802630+00:00 heroku[web.1]: Process exited with status 3
2021-09-23T12:24:43.897718+00:00 heroku[web.1]: State changed from up to crashed

Hey i am getting this error while trying to deploy on heroku with gunicorn I am not sure what does it mean could someone help

spiral blaze
#

@fallow meteor do i have to learn like css or html first or can i just dive in?

late creek
junior vale
late creek
#

:)

junior vale
#

i ran the app twice ๐Ÿคฆ

dire urchin
#

also good idea

#

maybe a dumb question but do i need to let the user know i will be dumping their info into a db?

inland oak
vestal hound
#

depends on your jurisdiction

#

and what info it is

dire urchin
#

the user's email and whatever they put their "name" as, along with the message, but I'm already shying away from this idea

manic frost
#

Is there any way to do dependency injection with HTTPEndpoint in Starlette without reinventing the wheel?

#

The easiest solution I can think of is a function that returns a class, but that's cursed and adds an indentation level

dense slate
#

If I have an event hit an endpoint directly on my Django backend (Next/React frontend), how do I send a response to the front end to go to a certain page when it's finished, since in this case Django isn't controlling navigation on the frontend?

fallow meteor
#

cuz u will be using bootstrap for the most part for styling, so u need some knowledge

#

but its easy, i guess it would take 30 mins to gather the knowledge of most of the html tags and all

spiral blaze
#

iam following a tutorial just now, for django, i typed in everything the same and somehow an error occurs

mystic vortex
#

is it wrong ??

@app.route("/")
async def home():
    return await render_template("main.html")

@app.route('/handle_data', methods=['POST', 'GET'])
async def handle_data():
    projectpath = await request.form['projectFilepath']
    print(projectpath)
    return projectpath
#
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form action="{{ url_for("handle_data")}}" method="post">
        <label for="firstname">First Name:</label>
        <input type="text" id="firstname" name="fname" placeholder="firstname">
        <label for="lastname">Last Name:</label>
        <input type="text" id="lastname" name="lname" placeholder="lastname">
        <button type="submit">Login</button>
        
</body>
</html>
#

its not working when i am trying to get the post

snow sierra
mystic vortex
#

@snow sierra

snow sierra
#

"{{ url_for("handle_data")}}" use single quotes 'handle_data'

mystic vortex
#
from quart import Quart, jsonify, redirect, render_template, url_for, request
app = Quart(__name__)



@app.route("/")
async def home():
    return await render_template("main.html")

@app.route('/handle_data', methods=['POST', 'GET'])
async def handle_data():
    projectpath = await request.form['fname']
    p2 = await request.form['lname']
    print(projectpath)
    return {projectpath: p2}



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

@snow sierra

#
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form action="{{ url_for('handle_data')}}" method="post">
        <label for="firstname">First Name:</label>
        <input type="text" id="firstname" name="fname" placeholder="firstname">
        <label for="lastname">Last Name:</label>
        <input type="text" id="lastname" name="lname" placeholder="lastname">
        <button type="submit">Login</button>

    </form>
        
</body>
</html>
snow sierra
#

"{{ url_for('handle_data') }}" method="POST"

#

i don;t know, just lets start by this changes :d

mystic vortex
#

ok

#

not working

#

error

snow sierra
#

did you tried it?

mystic vortex
#

@snow sierra can u show me a example of how to make a post request?

snow sierra
#

I'm using Django :x

#

and no time to test some cases on flask, later evening maybe

mystic vortex
#

if yes so can u tell me how can i get started?

#

someone tell me how can i get started with django

#

???

dire urchin
#

either look up the docs or youtube search django tutorial

frank shoal
#

I can tell you how to get started with fastapi

mystic vortex
#

i am going with django

#

thanks for helping

meager anchor
frank shoal
#

shell: ```sh
pip install fastapi

app.py: ```py
from fastapi import App

app = App()

@app.route('/')
def home():
  return "Hello, world!"

main.py: ```py
import uvicorn

if name == 'main':
uvicorn.run('app')

#

Ok, I go now

meager anchor
#

fastapi and django are really for two different kinds of projects imo, django is absolutely brilliant for user-facing sites and fastapi is absolutely brilliant for well, APIs

frank shoal
#

fastapi pairs well with frontend frameworks, like react or vue

mystic vortex
#

honestly django is just amazing

#

@meager anchor isint is possible to create chat room with django

mystic vortex
meager anchor
meager anchor
#

i use it at work for a few things and it handles very very good volume

frank shoal
#

fastapi supports websockets fyi

native tide
#

if anyone is good with beautifulsoup and don't mind helping out #help-cupcake

torpid folio
#

can anyone suggest me some good tutorial on websocket?

weak mulch
#

Just search up socket io python integration

#

Youll find pretty good tutorials.

native tide
shut relic
#

What to choose for creating an api + websockets. FastApi or django + DRF ??

#

I like the documentation of fastApi but I dont know if its going to be alive for very long

#

FastApi looks good but I dont know if I will be able to find any help with any edge cases that will occur in the project as it gets bigger

calm plume
#

FastAPI is wonderful for API creation, I've used it multiple times

warm igloo
#

FastAPI is very popular and catching up to others. It is actively under development.

shut relic
#

what are its weaknesses to django drf?

warm igloo
#

Not familiar enough with DRF. I never reach for Django as to me it's just TOO big.

calm plume
#

Honestly, if it's just an API, I'd always go with FastAPI, it's much simpler

#

I'd only use DRF if it heavily ties into another Django project

shut relic
#

hm ok that sounds good

#

I really like it I just want to be sure that I will not have any problems in the future

#

I want my api to communicate with a machine that sends and receices geolocation data with websockets

#

also to have user auth and roles

calm plume
#

FastAPI is very actively maintained, it's pretty popular. I doubt you have to worry about it losing that.

calm plume
shut relic
#

ok nice

calm plume
shut relic
#

thnx

#

my plan is to make a small stack that I can scale to multiple machines if needed

#

like use a load balancer in front and multiple API containers (fastApi) in the back

#

with 2 postgres databases one as main and one as the replica

ionic raft
# uneven radish <@837562596231872512> May be I'm overthinking this but Django Documentation Tut...

@uneven radish another post mentioned the following:
POST is actually best practice for sensitive requests which change some database data. Because it is auto semi protected against CRSF attacks. Tricks like
<img src="url/delete account at site X">
will be automatically more difficult and requiring for attacker to have attack hidden in javascript at least

All I can say is that the documentation you cited is a bit general. Updating a DB is another layer complexity, and I'm curious about that recommendation when placed against what the CRSF token is supposed to protect against. While I get why you're posting what you've posted, the CRSF token is supposed to protect against the potential gap being listed. And in between various tutorials and the book, Two Scoops of Django, I've just not see anything that highlights POST (assuming a CRSF token is used - which has to be explicitly turned off to not use) and render as being a problem.

On the plus side, this is all good research. Deep research and finding out best ways to get the job done can only be a good thing. Good luck. ๐Ÿ™‚

Side note: And it's this sort of debate/conversation that is exactly why this Discord is amazing ๐Ÿ˜„

manic frost
#

the correct way to protect against that is to implement CORS correctly

#

but it could still be an issue with images and such if you allow embedding your own images

#

...which is not a good idea because you can make IP grabbers that way.

uneven radish
# ionic raft <@!484412997947752458> another post mentioned the following: POST is actually be...

Thank you for taking out time and replying.
I'm still not convinced how can I use render to return after I have successfully added a new comment under my blog (my application) or dealing with my POST call. I tested and tweaked my code but still couldn't remove that resubmission form error when using render().
However, if I use redirect and I don't have to deal with that problem.

I am just a beginner at this point following a book. Maybe in later chapters, they will introduce and differentiate or make things more clear. I'd still use redirect at this moment because of obvious reason.

If you test your code further, do let me know the findings and also post your code snippets.

And I completely agree about this being a good research. We will be learning something new and remove bugs one at a time.
Cheers! ๐Ÿป

inland oak
#

So many safety mechanisms already there, all we need just to turn them on

#

CSP technically protects too for same purposes

#

It will ensure that only your javascripts will run

It is more against XSS though

uneven radish
#

You've been following this conversation @inland oak ?

inland oak
#

Just few last posts

uneven radish
#

The issue was when successfully dealing with POST call when I use redirect to return and refresh my form page my form isn't submitted again. But when returned with render, I can submit my form N times just by refreshing.

inland oak
#

Well, and we can also
Use PUT to update or replace
Use DELETE to delete ;b

uneven radish
#
def post_display(request, year, month, day, slug):
    # Display all the details of the post
    post = get_object_or_404(
        Post,
        slug=slug,
        published__year=year,
        published__month=month,
        published__day=day,
        status="published",
    )

    # A list of active commnets on a particular post
    comments = post.comments.filter(active=True)
    new_comment = None

    if request.method == "POST":
        comment_form = CommentForm(data=request.POST)

        if comment_form.is_valid():
            new_comment = comment_form.save(commit=False)
            new_comment.post = post

            new_comment.save()

            return render(request, "blog/post/display.html", context={
                "post": post,
            })
            # return redirect(
            #     reverse(
            #         "blog:post_display",
            #         kwargs={
            #             "year": year,
            #             "month": month,
            #             "day": day,
            #             "slug": slug,
            #         },
            #     )
            # )
    else:
        comment_form = CommentForm()

    context = {
        "post": post,
        "comments": comments,
        "new_comment": new_comment,
        "comment_form": comment_form,
    }

    return render(request, "blog/post/display.html", context)โ€Š
inland oak
#

Not sure what to do with it.
I deal only with back and devops.
Front is still a mystery land for me

I can advice to try generating unique hash in your msg data

And validating that new recorded msg is not having the hash perhaps

#

It sounds as not perfect solution though ๐Ÿค”

uneven radish
#

Yeah!

#

Sounds like a workaround.

#

Also, the redirect commented works perfectly and do not add same comment again if user refreshes their webpage.

inland oak
#

I am afraid that you will have hash collisions in this case

#

Perhaps to use hash with time expiration in it

#

If hash was generated longer than N time ago. To ignore it

#

The time can be inbuilt into the hash and encoded

#

Extracted on decoding back

uneven radish
#

Umm... Still an overkill solution.

inland oak
#

Validating that new msg is not equal to previous one?

uneven radish
#

Why validate explicitly when Django can do that for me? And prevent resubmission.

#

If I use redirect, of course.

inland oak
#

It can? ๐Ÿค”

uneven radish
#

Well, not exactly "validate" but prevent form resubmission upon refresh.

inland oak
#

Oh, u mean... just wipe the field data after submission

uneven radish
#

Yup yup.

inland oak
#

That actually sounds like easier solution

#

Just redirect is not sure if best option to deal with it

#

Perhaps a bit of javascript

#

To clean stuff after you

uneven radish
#

Yes. It can help. Currently I'm trying to explore vanilla Django options to achieve this.

inland oak
#

I would try Svelte to do front part

#

It has jinja like language too that we got used in python

#

It should make smooth transition

uneven radish
#

Thanks. Will look into it. First time hearing it tho.

nova pewter
#

is it necessary to set up purge rules in order to use django-tailwind?

fallow temple
#

How to Django app as a client on laptop that is offline and push the data to your server when you get back online. plzz help

vestal hound
#

look up flexbox

proud lagoon
#

ive already installed the flask-login module

#

this is my first day working with flask, any help would be much appreciated

outer apex
# proud lagoon

can you share code where you're importing login_manager and defining it? they might be in 2 different files too

proud lagoon
#

sure, gimme a sec

#

oh god im sorry for wasting your time

#

there was a spelling mistake

#

in the import statement

#

lmaoo im sryyyy

outer apex
#

๐Ÿ‘

rotund perch
#

(NOTE: USING REST FRAMEWORK)
Hello, so I have a model that has a Title, Description, User(Foreign).
Getting all with the queryset model.objects.all() returns me many objects, for the serializer we can easily put serializer(model.objects.all(), many=True) but how do I access some attributes for every object I also want to add some data with the response for every object.

Ive did that with only one object of the model:

GetObject = model.objects.get(id=id)
serializer = ModelSerializer(GetObject, many=False)
data = { } 
    data['response'] = 'Success!'
    data['user'] = GetObject.user.username
    data['title'] = serializer.data['title']
    data['description'] = serializer.data['description']
    #etc....
return Response(data)

Ive also tried another way for multiple objects but I dont think its a good way to do it + I didnt know how to return that as a Response

  data = {

  }

  for objects in GetObject:
    objects_id = GetObject.get(id=objects.id).id
    objects_title = GetObject.get(id=objects.id).title
    objects_description = GetObject.get(id=objects.id).description
    data['id'] = objects_id
    data['title'] = objects_title
    data['description'] = objects_description
    print(data)
dusk portal
#
def notes_delete(request,note_id):
    if request.method =='DELETE':
        qset3=Notes.objects.filter(id=note_id).delete()
        messages.success(request,'DELETED')
        return HttpResponseRedirect(reverse('home:index'))
    return HttpResponseRedirect(reverse('home:index'))```
#

so what it is doing is it's directly rendering home page

#

not deleting

#

ohk done

lapis basalt
#

Hello,
Please is there any way in flask (with celery, redis or any other tool) to stock the user requests in a queue and proceed in each time only max 5 requests in parallels and then proceed the others and so one (like amazon sqs principle) to avoid sever over process capacity issues

opaque rivet
#

@lapis basalt I'd imagine you could do something like that with nginx

#

Override the .to_representation() method of your serializer (read the docs on this) - it allows you to modify the data in serializer.data

#

@rotund perch

rotund perch
opaque rivet
#

The docs probably do

rotund perch
#

Okay thank you!

lapis basalt
#

@opaque rivet Thanks! I will see

opaque rivet
#

Also I have a question, does each gunicorn worker spawn a django process?

#

Or do all the workers talk to a single django process

ivory thunder
#

Hi, I have a http client (phone app) that does not tell me what it is doing. Does anyone know how I can set up some test server to see what its requests look like? headers and data? (Thinking about e.g. httpbin.org but this does not show the request easily on the server side)

vestal hound
normal token
#

Hi, so my friends and i are thinking of working on a django project together and currently the whole project is on my pc. My question is can i share the whole project using GIT and if I succeed, do they just have to download the project and runserver to make it work (assuming they have the requirements.txt files)?

I was confused because there are commands such as manage.py startapp etc, and was wondering how to go about this. Thanks for helping a noob

ivory thunder
#

@vestal hound yes I just want to analyze the request details at first. Later I will write the server - the client is fixed, I just need to understand it so I can write the server side

ivory thunder
normal token
#

Cool
So it's not like startapp etc is mandatory right? Let me be clear.. so they can just download the project and run it on their pc?

ivory thunder
vestal hound
#

with one wildcard route

#

then just inspect the request objec

ivory thunder
vestal hound
ivory thunder
#

so I have 10 min left to do it...

normal token
ivory thunder
#

@vestal hound docker run httpbin is like 5 sec though!

ivory thunder
normal token
#

What's the other??

ivory thunder
#

There are many ways to work together. Keep people's competency and interests in mind, and if they're motivated you should be fine

#

@normal token there are 9 million. zipping code to sharepoint, deploying code to aws, docker-containers can deploy the app, ...

vestal hound
#
from fastapi import FastAPI

app = FastAPI()

@app.get("/{route:path}")
async def all_get(request: Request, route: str):
    print(route)
    print(request.headers)
    return None
#

repeat for POST, I guess

#

and the others if you need them

ivory thunder
#

@normal token maybe if you explain who the people are and what their tasks are, you'll get more concrete answers

#

@vestal hound brilliant, didn't think about the path trick there!

vestal hound
#

๐Ÿ‘‹

normal token
#

Oh ok
Its just my friends and I are thinking of making an e-commerce website and I have already made a few apps.. but i don't know how can I share the code with them except Github, even then I was confused with problems such as maybe they have to startapp etc

ivory thunder
normal token
#

Your answers made it clear, tho I'm worried I may have to get Github pro for that

normal token
#

there are 4 of us

vestal hound
#

but

#

it sounds like you're not familiar with devops

#

so this would be a good time to start

ivory thunder
#

ok, you might need github pro if your team uis larger than X, etc

vestal hound
#

there is this school of thought that "your app should be deployable with one command"

ivory thunder
#

agree, someone needs to handle the opsy stuff, deploying to a website etc

normal token
#

Oh ok.. so how do I share the code with them first of all?

#

So I need to grab someone in my class who's interested in devops now.. haha

#

or is devops something that is manageable to do alone?

ivory thunder
#

for working on code together, use git. Then put the git repo somewhere safe - github is one good option

#

@normal token someone needs to do it. Yes possible but it is some work if you want to automate everyting well

normal token
#

Cool!

#

Thanks a lot @ivory thunder ๐Ÿ™‚ Great help

vestal hound
#

and it's a good time to start

#

you can look at very basic things

#

like running your tests automatically

normal token
#

Cool I will look into it ๐Ÿ˜„
Devops- like aws etc?

vestal hound
#

AWS is one place you can deploy your project, yes

#

but devops, in general

#

is about turning your code into a working product

#

so integration, deployment, support, etc.

normal token
#

Oh ok! That's a good explanation, thanks!

vestal hound
#

np! it's not simple but it's always good to learn

normal token
#

๐Ÿ‘Œ ๐Ÿ‘Œ

pastel vessel
#

so im working on making a website to run off replit for now, mainly for testing, and running into an issue, here is my code ```py
#imports
def create_app():
@app.route("/")
async def home(self):
#doing stuff here
return app()

def setup():
create_app()``` so the issue im having is that i dont know where to tell it what host and port to run on

#

(lmk if this isnt the best place for this)

late gale
#

Hello i wanna ask a question can i make like a bot and integrate it with Django so when I add a post on my blog site it automatically add the same post and image on facebook and instagram , is that possible ?

devout coral
#

However, Iโ€™d suggest you look at the Facebook API as opposed to making a bot.

devout coral
#

I have a question, letโ€™s say I am making a Django application to track user availability. What is the best way to store the available times on a given day for a user?

I can think of two options but not sure which is best or if there is another alternative.

  1. Create an Availability model and an AvailabilityDay model that have a one to many relationship. I can then set the day of the week for the AvailabilityDay and a string of times(11AM,12AM,etc.) for the available times that day. Then I make some setter and getters for those times to use datetime objects.
  2. Have the same two models as above but add an extra model like AvailbilityTime that will simply store those available times as datetime objects with a one to many relationship.
    Thoughts?
vernal lotus
#

anytip for django modal?

vestal hound
#

soโ€ฆ

#

is that like regular availability?

#

i.e. it repeats every x period

#

or more like a calendar

vestal hound
devout coral
#

Regular availability yes. Say a user is available 11AM 1PM and 2PM on Sunday

vestal hound
devout coral
#

Yes exactly

#

So Iโ€™d only store a week

#

And that would be true every week

vestal hound
#

what are your predicted query patterns

#

like what kind of queries do you foresee yourself executing

devout coral
#

See who would be available at any given day/time

#

And of course see all available dates/times for a given user

vestal hound
#

so the thing is

#

hold up

#

which database?

devout coral
#

MySQL most likely. Maybe Postgres

vestal hound
#

so the thing is

#

Postgres has p good support

#

for datetime ranges

devout coral
#

Kinda torn between the two right now.

vestal hound
#

but these are concrete datetimes

#

whereas what you want to deal with is more abstract

#

i.e. โ€œany given Sunday at 1 PMโ€ vs โ€œthis particular Sundayโ€

#

so

#

there are a few ways to do it

vestal hound
#
  1. come up with a custom encoding of your data
#

one thing I did before was

#

encode each period

#

as a bit

#

(30 min IIRC)

#

then matching availability = bitwise AND

#

in hindsight maybe that was a bit overengineered

vestal hound
#

not modelling as concrete datetimes

#

but more likeโ€ฆa table with id, day, hour, minute columns?

sonic island
#

can anyone suggest something to make as a project using django and DRF?

vestal hound
#

then you have to perform the datetime logic manually

vestal hound
sonic island
vestal hound
devout coral
vestal hound
#

I personally donโ€™t like it but there isnโ€™t really a standard solution for this I believe

#

and itโ€™s not horrible but

#

well

#

you canโ€™t filter on database level

#

at least, not easily

#

if I understand you correctly

vestal hound
sonic island
vestal hound
#

how about a shop then

#

or a blog

novel grove
#

I have my own question via flask. letโ€™s say i have 2 users, user 1 and user 2. User 1 has info stored in a database and user 2 reads that info and removes it. Is there a way i can have user 2 tell user 1 info related to it. (like have them connect)

novel grove
#

or just interact in general

devout coral
novel grove
#

i want to have 2 separate sessions interact

#

is there a way for that

vestal hound
#

those are discrete ranges, right

sonic island
vestal hound
#

actually

#

you know what

#

in the abstract sense

#

you can think of the problem this way

#

each user is associated with a set of tuples

#

where each tuple contains the start and end index of a datetime range

#

e.g. (28, 32) would be 2 AM to 4 AM on Tuesday

#

assuming your week starts on Monday

vestal hound
devout coral
#

Well the day of the week thing Can simply be an int field in the day model so not worried about that.

vestal hound
#

at the moment

devout coral
vestal hound
#

so you have 168 rows per user

#

assuming 1 row per hour

#

and 24 hours per day

#

not too bad I guess

devout coral
#

Yeah, which is what I had thought of doing.

vestal hound
#

you could also check if thereโ€™s a more specialised database

#

for this use case

devout coral
#

Because instead of doing it like that I could simply make a model that just stores a time and have it relate to a model that stores the day.

devout coral
vestal hound
#

the query would be like

#

hm.

vestal hound
devout coral
#

And to optimize who goes to what task based on availability and some other factors.

vestal hound
#

I think? havenโ€™t done Django in a year ๐Ÿฅด

devout coral
#

Well. Iโ€™d probably look for users where their available days and times are within a specified range. Not sure what that availability__status represents.

#

But I think making models for the times and days makes it much simpler to create the queries for it.

#

I appreciate the feedback. Might pick your brain for some other insight as I finish organizing my project.

vestal hound
#

it becomes a question of efficiency

#

you could look into the bit type

#

feel like that would be best

#

atb!

devout coral
#

However, this might be premature optimization.

devout coral
vestal hound
#

my concern is more the accuracy of the data model

#

bits are harder to work with in Django

#

but it just seems like a nicer representation to me

#

shrugs

devout coral
devout coral
#

Another option is to have 24 Boolean flags in the AvailabilityDay model but that sounds like a nightmare lol

vestal hound
#

more like

#

how appropriate the data model is?

#

ease of use

devout coral
#

Yes, seems to be just a big table for no reason when you think about it I guess.

#

Since most of the rows would be similar since they only store one hour.

vestal hound
#

I like bits because itโ€™s just one column per user

#

and no joins required

#

and you can do everything in the DB

coarse yoke
#

hello there. do you have an experience with gzip on the heroku?

devout coral
#

Yeah, Iโ€™m thinking of something similar. But storing tuplesnof time objects.

#

For example letโ€™s say you have a AvailabilityTimeRange model with two fields upper and lower. You would store a range the user selects (upper=11AM, lower=11AM) or (upper=11AM, lower=6PM).
So then you would basically save multiple ranges if the person decides to have an hour gap or more and if there is no gap it just extends the range.

#

This would make the query a slightly more complex than storing the individual times but would decrease the amount of rows per user significantly.

vestal hound
devout coral
vestal hound
#

and even then

#

not sure if Django would support that

#

think you'd need raw SQL

devout coral
#

One way I can think of doing it which is not a great approach is to build a tuple or list for the required range so letโ€™s say (11AM, 12PM, 1PM) for 11AM-1PM. Then do the same for all the ranges in the availabilities and see if the required tuple is in the other.

devout coral
#

Yes

vestal hound
#

it's not hard in Python

devout coral
#

I mean, this is being built in Django after all.

vestal hound
#

but

devout coral
#

Donโ€™t have to do it at the database level right?

vestal hound
#

filtering in Python will not scale

vestal hound
devout coral
vestal hound
#

for any appreciable number of users it's unlikely to work

#

because you'd need to pull all that data over the wire

devout coral
#

Scalability is key, which was the big concern with the 168 rows per user

devout coral
#

Ok

#

Then I just go with that approach lol. Optimize later.

vestal hound
#

that would be like...at most a KB per user? with 1 million users that's only 1 GB

#

in general I would say compute is harder to save on than memory

#

so

#

go for whatever lets you optimise on the DB side

#

but YMMV

devout coral
#

Well, not just thinking of the space taken I meant the amount of time to query such a large table.

#

YMMV?

devout coral
vestal hound
vestal hound
#

so constant-ish time

#

remember that if you filter in Python

#

you'll need to pull every single record in the table

#

in general, you don't want anything you do frequently to be linear time and above

devout coral
#

Yeah, makes sense. Iโ€™ll go with that approach for now and optimize later as needed.

lapis reef
#

Even if the link is present, it does not work

west cove
#

hi,i need help in html actually i linked a webpage to submit button but when i try it it says HTML1423: Malformed start tag. Attributes should be separated by whitespace.

meager anchor
#

@west cove show your tag

dusty moon
#

anyone knows how do i get gradient text using CSS?

novel grove
#

is it possible for 2 seperate sessions to interact with each other?

#

my only thought to make this possible is for every session to have a interaction endpoint so like '/user/interact/username' or something like that

#

am i wishfully thinking? or is something like that actually possible

#

and or is there any other way to have this work

storm laurel
#

programming is only words

#

And rap or eletrical machines

#

And words

storm laurel
#

Just trainning for my interview

outer apex
novel grove
vestal hound
#

do you mean that?

#

or do you want, in general, two users online at the same time to have the ability to interact

vestal hound
#

anyways

#

it depends on your needs

#

if realtime, like chat or a game

#

I would suggest websockets

#

but even vanilla HTTP requests will work

novel grove
vestal hound
novel grove
#

so via that could i establish a 'websocket' or is a websocket a whole diffrent thing

vestal hound
#

websockets basically let you maintain a connection to a server

#

and transmit data bidirectionally

#

on the other hand, requests open new connections each time they are made

#

and only allow initiation by the client

novel grove
#

just something to help me get started in this

outer apex
novel grove
#

ight thanks

proud lagoon
#
<html>
<head>
  <link rel="stylesheet" href="style.css">

</head>
<body>
  <div class="basic">
      <div class="box">
      </div>
  </div>

</body>
</html>


{% extends "base.html" %} {% block title %}Register{% endblock %} {% block
  content %}
  <form method="POST">
    <h3 align="center">Register</h3>
    <div class="form-group">
      <label for="email">Email Address</label>
      <input
        type="email"
        class="form-control"
        id="email"
        name="email"
        placeholder="Enter email"
      />
    </div>
    <div class="form-group">
      <label for="firstName">First Name</label>
      <input
        type="text"
        class="form-control"
        id="firstName"
        name="firstName"
        placeholder="Enter first name"
      />
    </div>
    <div class="form-group">
      <label for="password1">Password</label>
      <input
        type="password"
        class="form-control"
        id="password1"
        name="password1"
        placeholder="Enter password"
      />
    </div>
    <div class="form-group">
      <label for="password2">Password (Confirm)</label>
      <input
        type="password"
        class="form-control"
        id="password2"
        name="password2"
        placeholder="Confirm password"
      />
    </div>
    <br />
    <button type="submit" class="btn btn-primary">Submit</button>
  </form>
  {% endblock %}
#
*{
    margin: 0;
    padding: 0;
}
.basic{
    height: 100%;
    width: 100%;
    background-image: linear-gradient(rgb(154,204,255), rgb(56,182,255)), url(images/md.jpg);
    background-position: center;
    background-size: cover;
    position: absolute;
}
#

everything works, but the css modifications dont show up :(

tepid fern
#

you sure the html and css file are in the same folder?

fallow meteor
#

does query.get and filter do the same thing in sql

jovial cloud
proud lagoon
#

one

#

@jovial cloud

jovial cloud
#

I can see that some semicolons are missing in the JS code

jovial cloud
# proud lagoon one

If you're extending base.html there shouldn't be any html tags before it or even anywhere at all. Extending copies the html from base.html and pastes it in your new html file with Jinja.
Also, can I see your base.html file

opaque rivet
#

@native tide the click event listener has an undefined variable, clicks

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

proud lagoon
jovial cloud
proud lagoon
#

sure

#

i hope it works

#

it doesnt :(

opaque rivet
#

@native tide I know, look in your "click" event listener. Where is the clicks variable?

#

@native tide aah I see, I didn't see it. So, what is the issue?

dapper perch
#

anyone with experience with discord bot dashboard?

jovial cloud
# proud lagoon it doesnt :(
{% extends "base.html" %} {% block title %}Register{% endblock %} {% block
  content %}
  <form method="POST">
    <h3 align="center">Register</h3>
    <div class="form-group">
      <label for="email">Email Address</label>
      <input
        type="email"
        class="form-control"
        id="email"
        name="email"
        placeholder="Enter email"
      />
    </div>
    <div class="form-group">
      <label for="firstName">First Name</label>
      <input
        type="text"
        class="form-control"
        id="firstName"
        name="firstName"
        placeholder="Enter first name"
      />
    </div>
    <div class="form-group">
      <label for="password1">Password</label>
      <input
        type="password"
        class="form-control"
        id="password1"
        name="password1"
        placeholder="Enter password"
      />
    </div>
    <div class="form-group">
      <label for="password2">Password (Confirm)</label>
      <input
        type="password"
        class="form-control"
        id="password2"
        name="password2"
        placeholder="Confirm password"
      />
    </div>
    <br />
    <button type="submit" class="btn btn-primary">Submit</button>
  </form>
  {% endblock %}

This is how your 2nd html should look. And put your class(for styling) either in your base.html or the 2nd html file

proud lagoon
#

my 2nd html file does look liek that

#

i also added the class in base.html

#

it didnt wor

#

work*

sonic island
#

how to use "has_module_perms" in django to provide custom permissions to AbstractBaseUser?

main grail
#

How to do the text will change color after one second

modern edge
#

how would i know if a user's session is over so that i can clean up the user's temporary files on the server? (Flask)

main grail
#

How to do button will look like this?

sonic island
main grail
sonic island
sonic island
woeful atlas
#

Hi

#

Is it a good idea to make a vpn with python?

main grail
sonic island
main grail
#

quart

#

from quart import *

calm plume
woeful atlas
#

and performance levels?

calm plume
#

No idea. But I would think it's pretty hard to make in Python

modern edge
#

is it a paid host?

#

which is?

#

oh repl

#

it shutdowns when u exit doesnt it?

main grail
#

background: black;

#

im using css too

#

i dont need to put background-color background works to :)

modern edge
#

nice

#

lol

#

do u use flask?

#

i see

calm plume
#

That's JavaScript with expressjs, not Python with Flask

#

And that's not all that hard to understand if you know the basics of node.js