#web-development

2 messages · Page 163 of 1

ivory bolt
#

hey, I tried something and it worked

hollow apex
#

oh

#

tell me

#

RIGHT NOW

ivory bolt
#
from random import randint
app = Flask(__name__)


@app.route('/home')
@app.route('/')
def home_page():
    return render_template('home.html',the_title = 'Home')



@app.route('/random',methods=['GET', 'POST'])
def random_page():
    if request.method == "GET":
        return render_template("random.html")
    if request.method == "POST":
        range_start = request.form['start']
        range_end = request.form['end']

        result = randint(range_start,range_end)
        return render_template('random.html',the_title = 'Random Generator',the_result = result)

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

so you need to do something for a get request as well right

#

oops! wait, though the page finally loads, I messed something up

#

wow I'm dumb

hollow apex
#

nicee

#

so when you click generate

#

it shows this

#

and I have zero idea where it gets converted into int

ivory bolt
#

lol wait

#

friend me

#

I'll continue this on my server it may get spammy here

hollow apex
#

okay I did

fast siren
#

Hi, I have a question about flask.
So from what I gathered you use this to declare a variable that every template can use

@app.context_processor
def inject_stage_and_region():
    return dict(some_name=variable)

And I was wondering, how can I modify that variable?
For example, you store a logged_in variable and when the user logs out you update it and now every template knows the user logged out. Is that possible?

opaque rivet
#

CORS is enforced by all major browsers, (and they don't change your code) - so that's a bit ambiguous

left jackal
#

Sorry language barreer I mean what is the best browser that's not blocking your code.

#

google CORS started blocking my code during one web scraping project

late gale
#

does anyone know why i dont recieve any money from sandbox paypal

mint folio
#

In both accounts or just one?

late gale
#

both accounts

#

Business and default

#

I found a notification it says

#

idk what's the problem of my code that did this

mint folio
#

Are you sure it’s sandbox because as far as I know in sandbox environment payments don’t go through review.

late gale
#

yes it is

mint folio
#

Right then maybe there might be a setting to turn off payment review

#

The setting will be account side and not an issue with the code.

late gale
#

i just turned them off

#

let me try

#

not working

#

aaah yees

#

its a problem in the code

#

i added an alert but it's not showing

#

i still dont see alerts

#

cause its an account problem let me see

mint folio
#

You are paying with your sandbox account right?

#

The personal one

late gale
#

yes

mint folio
#

Do you get any responses back from the API requests you make to them?

#

This reminds me PayPal is an absolute pain integrating. It’s documentation and API is horrible compared to other gateways.

late gale
#

idk what's the problem tbh why its refusing to send money

#

what do i do now

#

shall i delete app and create a new one ?

#

ooh it worked

#

when i created platform app it worked now the alert appears

opaque rivet
#

@left jackal firstly, CORS doesn't block your code. It blocks the browser/client from parsing the response from the server.

Are you sure you're actually web scraping and not sending a request to the API

keen berry
#

yo guys can someone tell me how to detect for automated browsers using django

#

like if i detect automated browser, display captcha

#

if no automated browser detected, dont display captcha

civic pewter
#

Need help 😕

#

I wanted to know how I can save a photo that will contain a watermark. Currently grabs a photo from the form and creates a watermark on it, but saves it separately. More precisely, I would like the photo I send in the form to be processed and saved.

#
    if request.method == 'POST':
        form_w = ImageForm(request.POST, request.FILES)
        if form_w.is_valid():
            # form = form_w.save(commit=False)

            cd = form_w.cleaned_data['img']


            im = Image.open(cd)
            width, height = im.size

            draw = ImageDraw.Draw(im)
            text = "TEST WATERMARK"

            font = ImageFont.truetype('arial.ttf', 36)
            textwidth, textheight = draw.textsize(text, font)

            # calculate the x,y coordinates of the text
            margin = 10
            x = width - textwidth - margin
            y = height - textheight - margin

            # draw watermark in the bottom right corner
            draw.text((x, y), text, font=font)

            print('Before saving: ', im)

            im.save('Luki/media/upload_p/{}'.format(cd))

            img = Image.open(('Luki/media/upload_p/{}'.format(cd)))
            print('After saving: ', img)

            form_w.instance.save()

            return redirect('Luki:gallery')
    else:
        form = ImageForm()
    return render(request, 'Luki/upload_img.html', {
        'form': form,
    })```
dusky harbor
#

hey is this the correct place to ask for help with Web3?

rough urchin
#

Hii

leaden path
#

Hi everyone.

rigid prairie
#

python web development courses

#

can anyone recomm

#

please

leaden path
#

I think you can do udemy courses for python web development.

#

@rigid prairie

rigid prairie
leaden path
#

Which framework, you want to learn?

#

@rigid prairie

rigid prairie
#

django is my preference

#

i think

ivory bolt
#

k so don't udemy when you can learn for free

#

The one course I ALWAYS recommend for beginners is one taught by coding for entrepreneurs

leaden path
#

python have a lots of framework so you have to choose which one you want to learn? and Every framework have some facility and objective. So i think What do you want to do in future then you have to choose framework it will be better.

ivory bolt
#

I'll send a video

leaden path
#

@rigid prairie

ivory bolt
#

@rigid prairie , django and Flask are great frameworks -- you should chose now wether you want to build complex web-apps or simpler ones

rigid prairie
#

i really wanna make web apps like chat app, and something on ethe line

ivory bolt
#

django is more comprehensive than flask, but it's not too difficult to learn as a first framework

rigid prairie
#

oh

ivory bolt
rigid prairie
#

so where should i start from

ivory bolt
#

I'll drop a link here

leaden path
ivory bolt
#

Learn the Python Django framework with this free full course. Django is an extremely popular and fully featured server-side web framework, written in Python. Django allows you to quickly create web apps.

💻Code: https://github.com/codingforentrepreneurs/Try-Django

⭐️Course Contents ⭐️
⌨️ (0:00:00) 1 - Welcome
⌨️ (0:01:14) 2 - Installing to Get ...

▶ Play video
#

this is the first video I'd recommend -- for anything supremely SPECIFIC, if you can't get a particular thing right in django, check out Corey Shafer on yt

#

<pronoun> also has great videos for any specific PART or module, though I'd suggest to watch him after you learn the fundamentals

ivory bolt
ivory bolt
#

for a coding walkthrough of building a chat app, Corey Shafer and Dennis Ivy (watch in the future) will be great

rigid prairie
#

sure

#

thanks man

rigid prairie
stark tartan
#

Django with mangoDB or postgrsql SQL is good I am building large project

ivory bolt
#

I've not tried Mongo but PostgreSQL is good

#

it won't be as instantaneous as something like dbsqlite, but it's more robust and secure overall of course

#

not to mention

#

open

#

source

#

🙂

leaden path
#

I think, PostgreSQL will be best.

ivory bolt
#

yep

#

I can give you the setup guide for integrating postgres with django later

keen berry
#

guys

#

django

ivory bolt
#

quick google: If you want to use a database-backed session, you need to add 'django. contrib. sessions' to your INSTALLED_APPS setting. Once you have configured your installation, run manage.py migrate to install the single database table that stores session data.

#

Gimme a sec

keen berry
#

wat

#

i have session data

#

like request.session['user'] = "John"

#

how do i get "John" from the consumer

ivory bolt
#

waitup

keen berry
#

ok nvm

#

@ivory bolt its ok ik now

#

i used self.scope['session']['user']

#

thanks anyway

native tide
#

Hello

#

can python also make websites

#

I am a experienced web developer

#

Not much JS

#

But HTML and CSS

rigid prairie
#

how do i start a virtual env

#

in windows

#

i tried activate/Scripts

#

not working

#

i am in the venv name directory

#

trydjango

#

nope

#

for begginers

#

can i just use pycharm?

#

it has virtual env

#

kk

#

i will use that

#

then

#

it is easier

#

it should be like this Scripts\activate

#

but it is not working for some reason

#

yeah

#

lemme

#

in my pc it does not works with this

#

iyeah

#

that works

#

no respond

ivory bolt
#

have you tried deploying react on another local machine/virtual machine and tested that first

#

wait

rigid prairie
#

no response

#

C:\Users\Prabal\dev\venv\Scripts\activate.bat

#

also no work

#

done

ivory bolt
#

@covert cosmos this is what’s you want to do right

#

I personally don't have much experience with deployment or system architecture in general

#

but

#

setting up another instance and communicating between one another IS POSSIBLE

rigid prairie
#

the name is trydjango

ivory bolt
#

for large scale projects yes

rigid prairie
ivory bolt
#

the idea is you want the user to be able to see the frontend FAST

#

and you don't wanna load your chunky backend with it

#

what's your project like

rigid prairie
ivory bolt
#

and wether you can actually implement it

#

My question still stands

#

what type of app are you biilding

#

*building

#

and wether you know HOW to run the react app independently from django and deploy it on another instance

coarse heart
#

Hey this is me on mobile

#

Explain comprehensively

#

Cuz no blog app needs fullstack 😂

#

I suggest deploy on one backend for low traffic

#

But guy larger scale or experimental purposes, create another instance and run

#

It's gonna cost you a bit more

#

Brroooo

#

Not a blog app 😂

#

On a scale of 1-10, how heavy is the project

#

I recommend running another instance if this is something a lot of people are gonna use

#

Yep

#

I'll do some research and get back to you though

#

It could cost you so let's see if it's worth it

lyric raptor
#

how long would it take for a begineer to build a landing page with python

coarse heart
#

Yep... Architecting systems is pretty interesting

coarse heart
#

Especially on the backend

paper pier
lyric raptor
#

django or flask tho

coarse heart
#

I can help you get started with Flask if you want to just build super quick

#

With limits

lyric raptor
coarse heart
dusk portal
#

Oh proz

#

when this noob @dusk portal will become pro thinkmon

vestal hound
#

what do you mean by that

#

SQL table?

paper pier
rigid prairie
#

hey

#

do i need to learn css and js for django>

#

?

stone wren
#

[django]

took backup of the staging server database,

restored it in dev environment.

no matter what object, model I try to update, I get

IntegrityError

null value in column "id" violates not-null constraint DETAIL:  Failing row contains

we also have django-defender setup, so even when logging in, it tries some db transactions, and get the same error,

what would be the issue? has anyone faced this?

paper pier
vestal hound
#

in tables

paper pier
late gale
#

Can someone please tell me why this is happening

#

i didnt do anything

#
def contact(request):

    if request.method == "POST":
        name = request.POST['name']
        subject = request.POST['subject']
        message = request.POST['message']
        email = request.POST['email']
        try:
            validate_email(email)
            send_mail(
                subject,
                "Email: {}\n\nMessage: {}".format(email, message),
                'from@example.com',
                [settings.EMAIL_HOST_USER],
                fail_silently=False,
                 )    
#

anyone ?

inland oak
#

looking for your except

late gale
#

that's the whole contact view

def contact(request):

    if request.method == "POST":
        name = request.POST['name']
        subject = request.POST['subject']
        message = request.POST['message']
        email = request.POST['email']
        try:
            validate_email(email)
            send_mail(
                subject,
                "Email: {}\n\nMessage: {}".format(email, message),
                'from@example.com',
                [settings.EMAIL_HOST_USER],
                fail_silently=False,
                 )        
    
        except ValidationError:
            messages.error(request, "please enter a valid email")
            
        Contact.objects.create(name=name,email=email,subject=subject,message=message)
        
        return render(request, 'base/contact.html', {"name": name})

    return render(request, 'base/contact.html', {'title': 'Contact'})
#

ok let me show u more of error

inland oak
# late gale that's the whole contact view ```py def contact(request): if request.metho...

just add prints...

def contact(request):
    print("debug 1")
    if request.method == "POST":
        print("debug 2")
        name = request.POST['name']
        print("debug 3")
        subject = request.POST['subject']
        message = request.POST['message']
        email = request.POST['email']
        try:
            print("debug 4")
            validate_email(email)
            print("debug 5")
            send_mail(
                subject,
                "Email: {}\n\nMessage: {}".format(email, message),
                'from@example.com',
                [settings.EMAIL_HOST_USER],
                fail_silently=False,
                 )        
            print("debug 6")
    
        except ValidationError as error:
            print(f"debug error: {error}")
            messages.error(request, "please enter a valid email")
        print("debug 7")            
        Contact.objects.create(name=name,email=email,subject=subject,message=message)
        print("debug 8")
        return render(request, 'base/contact.html', {"name": name})
    print("debug 9")
    return render(request, 'base/contact.html', {'title': 'Contact'})
#

and check where they will stop)

#

as possible reason, send_mail could be broken

late gale
#

oh ok

inland oak
#

as alternative, perhaps POST request is not working

#

and it is not entering your if at all

late gale
#
          <form action="{% url 'Contact' %}" method="POST">

Here is the opening form tag

#

let me try to print the view and it see if it works

#

so it displayed
debug 1
debug 2
debug 3
debug 4
debug 5

#

so send mail is the problem

#

let me update django and see if it's working

#

not working

#

idk what's the issue

#

@inland oak

inland oak
#

how the output to console changed

#

after disabling send_mail?

late gale
#

nothing

#

let me comment send mail

#

all debug are showing to 8

rigid prairie
#

what is wrong?

inland oak
#

think about enabling debug mode for your framework

#

it should be possible in its settings

#

it will describe more throughly what's wrong after rendering template

cold socket
#

Anyone here create Alexa skills before using Flask or something?

inland oak
#

yup

late gale
#

it's already true

inland oak
#

which framework is it

late gale
#

Django

inland oak
#

perhaps it is not True True

#

all right. that's easy then

#

it is true)

late gale
#

yes

inland oak
#

I don't know then

#

I rendered POST templates only one time in my life

late gale
#

oh 😦

late gale
#

I updated django and still not fixing it

#

it's something related to send_email

inland oak
#

¯_(ツ)_/¯

rigid prairie
#

this error is showing up

late gale
#

yes

rigid prairie
#

help

#

what si wrong here

inland oak
#

you are over shadowing it

rigid prairie
inland oak
#

!e

var = 5
print(type(var))
lavish prismBOT
#

@inland oak :white_check_mark: Your eval job has completed with return code 0.

<class 'int'>
inland oak
#

remove variables named type if you have them

rigid prairie
#

i am in django

#

i did not use type anywhere

inland oak
#

¯_(ツ)_/¯
not enough information to guess anything else then

#

perhaps you are iterating wrongly over QuerySet object, or where you expected to have QuerySet

rigid prairie
#

do u know any course where latest django version is used>?

rigid prairie
#

thx

late gale
#

Im really depressed that my code is showing error without any change

#

is SMTP server down or something

inland oak
#

some email settings tuning is required

late gale
#

it was working clean

#

but i tried it today its not

#
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
           
EMAIL_HOST = 'smtp.gmail.com'

EMAIL_PORT = 587

EMAIL_USE_TLS = True

EMAIL_HOST_USER = 'MYEMAIL'

EMAIL_HOST_PASSWORD = 'PASSWORD'
indigo vessel
#

roadmap for web development

late gale
#

So there isnt any fix for issue it prevents all my email from being sent

late gale
#

there

#

it says check dns server

#

how to do so

inland oak
#

perhaps to try binding to 0.0.0.0:8000

late gale
#

nslookup smptp.mail_host.com this shows error

#
Server:  one.one.one.one
Address:  1.1.1.1

*** one.one.one.one can't find smptp.mail_host.com: Non-existent domain
late gale
inland oak
late gale
inland oak
#

to have public dns like 8.8.4.4

late gale
inland oak
#

ping 8.8.4.4

#

can you see it?

late gale
inland oak
#

yeah

late gale
#

let me add it wait

inland oak
#

would not it be perfect)

#

for google email

late gale
#

let me try now

inland oak
#

also

#

running from Windows server is a bit weird

#

not really efficient

#

did you think about getting linux vps

late gale
#

still not working

inland oak
#

shrugs

late gale
#

I changed my etherenet dns or should i change router dns

#

i believe it wont work either

#

now it shows this

Server:  dns.google
Address:  8.8.8.8

*** dns.google can't find smptp.mail_host.com: Non-existent domain
inland oak
#

did you change it on windows server?

late gale
inland oak
#

perhaps you have wrong smtp server address

#

I am actually having google email working too in django

late gale
inland oak
# late gale how to check

my mail sender

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from django.conf import settings
from types import SimpleNamespace
from django.template import Context, Template
import os


def send_mail(mail):
    """Function capable to send google email
    from google email address"""
    # commaspace = ', '
    message = MIMEMultipart("alternative")  # create a message
    message["Subject"] = mail.subject
    message["From"] = settings.MAIL_USERNAME
    message["To"] = mail.address  # commaspace.join(mail.recipients)
    message.attach(MIMEText(mail.text, 'plain'))

    if hasattr(mail, 'html'):
        message.attach(MIMEText(mail.html, "html"))

    server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
    server.ehlo()
    server.login(settings.MAIL_USERNAME, settings.MAIL_PASSWORD)
    server.send_message(message)
    server.close()


def send_verify_email(name, url, address):

    context = Context({"name": name, "url": url})
    with open(os.path.join('main', 'templates', 'email',
                           'verify_email.txt')) as file_:
        txt = Template(file_.read())

    with open(os.path.join('main', 'templates', 'email',
                           'verify_email.html')) as file_:
        html = Template(file_.read())

    mail = SimpleNamespace(subject='test subject',
                           text=txt.render(context),
                           html=html.render(context),
                           address=address)
    send_mail(mail)
#

I was a little bit of pervert when I chose SimpleNamespace, don't mind it

late gale
#

so should i convert this EMAIL_HOST = 'smtp.gmail.com' to this EMAIL_HOST = 'smtp' but i believe i shouldnt

inland oak
#

do what you wish. You can just copy my google mail sender, in bits you need

late gale
#

and wanna try your port

#

now i have a new error

#
getaddrinfo failed
#

oh waiit

#

still not working

#

this is a disaster

#

Can this fix it ?

late gale
dusk portal
#

ik about flask

#

im good at that

#

idk django

#

and i am stuck

late gale
#

they are similar

dusk portal
#

but fetching from db and some things remains same

late gale
#

idk my website was working correctly now not

#

idk whyy

dusk portal
#

are u free can u come voice chat ,can u help me plz

dusk portal
late gale
dusk portal
#

open this

#

then scroll down after a minimal application

#

u can see some text like this

#
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse

from .models import Choice, Question
# ...
def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = question.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        # Redisplay the question voting form.
        return render(request, 'polls/detail.html', {
            'question': question,
            'error_message': "You didn't select a choice.",
        })
    else:
        selected_choice.votes += 1
        selected_choice.save()
        # Always return an HttpResponseRedirect after successfully dealing
        # with POST data. This prevents data from being posted twice if a
        # user hits the Back button.
        return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))```
#

so some questions , doubts and problems in it

#

oh

rigid prairie
#

oh

dusk portal
#

oh

rigid prairie
#

NOTE: Updated and compatible with Django 3.0

In this video I'll introduce my django crash course series. In these tutorials we will will be building a customer management app. Part one will cover installing django and getting our basic app setup.

Follow me on Twitter: https://twitter.com/dennisivy11
Linkedin: https://www.linkedin.com/in/dennis...

▶ Play video
#

is this one

#

good

#

for begginers

#

cause the previous one was using django 2.0.7 which is full of bugs

brisk vessel
#

hey iam new here

late gale
dusk portal
#

hey

#

can u guyz help me out

#

clearing my doubts

#
<form action="{% url 'app1:detail' question.id %}",method="POST"></form>
{% csrf_token %}
<fieldset>
    <h1>{{question.question_text}}</h1>``` i have not taken this question.question_text i mean not written inside for loop then too workinng + its given in the docs too
#
def detail(request,question_id):
    question = get_object_or_404(Question, pk=question_id)
    question={'question':question}
    return render(request,'app1/detail.html')``` iis it because this question
brisk vessel
dusk portal
#

@late gale bruh help plz

#

how bruh thats what asking i havent used there any for loop

#

how

late gale
#

what are u trying to do

dusk portal
#

oh so we r fetching it from?

#

how without question thats the issue

late gale
#

they both are perfect

#

is there any error occuring

dusk portal
#

but first docs as my friend @H0NCHO said

dusk portal
late gale
#

if you prefer videos or reading

#

i personally prefer videos

dusk portal
#

i myself too

#

but started

#

and done till some end

#

now ig i cant leave it like that

ivory bolt
#

often times it's a TCP thing

#

sometimes a pending TCP connection on one end from a client gives out a timeout error

late gale
#

let me try 25

ivory bolt
#

check out the default email port

late gale
#

its 587

#

as in the app

ivory bolt
#

look it could just be some TCP thing, if it's not working today it could work tomorrow

#

restart your server a couple fo times maybe

opaque rivet
#

@dusk portal please can you be more specific with the errors you encounter? Saying "it's not working" does not help people answer your questions.

late gale
late gale
#

i changed my dns to google

ivory bolt
#

wut no I ain't a legend that can fix ur printer I wouldn't know how to restart a pc

#

seriously tho no

opaque rivet
#

Be specific with questions then

ivory bolt
#

seriously tho I can't fix ur printer

late gale
ivory bolt
#

m joking

late gale
#

lol

ivory bolt
#

completely out of context

late gale
#

so what should i do now

#

I cant find a solution for it

dusk portal
#

as im learning from docs so they showed this py <form action="{% url 'polls:vote' question.id %}" method="post"> {% csrf_token %} <fieldset> <legend><h1>{{ question.question_text }}</h1></legend> so in last line we are not fetching it inside for loop so how is it possible ,as per me it can be 2 reasons cez in db question=ForeignKey or cez in my view ```py

def detail(request,question_id):
question = get_object_or_404(Question, pk=question_id)
question={'question':question}
return render(request,'app1/detail.html',question)``` this is detail

late gale
#

I allowed port 25 , 80 on my firewall

#

thought they are disabled

dusk portal
late gale
#

and nothing happened

dusk portal
#

@opaque rivet where u gone sir 👀

opaque rivet
#

@dusk portal you didn't even show any for loop

dusk portal
#

i myself is amazed after seeing this

#
#my class Choice
class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)
    ```
ivory bolt
opaque rivet
#

Firstly, I don't know what the issue is.
You're rendering the question_text attribute of your question.

#

There is no for loop there

#

I have no clue why you're talking about a for loop

late gale
#

its like an error without any reason

ivory bolt
#

i found something and it seems to make sense

late gale
#

let me try

ivory bolt
#

this is very similar to your question here and basically you're unable to connect to the email server

late gale
#

telnet isnt recognized

opaque rivet
#

Probably not connected to smtp server

late gale
#

let me allow it on windows

#

found this that can enable it

#

@ivory bolt It says this

#

Connecting To smtp.xxxx.com.kh...Could not open connection to the host, on port 25: Connect failed

#

so no connection to 25 port ?

#

let me see if its enabled in firewall

coarse heart
#

That's not it

late gale
#

then what it is

coarse heart
#

Read the post and understand it completely

#

That's something for a development server

late gale
#

but that on linux

opaque rivet
late gale
#

im using windows

late gale
opaque rivet
#

@late gale connect to your provider's smtp server

#

That is literally a placeholder

opaque rivet
#

Following their docs

late gale
#

where

#

when i typed django smtp it led me to send email

opaque rivet
#

Ok, follow them docs then

#

You need the SMTP server of your mail provider

late gale
#

Can u please elaborate

#

This is my first time to deal with something like this

opaque rivet
#

If you plan to send emails from your gmail mail, you need to connect to the smtp server to send said emails.

smtp.xxxx.com.kh is a placeholder. (if you can't tell, its because of the 4 xs).

So obviously you can't connect to a server that doesn't exist.

#

Pretty sure just following django docs should sort this out for you.

late gale
#

it doesnt has anything related to smtp configuration , I added everything and it was working fine i swear last week

#

please consider that this problem is intense the website is sending emails everywhere so something like this could destroy organization website

opaque rivet
#

It does have information related to SMTP configuration

late gale
#
EMAIL_HOST = 'smtp.gmail.com'

EMAIL_PORT = 587

EMAIL_USE_TLS = True

EMAIL_HOST_USER = 'EMAIL'

EMAIL_HOST_PASSWORD = 'PASSWORD'

DEFAULT_FROM_EMAIL = "ORGANIzation <noreply@ORGANIzation .com>"
#

and not working

opaque rivet
#

For gmail, you have to go into your account settings and tick allow unsecure access.

#

Did you do that?

late gale
#

where

opaque rivet
#

Search it up. Something about gmail insecure access

late gale
#

I allowed to create app in google

opaque rivet
#

I have no clue what you just said

late gale
#

I created an app password in google so i can connect my gmail to django

#

It was working fine last week

#

omg

opaque rivet
#

Look at a guide to setup gmail with Django. It'll tell you the settings to change to allow you to connect to googles smtp servers.

late gale
#

I dont believe the problem is connection between django and gmail

#

because it was working

#

the problem is in smtp server

#

cant connect to

opaque rivet
#

Exactly, which is what I just said.

late gale
#

and still its connected to gmail

#

oooh

#

waaaait

#

should i remove 2FA

#

and try ? @opaque rivet

opaque rivet
#

Yes, that's the setting, just follow a guide further

late gale
#

ook

#

ok its off now let me try

opaque rivet
#

Make sure you enable less secure app access

#

not just disable 2FA

late gale
#

ooh so i should make it on

#

ok

opaque rivet
#

🤦‍♂️

late gale
#

hahaha

#

still not working

#

i will kill my self

#

🔪

#

😭

#

@opaque rivet

#

Cry with me

#

Cant this problem be erased from Earth

#

let me try to restart the pc and wish for a miracle

#

Not working

#

Anyone ? this is really depressing

ivory bolt
#

wow

#

this is fucking depressing

#

apologies for the five year-olds

late gale
ivory bolt
#

I mean fudging

#

oh k

#

nice!

late gale
#

hahaha

#

Im screaming

#

HELPP!

ivory bolt
#

k wait

late gale
#

Like seriously im done of this Why is it doing like this

ivory bolt
#

send me all ur code

#

hop onto pm

#

*dm

#

and friend request

late gale
#

and report

#

for tryinh to hack

#

Jokin g

#

let me send here

ivory bolt
#

XD

#

xD

mint folio
#

What’s your current setup? 2fa and app password?

late gale
#

views.py

def contact(request):
    print("debug 1")
    if request.method == "POST":
        print("debug 2")
        name = request.POST['name']
        print("debug 3")
        subject = request.POST['subject']
        message = request.POST['message']
        email = request.POST['email']
        try:
            print("debug 4")
            validate_email(email)
            print("debug 5")
            send_mail(
                subject,
                "Email: {}\n\nMessage: {}".format(email, message),
                'from@example.com',
                [settings.EMAIL_HOST_USER],
                 )        
            print("debug 6")
    
        except ValidationError as error:
            print(f"debug error: {error}")
            messages.error(request, "please enter a valid email")
        print("debug 7")            
        Contact.objects.create(name=name,email=email,subject=subject,message=message)
        print("debug 8")
        return render(request, 'base/contact.html', {"name": name})
    print("debug 9")
    return render(request, 'base/contact.html', {'title': 'Contact'})
late gale
#
EMAIL_HOST = 'smtp.gmail.com'

EMAIL_PORT = 587

EMAIL_USE_TLS = True

EMAIL_HOST_USER = 'NO x 10^99'

EMAIL_HOST_PASSWORD = 'NOOOOOOO'

DEFAULT_FROM_EMAIL = "NoOO<noreply@NOO.com>"

Settings.py

mint folio
#

And so what happens currently? Where is the error or issue?

mint folio
#

Also have you tried any local test mail providers. Just to rule out if it’s gmail or your code?

late gale
#

yup i tried smtp test on google and it worked perfectly

karmic girder
#

unable to authenticate using django form

views.py

from django.shortcuts import render
from django.contrib.auth.models import User
from django.shortcuts import redirect
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import authenticate, login
from .forms import LoginForm

def Register(request):
if request.method == 'POST':
    form = UserCreationForm(request.POST)
    if form.is_valid():
        data = form.cleaned_data
        user = User.objects.create(username=data['username'],
                                   #    password=data['password1']
                                   )
        user.set_password(data['password1'])
        user.save()
        return redirect('/')

form = UserCreationForm()

context = {
    'form': form
}
return render(request, 'register.html', context)


def LoginUser(request):
if request.method == 'POST':
    form = LoginForm(request.POST)
    if form.is_valid():

        

        data = form.cleaned_data
        user = authenticate(
            request, username=data['username'], password=data['passsword'])
        print(data)
        print(user)

form = LoginForm()
context = {
    'form': form
}
return render(request, 'login.html', context)

forms.py

from django import forms

class LoginForm(forms.Form):
username = forms.CharField(max_length=100,)
passsword = forms.CharField(widget=forms.PasswordInput)

output

Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
{'username': 'abc', 'passsword': 'abc'}
None
[11/Jun/2021 17:00:47] "POST /login HTTP/1.1" 200 3330
{'username': 'abc', 'passsword': 'abc'}
None
[11/Jun/2021 17:01:05] "POST /login HTTP/1.1" 200 3330

late gale
#

Tried this

#

added my google account and added smtp.gmail.com and port 587 and worked

#

so the problem is in my project ?

ivory bolt
#

maybe it's your local machine

mint folio
#

Which is why i said have you tried with other local test mail providers.

late gale
#

didnt try anything other than smtp

ivory bolt
late gale
#

how to try other mail provider then

mint folio
#

Test with something like mailhog or papercut

late gale
#

tried mailhog

#

im not good with these stuffs just beginner with the mail servers

opal agate
#

hi guys i have been following a tutorial on django ,and i was doing the same as the tutorial untill he started using css and js ,so i have copied his tamplate and pasted in the right folder

nimble epoch
#

@late gale did you setup two auth for you gmail? and did you create app password?

opal agate
#

but the result was different

late gale
nimble epoch
#

and your EMAIL_HOST_USER and EMAIL_HOST_PASSWORD are set correctly i mean not these examples that youve used here right?

late gale
#

Yup they are

#

daamn the whole server is trying to help me and this problem cant be fixed yet

#

Im really glad but this problem is very depressing

#

Dont leave me struggling alone @mint folio @ivory bolt 😭

#

we need to call bill gates

#

Can anyone copy my form and send it and try it in his PC

#

and tell me if it works or not

#

but i need to trust someone ^^

#

and why thistelnet smtp.xxxx.com.kh 25 returns Connecting To smtp.xxxx.com.kh...Could not open connection to the host, on port 25: Connect failed

#

Please don't forget about me this problem is intense

pulsar fjord
#

doomsday

#

Everything is fixable in the end .. look for the lone code line or variable in this case input parameter

karmic girder
#

unable to authenticate using django form

views.py

from django.shortcuts import render
from django.contrib.auth.models import User
from django.shortcuts import redirect
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import authenticate, login
from .forms import LoginForm

def Register(request):
if request.method == 'POST':
    form = UserCreationForm(request.POST)
    if form.is_valid():
        data = form.cleaned_data
        user = User.objects.create(username=data['username'],
                                   #    password=data['password1']
                                   )
        user.set_password(data['password1'])
        user.save()
        return redirect('/')

form = UserCreationForm()

context = {
    'form': form
}
return render(request, 'register.html', context)


def LoginUser(request):
if request.method == 'POST':
    form = LoginForm(request.POST)
    if form.is_valid():



        data = form.cleaned_data
        user = authenticate(
            request, username=data['username'], password=data['passsword'])
        print(data)
        print(user)

form = LoginForm()
context = {
    'form': form
}
return render(request, 'login.html', context)

forms.py

from django import forms

class LoginForm(forms.Form):
username = forms.CharField(max_length=100,)
passsword = forms.CharField(widget=forms.PasswordInput)

output

Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
{'username': 'abc', 'passsword': 'abc'}
None
[11/Jun/2021 17:00:47] "POST /login HTTP/1.1" 200 3330
{'username': 'abc', 'passsword': 'abc'}
None
[11/Jun/2021 17:01:05] "POST /login HTTP/1.1" 200 3330

#

Please help me

supple vault
#

Is it possible to have an API that gets data through a POST request and also is a websocket / socket server that can send the data in the POST request to the clients connected

dusk portal
#

Some of my friends said that django is not worth it
Node has more demand ,are my flask skills not worth it are they only for building logic and my use not for commerical purposes
Do anyone ask for flask or django on back-end

pulsar fjord
#

done

steady swan
#

Websockets works off the same connection principles of HTTP, so in theory any http server should be capable of upgrading the connection.

late gale
#

im getting this error

#

my settings.py

EMAIL_HOST = 'smtp.gmail.com'

EMAIL_PORT = 587

EMAIL_USE_TLS = True

EMAIL_HOST_USER = 'NO x 10^99'

EMAIL_HOST_PASSWORD = 'NOOOOOOO'

DEFAULT_FROM_EMAIL = "NoOO<noreply@NOO.com>"
#

It was working last week suddenly It occurs

opaque rivet
#

@steady swan once the request is upgraded, it doesn't continue to follow HTTP principles - or does it?

late gale
steady swan
dusk portal
#

See #general ppl say flask is dead and django is not better then node

late gale
#

Please like we spent all day in this me and some members as well

steady swan
#

Hopefully if you break it down you can isolate where the connection issues are coming from.

opaque rivet
#

@steady swan ah yeah, I totally just forgot that websockets is an entirely different protocol. It's just the original request with the upgrade header which initiates it.

I've been using django, but iirc the middleware is not async so there's performance penalties out of the box.

steady swan
late gale
#
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 70ms, Maximum = 71ms, Average = 70ms
opaque rivet
late gale
#

ms is great

steady swan
late gale
steady swan
#

But django channels was created for this purpose exactly

late gale
#

so i believe something went wrong

opaque rivet
#

@steady swan what tools have you been using, recently? Out of curiosity.

steady swan
late gale
steady swan
opaque rivet
#

@late gale follow the guide link above. I used it to setup gmail emails.

steady swan
#

0% loss means it was able to send packets no problem

late gale
#

I told u , it was working

#

suddenly it didnt

#

then what might be the problem

#

is it dns issue ?

steady swan
#

likely not if you can ping okay

#

next step maybe is write a small standalone script to try and make an smtp connection

#

I'm sure Google can come up with some good tutorials

#

if that works, then there must be something in your app layer

supple vault
#

I'm kinda stuck 😭

steady swan
# supple vault Any libs I can checkout for this?

Again, as the Sanic maintainer I'm biased towards that. But all of the async frameworks should support this. There's also standalone libs like websockets which does have an HTTP layer, but is best for super simple heathchecks. You're better off with a framework that has both http and websockets support.

steady swan
steady swan
late gale
#

@steady swan I tried to send it using the link above and it sends me the same error

[WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
steady swan
#

so, sounds like a problem with your machine/network connection

late gale
#

what might be the issue

twin hamlet
#

Hello anyone know about Django

late gale
#

is there something to do in my router settings

twin hamlet
#

?/

late gale
twin hamlet
#

I want to differentiate the edit profile view

#

Facing this error

#

edit prof view for labour

#

and Efitprofview for Engineer

#

@ruby portal r u there ?

late gale
#

@steady swan Oh when I changed my port to 465 and disabled TLS and enalbed SSL it worked @opaque rivet @ivory bolt

#

I GONNA CELEBRATEEEEE!!!!

#

DANCE WITH MEEE

#

💃

naive garnet
#

👯

late gale
#

I need 50 champagne for this

naive garnet
#

cheeeers

civic pewter
#

how can I overwrite the variable from cleaned_data

late gale
civic pewter
#

mhm @late gale can you help me with the code?

#

As I asked before...

#

I wanted to know how I can save a photo that will contain a watermark. Currently grabs a photo from the form and creates a watermark on it, but saves it separately. More precisely, I would like the photo I send in the form to be processed and saved.

#

anyone ? 😅

left tangle
#

Hello, I'm kind of confused by how django works, when I'm creating a website with django, do I have to code in html css and js? Or just python and django somehow creates html css and js for the front end?

proper hinge
#

Yes, you still have to write HTML, CSS, and JS.

#

The HTML you write isn't the plain HTML you might expect. Django can insert data from Python into the HTML before it sends it off to a user's browser.

#

HTML, CSS, and JS are all front-end things. Django is a back-end framework. It takes care of serving web pages and other static content (images, CSS files, JS files, etc.) to users' browsers. But you still have to write all those things yourself.

south lodge
#

Is an ASGI server like Uvicorn supposed to run behind a reverse proxy, or can it be exposed directly to the internet?

cerulean badge
#

how do i get all users that do not have a group with name group_name? (context django)

quick cargo
#

Things like Nginx have many security advantages like concurrent connections limitations and also allow you to support HTTP/2 for clients which is a big advantage

south lodge
quick cargo
#

Nginx is probably the defacto

#

cant argue with decades of work

south lodge
#

👍 thanks, I appreciate it!

proper hinge
# quick cargo I would recommend sticking it behind a reverse proxy

I have a related question. If I put my site behind Clouflare, do I still need a reverse proxy? CF is a reverse proxy itself, and I don't need any complex routing since I only have 1 service running. AFAIK CF can take care of HTTP/2. Not sure about limiting concurrent connections. What would I be missing out on without nginx?

quick cargo
#

Well generally

#

High performance static file sending

#

and not HTTP/2 + going to your server

proper hinge
#

I use whitenoise which serves them through cdn, so whatever

quick cargo
#

Cloudflare does client -> CF upto HTTP/3 v1

#

which is great

#

but that's still HTTP/1 to your servers from cloudflare

#

which generally is more distance apart than clients to cloudflare unless you're also geo distributed

fast patio
#

sry this if off topic but in flask wehn ur returning something in html how do. u apply pandas?

proper hinge
#

Hmm okay. Something to consider. But I don't think my particular case would benefit much from HTTP/2.

#

I just don't want to deal with having to deploy nginx too 😒

quick cargo
#

If client sends on average more than 1 request per connection, it's worth it normally

#

Because multiplexing requests cuts out having to open another connection and doing the whole TLS handshake again etc...

#

which can make a big big diffrence

#

but that depends on your work load really

proper hinge
#

Is it out of scope for WSGIs to support HTTP/2 directly

quick cargo
#

generally yes

#

Most python http servers dont even support HTTP/2

proper hinge
quick cargo
#

Hypercorn supports HTTP/2 although performance is meh and Personally i've never been able to get Hypercorn be stable when in a prod environment

proper hinge
#

Anything else nginx have that's noteworthy?

#

Well there's other tools too, but I get the impression nginx is more than just a reverse proxy. Has more features compared to e.g. HAProxy I believe.

quick cargo
#

well the fact it runs lua basically means it can do alot, our setup uses kong which is basically traefik (although kong is older than taefik iirc) but wraps Nginx as it's backend

#

so we run Proxy caching, ratelimit, response size limiting, request size limiting, auth

#

etc..

proper hinge
#

Actually, nginx's site has a good list of features. Nothing really stands out to me for my use case.

quick cargo
quick cargo
proper hinge
#

Yeah, exactly.

#

I have a small scale project and a lot of the info online was immediately defaulting to "you need a reverse proxy"

#

It was extremely difficult to find anyone explain why

quick cargo
#

well alot of it comes down to limiting concurrency, TLS support and just the fact that things like nginx are hyper optimised and have decades of security testing

#

Python seems to suffer much harder than other languages as concurrent clients increase

subtle otter
#

hiii, so in my website i'm using sqlite3 as db , is there a way to keep only one row if the primary keys are the same??

quick cargo
#

thats the idea of a primary key

#

there can only ever be one row with the same value in the primary key column

#

because it has the UNIQUE constraint

subtle otter
#

ohhh okay okay , how do i set a primary key xD

c.execute("""CREATE TABLE MD5 (
            md5 text PRIMARY KEY,
            link text,
            language text,
            type text,
            date integer
            )""")

is this right?

quick cargo
#

yes

subtle otter
#

kk thank you so much 🙂

subtle otter
#

is there a way to disable the console log for when the primary key is found?? sqlite3.IntegrityError: UNIQUE constraint failed: MD5.md5 this one here so it doesn't keep on logging it every time it finds one

proper iron
quick cargo
#

also nice to see you in the discord :P

ivory bolt
ivory bolt
#

meaning when you visit www.yourwebsite.com/, django will handle where can the user go by typing something in the url, what html n css it should show when you type that URL, and what all you can do next

#

html and css is only a markup language, it'll help you render things on a webpage but not actually do anything. Adding users, chat or other features, processing of data -- that's all django

left tangle
ivory bolt
#

yep

#

simply put, I can create THIS with html and css

#

But nothing will actually work -- the links won't go anywhere, the site won't do a thing, your server won't run in the first place in the real world

left tangle
#

Got it.. I was under the impression that i don't have to learn html,css,and js for now, and just focus on python.

lethal kite
#

Hello everyone

#
        $(document).ready(function () {            
            status();
            $("li.status").click(function() {
                $.ajax({
                    url: "/update_status/",
                    type: "POST",
                    data: {
                        'request_contract_id': 9, //I need optimize this to detect automatically the id and status
                        'status': 'Rechazado' 
                    },
                });
        });
    });
#

Can anyone tell why my ajax it's not working?

lethal kite
#

ajax*

#
class ContractRequestStatusUpdate(View):
    model = RequestContract
    form_class = RequestContractUpdateStatusForm

    @csrf_exempt   
    def dispatch(self, request, *args, **kwargs):
        return super().dispatch(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        #Nowadays the id is manually.
        id = self.model.objects.get(pk=9)
        if request.method == 'POST' and request.is_ajax():#I verify is request is POST and Ajax
            form = self.form_class(request.POST)
            if form.is_valid():
                id.status = form.cleaned_data['status']#I clean the datos from status
                id.save()
        return HttpResponse('/')
       ```
#

This is my view

#
class RequestContractUpdateStatusForm(forms.Form):
    request_contract_id = forms.IntegerField()
    status = forms.ChoiceField(choices=RequestContract.STATUS)
#

and this is the form that i'm using,

#

I can update perfectly my register, but i have to reload the page, so I think something it's wrong with AJAX

#

can anyone help me?

warm igloo
#

What do you want it to do? What's broken about it?

Remember, since this is AJAX, it is submitting "behind the scenes". You can return a 500 or 200 message back and the AJAX function can do something with it like show a "Success!" modal or do a page redirect.

So as far as I can tell this is running as designed -- you submit the form, it sends data to your endpoint, you save it. And then you do nothing (no success, no redirect, nothing).

In Flask if you're posting to an endpoint and you want that synchronous POST to do something like a redirect when it is complete, check out return redirect(...) or return render_template(...) for instance.

BUT, that's if your form submits directly to the endpoint. Which you don't do here. You're submitting via AJAX. So AJAX is what should handle that. Returning a template or a new URL back to the JS won't do anything for you unless YOU do it. Dig?

#

@lethal kite ☝️

lethal kite
#

@warm igloo I got it thanks bro!!!

mossy warren
#

Does anyone have an idea on how to implement a online compiler where I can run my code online?

subtle otter
#

Guys how can i make that progress bar work with my python script pls??

native tide
#

I don't get why we use the cite tag for? could anyone explain why it does and why we use it?

misty goblet
#

for when you a citing something

native tide
#

Uh can you be more informative?

misty goblet
#

that's pretty much it, there are lots of html features that aren't very useful.

#

though I would imagine that some accessibility programs might make use of them

#

or bots looking at metadata

native tide
#

Oh Ty I will look in to it

#

@misty goblet I get it now but we only use cite tag for the title of another person's work for example a book right?

native tide
#

Why do we use blockquote tag for?

native tide
#

I read it but I don't understand

#

So could you explain it to me?

opaque rivet
# native tide So could you explain it to me?

Well, the blockquote tag is for making a blockquote. You can see what it looks like by clicking on the link.
Imo that question is similar to saying "what does the p tag do", well it creates a paragraph. What does the div tag do? It creates a div.

vast plover
#

this channel helps with js html css right?

proper hinge
#

Yes

#

Within reason. Like if you're writing a Node.js app then it's probably off topic.

vast plover
#

no no , i mean like simple questions about a code if its correct or not , etc

proper hinge
#

Those aren't mutually exclusive but never mind. What is your question?

vast plover
#

@proper hingeright now im very stuck in learning js html css, or python, personally i enjoy python alot more, but i dont know a career i can start learning with python right now

#

whenever i search in freelances or jobs , its usually web developers for front end mostly

proper hinge
#

I'm not the best person to be asking for career advice. I was under the impression you wanted help with some code. If you want career advice, please ask in #career-advice

vast plover
#

ok thanks alot

bright lodge
quick cloud
#

How can i un-install django? pip freeze | grep Django -> for this error: 'grep' is not recognized as an internal or external command,

bright lodge
#

So i was making a website to show 10 random images daily taken from API ......i have written 10 different img tags in my html anyway i could make it less redundant

quick cloud
mortal lily
#

i am making an app using python kivi i have some doubts can i ask here

bright lodge
jovial cloud
#

Are you using any of them?

cerulean badge
#
admin.site.unregister(User)
admin.site.register(User, UserAdmin)

i am trying to add some actions to the user but it gives me this error
django.contrib.admin.sites.NotRegistered: The model User is not registered
when i remove the line admin.site.unregister(User) then it gives me this error
django.contrib.admin.sites.AlreadyRegistered: The model User is already registered with 'auth.UserAdmin'.

can you tell why this is happening and how do i fix this (context django)

leaden path
#

Someone give me a good web scraping tutorial so that I can pull dynamic data.

cerulean badge
#

i want to add additional actions to User modal in django admin how do i do that? i can create a custom ModelAdmin but i want to keep everything as it is and just add additional actions (context django)

cerulean badge
bright saffron
#

hi , wanted to ask which are one of the best sites to learn djang[

#

django

grim yarrow
#

{"timestamp":1623485161160,"status":400,"error":"Bad Request","message":"JSON parse error: Unrecognized token 'mobile': was expecting ('true', 'false' or 'null'); nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'mobile': was expecting ('true', 'false' or 'null')\n at [Source: (PushbackInputStream); line: 1, column: 8]","path":"/campaign/vouchers/kAxAeMsjtmjCe4aoep/redeem"}

wicked wren
cerulean badge
#

is

@admin.action(description='My Action')
def my_action():
  pass

and this

my_action.short_description = 'My Action'

the same thing? (context django)

cerulean badge
bright lodge
# jovial cloud Are you using any of them?

yes im using flask ...dont know anything about jinja .....so i was stuck how to do it using python finally figured out i can do that by javascript .....if iam gonna do that with JS then might aswell do the whole thing in JS and node

#

instead flask

rough urchin
#

Hi

native tide
#

Hi, I am getting the error but why:

#

Does anyone have any idea?

cerulean badge
#

i want to create a dashboard which need the actions dropdown from admin change list how do i reuse them? (context django)

#

not just dropdown widget the functionality ofcourse

steel lodge
#

how to get emmet abrreviation on vs

#

??

#

for Html

opaque rivet
# native tide

INSTALLED_APPS is meant to be a list. Look over your INSTALLED_APPS if you can spot the error.

steel lodge
#

@simple sentinel

simple sentinel
#

Have you tried saving the files and re-running the server?

steel lodge
#

yes...several times/

#

giving the same error.

simple sentinel
#

Because I see the white dot which indicates some files have not been saved

steel lodge
#

@simple sentinel now see

noble spoke
#

Bro save all your files

simple sentinel
serene prawn
#

No autosave in vsc? 🤔

steel lodge
#

naah... i have saved it

serene prawn
#

Send your both urls files again

#

text/screenshot

#

doesn't really matter

steel lodge
#

@simple sentinel @serene prawn

#

see this error is coming

simple sentinel
serene prawn
#

create that template

steel lodge
serene prawn
steel lodge
#

man that wont work

serene prawn
#

You tried it?

steel lodge
#

worked......

#

hahahahahaha.....

#

shit just a mistake of 's'.

#

@serene prawn

serene prawn
#

like this

steel lodge
#

thank you so much buddy @serene prawn @simple sentinel

steel lodge
limpid python
#

I am unable to load a CSS file

night agate
leaden path
limpid python
#

i was able to fix, my 2 brain cells forgot to add STATIC_URL = '/static/'

opaque rivet
#

use flexbox:

<div class="container">
  <div class="title" />
  <div class="box" />
</div>
.container{
  display: flex
  flex-direction: row
  justify-content: flex-start
}

.container div {
  height: 100%
}```
#

just apply the same height rules for both elements if you want them to be the same height.

proper hinge
#

My website needs to use a third party API's data to display in the front end. The problem is that the API has a quota limit. If I make the requests directly, then my API key is exposed. If I wrap the API in my own, then the key is technically hidden but anyone can freely request my endpoint so it's practically the same.

How do I prevent abuser from quickly eating up my quota? How is this situation typically dealt with? Should I wrap the API and then implement rate limits on my endpoint?

native tide
opaque rivet
proper hinge
#

Thanks. Caching is prohibited by their terms, so I suppose I'll try to do rate limits.

opaque rivet
#

Perhaps it would be also possible to queue each user request to the 3rd party API. Maybe with rabbitMQ or redis? That way you're rate limiting your own server instead of each client, but that might mean that users wait longer for their first request

proper hinge
#

That's an interesting idea, and might make more sense if I expected lots of simultaneous users. But it also sounds more complicated to set up than endpoint rate limits.

rancid magnet
#

Hi, someone can help with this:

rancid magnet
rancid magnet
dusk portal
#

hey any flask dev i need some help

red palm
#

@dusk portal so what're your issues

dusk portal
#

so hey the issue is i was learning flask from last 1.5 months and then later left (Flask was my first framework ) so i faced alot of issues now im learning django from last 15 days but somehow my mind says plz cover topics u left in flask so plz can u help me cover those so im starting to ask @red palm

dusk portal
#

so first i will tell something will tell things idk so tell me as per that ik to connect db make db link form stuff jinja inheritance linking from mail and stuffs like login panels and all , so 1st question how can i use my react file as template 2nd question how can i make a signup backend ik it sounds simple but the thing is ik we have to take input as single form and then get it to db but the problem is it will be stored as simple text then how user can use it to login ;-; 3rd how can i write backend of search bar ;-;-; 4th how can i write backend of forgot password to reactive

#

and 5th yes how can i take donations by patroen paytm paypal ;-;

#

and yes i dont use flask_forms i like to write html and i dont use that import models to make main application(.py) file clean if project == big i use django

#

r u there 🤣 @red palm

red palm
red palm
dusk portal
#

can u show me 3rd

#

wow how

dusk portal
#

😑

#

ik db i just wrote ik these things

#

ik to add login panel im asking about sign up

red palm
dusk portal
#

are u free can i show screen @red palm

#

plz 5 min

red palm
native tide
#

hello

dusk portal
#

love u broi

native tide
#

i learn creating web-site in w3schools and free code camp

#

and

#

is ths web-sites good

surreal portal
#

Ok, trying Django for the first time and I can't even make migrations!

lavish prismBOT
#

Hey @surreal portal!

Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:

• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)

• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:

https://paste.pythondiscord.com

surreal portal
#
  File "C:\Users\User\Documents\Projects\django-next\backend\api\views.py", line 1, in <module>
    from backend.api.models import Post
ModuleNotFoundError: No module named 'backend.api'
#

This is after executing python manage.py makemigrations

#

Settings go like this

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    # Install `api` here
    "api.apps.ApiConfig",
    # Set up djangorestframework here
    "rest_framework",
]

It was working fine before creating a new model

#
from django.db import models
from django.contrib.auth.models import User

# Create your models here.
class Post(models.Model):
    title = models.CharField(max_length=50, default="")
    content = models.TextField(max_length=250, null=False)
    date_posted = models.DateTimeField(auto_now_add=True)
    thumbs_up_number = models.IntegerField(null=False, default=0)
    author = models.ForeignKey(User, on_delete=models.CASCADE)

#

How come it's not registered properly?

#

Do I have to do something else?

#

Ok after examining the file I really can't see where the error is

#

Wait do I really need api in INSTALLED_APPS

#

Urgh this is getting annoying. I'm commenting everything and I can't see where the problem is

fickle plank
#

Why do we need Flask?

#

I started learning Flask an hour ago, and haven't exactly figured out the purpose of Flask

#

Can't we achieve it by html and css?

dusk portal
#

What r u saying lol

#

Omg

#

Lol

#

@fickle plank

west peak
#

Hi guys

#

I have a question

#

I'm doing this AJAX call

#
btnSendOrder.onclick = () => {
  const request = new Request(`${URL}/set/purchases/`, {
    headers: { "X-CSRFToken": csrftoken },
  })
  fetch(request, {
    method : 'POST',
    mode : 'same-origin',
    body : JSON.stringify({
      id_user : idUser,
      phone : phoneNumber.value,
      products : productsStored,
    })
  })
    // .then(response => response.json())
    .then(response => {
      console.log(response)
      return response.json()
    })
    .then(test => console.log(test))
    .catch(err => console.log(err))
}
#

In this view of Django

#
def set_purchases(request):
    return HttpResponse(request)
#

how can i access to the data what i am sending

#

I tried with request.POST['id_user'] for example

#

but it don't work

surreal portal
#

Guess i'm gonna try the djangorestframework tut before I explode

gloomy wasp
#

isn't that because of

  padding: 20px 30px;
```?
#

maybe

surreal portal
#

Oh good news. I knew where the bug was

#

Apparently my Django server """fixes""" imports I've already imported

native tide
#

hello

opaque rivet
native tide
#

what are we doing

#

HTML

#

or CSS

dusk portal
#

DatabaseError: database disk image is malformed

final geode
#

Can someone give me some website feedback? Also can i post links?

#

My website sells stock photography where users can also sell their own images

wind rapids
#

is there any servers that spicifcially answers some of my dobuts in Django?

tawdry tinsel
#

Hey, I need your help /advice to resolve the Bug.

What I want to do:
If a user login in vue.domain.com then he doesn't need to login in bubble.domain.com and domain.com. Basically if user login via any subdomain.domain.com or domain.com, then he doesn't need to re-login in any of the sub-domain.
What my current approach is:

I trying to achive this by using JWT token in cookies.
so basically what I'm doing is, whenever login endpoint hit via anysubdomain.domain.com, and credentials are correct, we set cookies in response header with domain attribute.

response.set_cookie(key='refreshtoken', value=refresh_token, httponly=True, domain=".domain.com")
response.set_cookie(key='accesstoken', value=access_token, httponly=True, domain=".domain.com")
what my current hosting or setup look like:

backend (DJANGO/DRF) hosted on: api.domain.com
frontend (vue.js): vue.domain.com
frontend (bubble): bubble.domain.com
frontend (html/css/js): barehtml.domain.com
what the issue:

whenever I hit the api.domain.com/user/login via vue.domain.com with correct credentials, In response header I got the set-cookies with domain=".domain.com" but cookies aren't set on vue.domain.com or .domain.com

#

Here is the quick demo for better understanding

#

If anyone able to help me to resolve this bug, I really really appreciate.

twilit needle
steel lodge
#

please look into the matter guys:

#

I have written the code for the body of my website using {%block body} but it is not showing on my website.

cerulean badge
#

should i try to make forms in forms.py whenever possible or just use html whenever possible? whats the recommended way? (context django)

cerulean badge
#

for example should i be making a form in forms.py for a choicefield or include it in html directly?

foggy bramble
#

hi there
can anyone say why code block is not formatted in div

scenic pollen
#

does anyone know how I can get or make a custom domain?

quick cargo
#

You have to buy them from a registra

dusk portal
scenic pollen
dusk portal
quick cargo
dusk portal
#

pilij help me xD

scenic pollen
#

but I have seen people with custom domainds for free

#

tho its .ml instead of .com

quick cargo
#

Some registras are partnered with github education so give you 1 domain of some un-popular endings for free for a year

#

but generally you have to pay for a domain

scenic pollen
#

oh ok

#

thanks

dusk portal
#

;-; @quick cargo @scenic pollen

scenic pollen
#

ye?

dusk portal
#

^^

quick cargo
#

please dont ping people randomly

dusk portal
#

^^

#

ok sorry

#

done

#

xD

west peak
dusk portal
#

no it was some other problem xD

#

im dumb

#

fixed it

#

thanks alot u r the only who u replied @west peak

#

xD

dusk portal
#

anyones up

chilly falcon
#

name 'serializer' is not defined

#

code is this in drf

class DetailProduct(APIView):
    """docstring for DetailView"""
    # the below function will check where the object with following primary key
    def get_object(self,pk):
        try:
            return Product.objects.get(pk=pk)                                       # if there is object it will get that object
        except Product.DoesNotExist:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)  # if ther is not such object will send bad request
opaque rivet
chilly falcon
#

i think it should import from drf

opaque rivet
#

Well, you import the Serializer class from DRF, but errors is an attribute of the serializer object.

chilly falcon
#

how can i do that in here?

#

because obj dont exists?

opaque rivet
#

Follow the DRF docs on using serializers.
It isn't defined because you didn't create any serializer object. It's literally the same as this:
print(x) without ever specifying what x is.

chilly falcon
#

ok then any solution?

opaque rivet
#

And in this case there isn't even any need for a serializer, just return a message

opaque rivet
chilly falcon
#

i have same program from member it working

opaque rivet
chilly falcon
#

ok bro

opaque rivet
#

I have no idea what that means

#

You could just say:
return Response(data="Product not found", status=status.HTTP_400_BAD_REQUEST)

chilly falcon
#

ok i will figure it out thanks for help

civic pewter
#

Need Help

dusk portal
#

anyone's up

native tide
#

what does the div tag do in html(specifically)?

fast yoke
native tide
fast yoke
#

Don't think so

twin hamlet
#

hello

#

I need to create edit profile buttons which is consisting the different href

#

<li><a class="dropdown-item" href="{% url 'edit_prof' %}">EDIT PROFILE</a></li>

#

<li><a class="dropdown-item" href="{% url 'edit_prof_eng' %}">EDIT PROFILE</a></li>

#

If some condition then this will show up --><li><a class="dropdown-item" href="{% url 'edit_prof' %}">EDIT PROFILE</a></li>

#

else this will show up --> <li><a class="dropdown-item" href="{% url 'edit_prof' %}">EDIT PROFILE</a></li>

#

def home(request):
eng_id = Engineer.objects.get(user = request.user.id)
lab_id = Labour.objects.get(user = request.user.id)
print("ID and Username : ",lab_id.id,lab_id)
# print(eng_id)
# print("Labour {}".format(lab_id))
# print("Engineer {}".format(eng_id))
# context = {"eng_id":eng_id,'lab_id':lab_id}
return render(request, 'home.html')

opaque rivet
#

!code

lavish prismBOT
#

Here's how to format Python code on Discord:

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

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

opaque rivet
native tide
#

in bootstrap how do i choose a theme like this?