#web-development

2 messages Β· Page 190 of 1

vestal hound
#

isn't it STATIC_URL

stable sentinel
#

at this point I honestly don't know anymore lol

#

if I mess with the STATIC_URL i get all sorts of exceptions thrown at me that its conflicting with MEDIA_URL

opaque rivet
#

@cerulean badge you can have one "table" in your redis db for your queues, and another one for your data.

dusk portal
#

bruh @opaque rivet

#

help me out

stable sentinel
#

I just changed the STATIC_URL = '/absolute/path/to/the/files/' and the get request seems to queering the right directory, but I'm still returned a 404...

dusk portal
#
@login_required
@cache_page(60*2)
def notes_upload(request):
    if request.method=='POST':
        title=request.POST.get('title')
        desc=request.POST.get('desc')
        file=request.FILES['file']
        thumbnail=request.POST.get('thumbnail')
        author=request.user
        if ValidationError:
            messages.error(request,'CAN ONLY UPLOAD PDF FILES')
            return render(request,'index/notes_upload.html')
        entry=Notes(title=title,desc=desc,file=file,thumbnail=thumbnail,author=author,published_on=datetime.now())
        entry.save()
        messages.success('Notes updated successfully!')
        return HttpResponseRedirect('/')
    return render(request,'index/notes_upload.html')``` i'm uploading .pdf files only then too it's flashing error and data isn't saving to db 'CAN ONLY UPLOAD PDF FILES'
opaque rivet
#

I don't think if ValidationError is valid syntax. I've never tried to check if an exception was real, but it's probably returning True.

Use a try/except block for handling exceptions

dusk portal
#

ohk cool

#

still same error

vestal hound
#

I mean

#

it's probably the wrong directory, right

#

otherwise you'd get a hit

shrewd grove
#

Hi, I'm a new python dev and the project I'm working on uses both uvicorn and starlette - is uvicorn the web server and then starlette is a framework on top of that? I'm from a .net background so I guess an analogy would be they have their web server called kestrel then MVC sits on top of that. Would that be similar?

vestal hound
#

I have no idea what those .NET things are

#

but yes, Uvicorn is a server (following the ASGI spec) and Starlette is a web framework

shrewd grove
#

Great thanks.

graceful flax
#

Hi, I'm trying to add 5 miuntes to the current time

#

Using this

 datetime.timedelta(
                            seconds=300
                        ) + datetime.datetime.now(timezone.get_current_timezone())
#

I get this as the error

unsupported operand type(s) for +: 'NoneType' and 'str'
#

I print them individually it isn't none.

vestal hound
#

show the surrounding code

shrewd grove
#

So my next problem is getting the logging to work, when I start my server I can see log entries like this:
INFO: Uvicorn running on http://127.0.0.1:8082 (Press CTRL+C to quit)
But if I put in my own logging code in the application I never see the log output e.g.
log.info('test')
Never comes onto my terminal. I'm using Ubuntu.

graceful flax
# vestal hound show the surrounding code
                    try:
                        user = User.objects.get(email=request.data.get("email"))
                        activation = Activation.objects.get(user=user)
                        activation.expiry = datetime.timedelta(
                            seconds=300
                        ) + datetime.datetime.now(timezone.get_current_timezone())
                        activation.save()
#

That's it

vestal hound
#

oh god

#

the indentation πŸ₯΄

graceful flax
#

Discord

#

Sorry lol

vestal hound
#

hm it looks all right

#

show the traceback?

proper pine
#

So you people use Python to make a web?

#

Like is it possible?

graceful flax
vestal hound
#

where's the rest

#

this is

#

Flask?

vestal hound
graceful flax
#

Django

vestal hound
proper pine
vestal hound
#

you're running in debug mode

#

presumably?

vestal hound
graceful flax
#

Yep

proper pine
#

I use HTML

vestal hound
proper pine
#

That's why my name is like a tag

vestal hound
#

more accurately

#

the webpage itself

#

is of course in HTML (and CSS)

proper pine
#

Whattttt

vestal hound
#

but you use a web framework to serve pages

proper pine
#

Oh wow

#

I will learn it

vestal hound
#

for example

#

let's take Instagram

#

the webpage is in HTML and CSS (and JS)

#

but somewhere on Facebook's servers, there is code that takes the URL you type in, does stuff, and returns that webpage

#

that code is Python

proper pine
#

Ooo

dusk portal
#

;-;

shrewd grove
#

Hi, the app. I am working on starts with uvicorn when testing locally, but in the production environment where it runs in a docker container it's started with gunicorn. Does anyone know why this difference exists? Thanks in advance.

inland oak
#

check its parameters

shrewd grove
#

thanks. looks like it runs and manages uvicorns

shrewd grove
#

For some reason I just can't seem to get my log output appearing in the terminal window. I start uvicorn from the terminal, I can see my print statements but nothing from log.

inland oak
shrewd grove
#

not running in docker at present - shall i set in my terminal ?

amber current
#

Someone, please πŸ™πŸΌ

inland oak
shrewd grove
#

thanks,,, just found something else as well that might solve it

dusk portal
#

i wanted to get more n more deep into django and it's rest framework now

#

im learning alot in django as im doing freelancing

#

but idk how to apply web scraping with django

#

ai with django

#
  • i wanted to get deep into it's rest framework no client asks for that so my that skilleset is being dead
dense slate
#

@dusk portal Using Upwork?

dusk portal
#

xD

cerulean badge
cerulean badge
dusk portal
#

idk that

#

they just dm

#

lol

#

@opaque rivet lord is here to guide me again

#

xD

opaque rivet
#

@cerulean badge I believe it uses the "table" at index 0. You can store all of your data in another index, e.g. 1

#

You can go into your redis shell and see the data stored at each index. Your broker data should be stored at index 0.

cerulean badge
#

ok thanks

lavish prismBOT
#

@cerulean badge Per Rule 6, your invite link has been removed. If you believe this was a mistake, please let staff know!

Our server rules can be found here: https://pythondiscord.com/pages/rules

cerulean badge
#

this is from django3 by example
https://paste.pythondiscord.com/ijugevoqul.py
my question is wouldn't it return wrong suggestion if 2 people are visting their cart at same time and one have products with id 1, 2 and 3 while the other have product in cart with id 123?
i am talking about this line

flat_ids = ''.join([str(id) for id in product_ids])
tmp_key = f'tmp_{flat_ids}'
opaque rivet
#

@cerulean badge you could store cart info on the clients idea in localstorage then make API calls for the products instead

cerulean badge
#

the issue would still be the same, right?

#

if 2 users make the api call at same time ....

thorn igloo
thorn igloo
cerulean badge
thorn igloo
#

i see

dusk portal
#

hey @thorn igloo

thorn igloo
dense slate
#

Anyone dealt with the issue where you login to Django admin, therefore creating a session, and then when you try to login with a JWT of another user on the website (not admin panel), it logs in to the account associated with the session?

velvet yew
#

I'm experiencing an issue with djongo when used with Django REST framework where it initiates a new connection with my MongoDB at every request except for the very first one after starting the web server. That means the first request to my Django API is fast (~50 ms) but all the following requests are significantly slower (~600 ms) because they all initiate a new connection (it's much faster when I'm running the web server closer to the DB, but I'm running them far apart each other for debugging so it's easier to spot such issues).

When profiling the request I can see that pymongo\pool.py:1263(connect) is present in each request except for the first one, which I assume means the first request uses the pre-initiated DB connection, but all the others have to create a new connection, hence why it's so slow. I'm also seeing huge spikes of connections in my MongoDB dashboard, there should be only 1 connection, but when I'm testing this it gets up to 50-80 connections, and even when I shut down the web server, the connections only drop by one and plenty of zombie connections remain that only die after some timeout.

For the installation and configuration I've followed their GitHub instructions (https://github.com/nesdis/djongo/) so it goes like:

DATABASES = {
    "default": {
        "ENGINE": "djongo",
        "NAME": "django",
        "CLIENT": {
            "host": f"mongodb+srv://{MONGODB_PATH}",
        }
    }
}

(MONGODB_PATH = f"{MONGODB_DJANGO_USER}:{MONGODB_DJANGO_PASS}@{MONGODB_CLUSTER}" from environment variables)

Anyone else encountered the same or similar issue? I can send a link to the endpoint if someone would like to help with debugging

dense slate
lavish prismBOT
#

@cerulean badge Per Rule 6, your invite link has been removed. If you believe this was a mistake, please let staff know!

Our server rules can be found here: https://pythondiscord.com/pages/rules

cerulean badge
manic frost
#

@cerulean badge Why not call it with an empty list and see what happens?

cerulean badge
# manic frost <@!810158114190917662> Why not call it with an empty list and see what happens?

i did and it doesn't raise an error but this issue says otherwise
https://github.com/PacktPublishing/Django-3-by-Example/issues/46

GitHub

Chapter 9 throws an error if all the products from the cart are removed. The following should be added to recommender.py def suggest_products_for(self, products, max_results=6): product_ids = [p.id...

heavy oak
#

what to do

#

i have installed django

cerulean badge
manic frost
cerulean badge
dusk portal
#

xyz == project name

heavy oak
#

ok πŸ‘πŸΌ

warm patio
#

Anyone here used django all auth I’m having trouble getting the user object in request

warm patio
# cerulean badge whats your problem?

when i call the api on my server the user object isnt returned, if i do it using my browser then it works, how can i get the user object through an api call?
the request.user object
it works on browser call
but not when i call using the axios

cerulean badge
#

sry brother, never used axios or implemented rest api

sharp breach
#

hey

#

can anyone help me plszzzsszzz

#

my css and js are not loading whenever I host it

#

on my local host it is loading

sharp breach
sharp breach
#

its not loading css and js

#

what should I do????

#

??

#

helppp

warm patio
sharp breach
#

@warm patio

#

can u help??

warm patio
#

Some issue to do with static site generation probably

#

Using vercel?

sharp breach
#

no

warm patio
#

Try with vercel if not

sharp breach
#

I am using bootstrap

warm patio
#

Never used it

#

Can some one help me I need to ship my product but I’m stuck on this for last two days

opaque rivet
#

@warm patio Well, what's the difference between a "browser call" and the request from axios?

sharp breach
opaque rivet
#

Your http request with axios should contain information about your user, such as a token, which your authentication backend can use to return a user.

warm patio
warm patio
opaque rivet
#

What authentication method are you using?

opaque rivet
#

With your method, how are you going to identify which user has a specific item in their cart?

warm patio
opaque rivet
#

@warm patio hmm, I'm not sure about that authentication method - but with any authentication, your request should include identifiable information about the user you're trying to authenticate. A bare http request with no such data will not authenticate a user.

warm patio
warm patio
#

This is the only reason I can think of

cerulean badge
#

do you need to purchase storage separately to host media files in digitalocean? i am talking about media files not static files

dense slate
#

What do you guys use for logging in Django as well as whatever frontend you're using? Does the FE error logging in production generally get sent to the BE and processed there or does the client handle its own errors to log to a file?

inland oak
#

frontend person is going to be searched % Probabling going to be React, but I am eyeing Vue.js plus there will be usage of React/Vue Native as well

#

If I would be doing for my own project, I would go for Svelte ;b

dense slate
#

I'm not sure what you mean?

#

Was asking about logging. πŸ˜‰

inland oak
#

oh. I guess I wrongly interpreted your message

#

I thought for login in

dense slate
#

ah, no no, logging errors.

inland oak
#

and you said for logging as observability

#

I am at the moment implementing it

#

going for Promtail + Loki + graphana

dense slate
#

For FE or BE?

inland oak
#

BE

dense slate
#

Gotcha. What would you use for FE error logging?

inland oak
#

partially observability is also covered with Prometheus and its Exporters

#

it has exporter for Nginx too

#

so probably FE will be covered with just it

#

Plus I attached Alert Manager to prometheus πŸ˜‰

#

So I get alerts to discord if something went bad

#

Prometheus is also exported to Graphana

dense slate
#

Hm

#

Yea I suppose I could just log errors to my discord server.

#

With a custom discord hook logger.

inland oak
#

Actually prometheus makes nice observability
It has exporters for Linux, for Django, for Nginx, for any database

#

the only thing its missing, catching custom logs comfortably, that's why adding Promtail/Loki

#

together they should have a good basic coverage

#

it could be cool to go for something advanced like tracing instruments in addition(Jaeger?), but oh well, that would be a wish for a future

dense slate
#

I'm looking for the simplest implementation I can get. I assume logging to stdout is the easiest.

#

Maybe I'll bite the bullet and use Sentry. πŸ˜„

inland oak
#

there is always logging library πŸ˜‰

#

as simpliest solution

#

Sentry looks cool to try though

#

I am mostly going with Loki because it... is a choice for growing sort of?

#

as far as I heard it is highly used with Kubernetes

#

so.. going to be cool compatibility in some future

#

plus, it is universal to catch logs from any frameworks/languages

past cipher
#

Any idea how can I compile multiple css files into one global css file?

#

Need it to happen whilst in development too

dense slate
#

Why do you need to?

past cipher
#

because I have like to have my scss files organised into different sections whilst building a big project

#

and then compile into one file, and then minify

dense slate
#

Using templates?

#

or a FE framework?

#

Short answer I don't know, but why would you need to combine them? Does minifying and importing multiple files create an issue?

tribal python
#

Doesn't scss have an include directive?

#

So you can have one file that includes your others, and compile that specifically?

#

I know there's one CSS system that works that way at least

calm plume
#

There's partials, yes

#

You can create partial Sass files that contain little snippets of CSS that you can include in other Sass files. This is a great way to modularize your CSS and help keep things easier to maintain. A partial is a Sass file named with a leading underscore. You might name it something like _partial.scss. The underscore lets Sass know that the file is only a partial file and that it should not be generated into a CSS file. Sass partials are used with the @use rule.
https://sass-lang.com/guide#topic-4

#

@past cipher ^ Are these what you're looking for?

#

Also, if you're using the JS API there may be a way you can do that directly from there

velvet yew
native tide
#

is there a jetbrains ide for web dev like using firebox css html js all in the one ide

tribal python
#

phpstorm I think?

#

it is php focused

#

but iirc it supports the rest of webtech too

rare lagoon
#

Why my css is not rendering? I think I have everything correct, a static folder with my index.css file in there, and I have a layout html:

<!DOCTYPE html>
<html>
    <head>
        {% if title %}
        <title>WeatherBuddy - {{ title }}</title>
        {% else %}
        <title>WeatherBuddy</title>
        {% endif %}

        {% block head %}
        {% endblock head %}
    </head>
    <body>
        {% block content %}
        {% endblock content %}      
    </body>
</html>

And this is the index.html page:

{% extends "layout.html" %}
    {% block head %}
        <link ref='stylesheet' type='text/css' href="{{ url_for('static', filename='index.css') }}">
    {% endblock head %}
    {% block content %}
        <h1>The Weather, one search away.</h1>
        <h3>Search for a city to know its weather.</h3>
    {% endblock content %}

heavy oak
#

hey i am new to this field in web development , i am trying to make a website using django and mysql , so what should i need to download to activate mysql

#

how do i know my mysql database username and password

#

any resources

heavy hinge
#

Which is better for web dev?

#

Mid 2011 mac mini

  • 2.3GHz dual-core Intel Core i5 with 3MB on-chip shared L3 cache
  • 8GB RAM
  • 240GB SSD

Acer Chromebook 311

  • 1.1GHz Intel N4000
  • 4GB RAM
humble sundial
#

2011 mac, generally, the better specs, the better it is. (It could be different depending on the situation your in.)

odd belfry
heavy oak
lavish prismBOT
#

Hey @heavy oak!

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

heavy oak
#

django.db.utils.OperationalError: (1045, "Access denied for user 'AJR'@'localhost' (using password: YES)")

odd belfry
# heavy oak yea i downloded all that and when i run it it is saying acess denied for the loc...

I think you need to reset mysql root password and create new db and user for your project
https://www.google.com/amp/s/www.techrepublic.com/google-amp/article/how-to-set-change-and-recover-a-mysql-root-password/

TechRepublic

If you never set, forgot, or need to change your MySQL password, you're in luck. This article walks you through these steps, so you'll never be at a loss for that database root user password.

heavy oak
#

this error it is showing when i run python manage.py runserver

heavy oak
#

i am kinda new so i dont know how to create a new db , any resources

heavy oak
#

GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, INDEX , DROP , ALTER, CREATE TEMPORARY TABLES, LOCK TABLES ON **csproject **TO 'AJR'@'localhost'; when i use this code it is showing no database selected but my database name is **csproject **

heavy oak
#

ok it worked srry for the pin g

torpid folio
#

can anyone suggest some good resources to learn django?

marsh canyon
#

There is a tutorial in the documentation

heavy dagger
#

Hi

#

<a href ="index.html"><button type ="submit"> Click here </button> </a>
The form gets submitted but it doesnt get linked to "index.html"

shut plaza
#

Hi. I want to write an API consumer using python, to get data from a web site. Is there any good wrapper library that gives template classes/abstractions? Or I should use requests to develop my own? Thanks.

cerulean badge
#

do you need to purchase storage separately to host media files in digitalocean?
i am talking about media files not static files

civic crater
heavy dagger
#

no

civic crater
#

so what do you want exactly?

heavy dagger
#

the form to get submitted and linked to another page

civic crater
#

u need to use backend for that
but leme see if there's any solution for that

heavy dagger
#

i tried using js

#

but still didnt work

civic crater
heavy dagger
#

js

civic crater
#

it needs to be redirected from backend

heavy dagger
#

so what to do?

civic crater
#

is it a project to be submitted?

heavy dagger
#

yep exactly

civic crater
#

ok wait

heavy dagger
#

thanks

#

sure

civic crater
#

form method is post or get?

heavy dagger
#

post

civic crater
#

action?

heavy dagger
#

not defined

#

actually i got a project from school

#

i havent defined an action

#

the data isnt stored

civic crater
#

ok

#

can you read the question given by your school again or use a back-end?

heavy dagger
#

its in dutch

#

but i ll translate it

#

for ya

civic crater
#

i dont understand dutch
just check yourself

#

from html it is not possible ig

#

we can use jquery

heavy dagger
#

they say create an html form which in which the submit button gets linked to another page

#

idk

#

i ll just skip it then

#

they didnt teach us any javascript yet

#

its just css and html

#

but anyway why is it not possible? @civic crater

civic crater
#

yeah it is possible by backend

#

wait a sec
they didn't said that form needs to submitted

heavy dagger
civic crater
#

yeah i m also trying these

#

and if you need to link the form u need to use backend
they are using PHP for that

heavy dagger
#

is php necessary for type = submit?

#

because i could link any other type with anchor and java script

civic crater
#

yeah bro you can link a button to other webpage

#

but cant submit a form to other webpage in html

#

then there is a need of backend

heavy dagger
#

i cant use js as a backend?

civic crater
#

yeah u can but u need to install node.js

heavy dagger
#

i do have it

civic crater
#

then you are good to go

#

but sorry i dont practice node.js

heavy dagger
#

oof

#

what about php?

civic crater
#

would you like to build it in django?

heavy dagger
#

sorry i dont know django

civic crater
heavy dagger
#

😦

civic crater
#

l'll try if i can help you
as i know basics of node.js

heavy dagger
#

i have visual studio code i m pretty sure i installed it but how do i start a project

dreamy briar
#

excuse me guys, do u guys know how can i group css rules? i wanna do something like below, and i think i've seen it before

/* Pricing section */
#pricing {
    padding: 7% 15%;
  
  .row {
    text-align: center;
    margin: 10px 4.5rem;
  }
}

I want to add further rules for .row elements which has a parent of #pricing

vocal prawn
#

there is a flask application that works with celery + redis. When starting 50-100 tasks, after completing all of them, 2-3 (sometimes 5) tasks freeze, they are not executed. If you restart celery, the tasks that are frozen will be executed.

celery run:
celery --config=dmndmn.celeryconfig -A dmndmn.celery_run.celery worker --loglevel=info --concurrency=5

start tasks:
tasks.start_scan_task.apply_async(args=[id])

#

help please

small dawn
#

I'm a student and can't afford paid domain hosts..
I dont need much from the host just a custom name nothing else. no storage and all.
Does anyone has any ideas where i can get one ???
Please ping me on an answer tyy

small dawn
#

ok ty

native tide
dusk portal
#
@login_required
@cache_page(60*2)
def notes_upload(request):
    if request.method=='POST':
        title=request.POST.get('title')
        subject=request.POST.get('subject')
        desc=request.POST.get('desc')
        thumbnail=request.FILES['thumbnail']
        file=request.FILES['file']
        author=request.user
        entry=Notes(title=title,subject=subject,desc=desc,thumbnail=thumbnail,file=file,author=author,published_on=datetime.now())
        entry.save()
        messages.success('Notes updated successfully!')
        return redirect('/')
    return render(request,'index/notes_upload.html')```
#

it's storing to the db

#

but instead of redirecting

#

it's showing

#

TypeError at /notes_upload/
success() missing 1 required positional argument: 'message'

#

it's saving to the db not a problem but not redirecting insteading of that it gives error

sleek copper
#

How do I serve files requested by flask?

opaque rivet
#

@dusk portal because you need to pass two positional arguments, the request object and the message.

#

Normalise reading documentation

civic crater
sleek copper
#
SITE_NAME = 'https://www.whatsmyua.info'
excluded_headers = ['content-encoding', 'content-length', 'transfer-encoding', 'connection']

@app.route('/')
def index():
    return("nuts")

@app.route('/<path:path>',methods=['GET','POST',"DELETE"])
def proxy(path):
    global SITE_NAME
    global excluded_headers
    if request.method=='GET':
        resp = requests.get(f'{SITE_NAME}')
        headers = [(name, value) for (name, value) in  resp.raw.headers.items() if name.lower() not in excluded_headers]
        response = Response(resp.content, resp.status_code, headers)
        return response
    elif request.method=='POST':
        resp = requests.post(f'{SITE_NAME}',json=request.get_json())
        headers = [(name, value) for (name, value) in resp.raw.headers.items() if name.lower() not in excluded_headers]
        response = Response(resp.content, resp.status_code, headers)
        return response
    elif request.method=='DELETE':
        resp = requests.delete(f'{SITE_NAME}').content
        headers = [(name, value) for (name, value) in resp.raw.headers.items() if name.lower() not in excluded_headers]
        response = Response(resp.content, resp.status_code, headers)
        return response

When I request http://127.0.0.1/test, it acts as a reverse proxy for https://www.whatsmyua.info. The page loads, but the css and js needed by the page don't. How do I fix this?

#
127.0.0.1 - - [16/Sep/2021 13:21:37] "GET /test HTTP/1.1" 200 -
127.0.0.1 - - [16/Sep/2021 13:21:37] "GET /css/style.css HTTP/1.1" 404 -
127.0.0.1 - - [16/Sep/2021 13:21:37] "GET /js/app-built.js HTTP/1.1" 404 -
127.0.0.1 - - [16/Sep/2021 13:21:37] "GET /js/app-built.js HTTP/1.1" 404 -
dusk portal
#

messages.success/error/info(request,'THIS IZ MESSAGE')

#

and then return render redirect HttpResponseredirect n all

#

And in html for object in messages and {{object}}

tawny pollen
#

hello django peeps can you help me ?

open forum
open forum
tawny pollen
#

I want to show in the author detail template the blog posts the author made

#
DETAIL VIEW
class BlogAuthorDetailView(generic.DetailView):
    model = BlogAuthor

    def get_context_data(self, **kwargs):
        # Call the base implementation first to get a context
        context = super().get_context_data(**kwargs)
        # Add in a QuerySet
        context['blog_list'] = Blog.objects.filter(author=self.user)
        return context

MODELS.MODEL
class BlogAuthor(models.Model):
    # author name
    user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
    bio = models.TextField(max_length=1000, help_text='Write a short biography')

    def __str__(self):
        return f'{self.user}'

    def get_absolute_url(self):
        return reverse('blogauthor_detail', kwargs={'pk': self.pk})


class Blog(models.Model):
    name = models.CharField('Blog Name', max_length=200)
    post_date = models.DateTimeField('Date Posted', auto_now_add=True)
    author = models.ForeignKey(BlogAuthor, on_delete=models.CASCADE, null=True, blank=True)
    text = models.CharField('Blog Text', max_length=1000, help_text='Short description of your blog')

    class Meta:
        ordering = ['post_date']

    def get_absolute_url(self):
        return reverse('blog_detail', kwargs={'pk': self.pk})

    def __str__(self):
        return f'{self.name}'

TEMPLATE HTML
        <!-- Section 2: Contact Information -->
        <section id="contact-info">

            <h2>Blogs List</h2>

            <ul>
                 {% for blog in blog_list %}
                      <li><a href="{{ blog.get_absolute_url }}">{{ blog }}</a></li>
                 {% endfor %}
            </ul>

floral herald
#

Any one can suggest me described django rest framework YouTube tutorial?

jovial cloud
true kernel
#

Hello people! I had a problem.
My homepage takes too much time to load, so what I wanna do is show some other page until it loads, and then show the original page, and I was wondering how I can do this. Any ideas? I suppose this is a common issue. I am using django btw. And you can check out the project at https://github.com/ayushsahu247/StockInvestingApp

GitHub

A stock investing web application built on Django. Click on the youtube link given below for demo. - GitHub - ayushsahu247/StockInvestingApp: A stock investing web application built on Django. Clic...

true kernel
jovial cloud
true kernel
#

Thanks, but my site isnt online

#

guess its time to take it online

jovial cloud
jovial cloud
jovial cloud
true kernel
#

wheres the arrow button?

jovial cloud
#

Have you tried to inspect element in Google Chrome

true kernel
#

what then?

jovial cloud
# true kernel what then?

On the pane with elements, console, sources and others, there should be an arrow at the end(or lighthouse on that pane)

true kernel
#

so i have to do this on my localhost's page?

jovial cloud
#

Yeah, when you load the page in Google Chrome, you run lighthouse on it(Generate report btn)

#

Usually, JS is the culprit for slow page loading

true kernel
#

i think

#

thanks man!

jovial cloud
true kernel
#

where do i get this data?

jovial cloud
jovial cloud
brave stag
#

in Django how can I configure the error log to be sent by mail
every time there is an error, it should be sent by mail

rotund perch
#

what is better, knox auth or JWT based auth?

random tundra
#

do people use and configure django admin interface in actual products? in either base django or a rest api?

true kernel
#

Any idea how to deal with MemcacheUnexpectedCloseError?

exceptionpymemcache.exceptions.MemcacheUnexpectedCloseError
Bases: pymemcache.exceptions.MemcacheServerError

Raised when the connection with memcached closes unexpectedly.

This is all I got from the documentation 😦

true kernel
glacial yoke
#

so, I'm using python django with react, and I am creating an SPA website
I have a few pages that just need to render the index.html file, because all the frontend is filled in by react
so I have created urls for those pages, but for some reason I can only render the root website directory(localhost:8000), but whenever I try to load something else, for example I have a url /profile, it just gives me an error, saying that it couldn't get /profile/static/main.js
urls.py:

from django.urls import path
from . import views

urlpatterns = [
    path('', views.IndexView.as_view()),
    path('profile/', views.IndexView.as_view()),
]

views.py:

from django.shortcuts import render
from django.views.generic.base import View

class IndexView(View):
    def get(self, request):
        return render(request, 'index.html')

index.html:

<script src="static/main.js"></script>

template dir's in settings:

PROJECT_ROOT = os.path.dirname(__file__)
'DIRS': [
            os.path.join(PROJECT_ROOT, 'static') #Ρ‡Ρ‚ΠΎΠ±Ρ‹ ΡƒΠΏΡ€ΠΎΡΡ‚ΠΈΡ‚ΡŒ Ρ…Ρ€Π°Π½Π΅Π½ΠΈΠ΅ шаблонов
        ],

I just don't understand, why does it look for the main.js file in /profile/static/main.js, but not just /static/main.js
because when I go to the root url of the site, everything is fine

#

nevermind, people of the internet, I fixed it by changing <script src="static/main.js"></script> to

{% load static %}
    <script src="{% static 'main.js' %}"></script>
native tide
#

im just trying to create a simple documentation for my discord bot how would i learn how to do that

glacial yoke
native tide
#

the md file would be easier correct.

#

?*

calm plume
#

What kind of docs are you trying to make? User docs or developer docs?

native tide
#

for the cmds and stuff of my bot

calm plume
#

For users I'd just use markdown

opaque rivet
#

For absolute paths prefix it with /

glacial yoke
opaque rivet
#

But of course your solution with static is always best, because then you can dynamically change all of the src of your static files.

wary flint
#

Hey, i'm creating a web app and I need to ensure the user can only access only their data. What is the recommended secure way of doing this? So far, it seems you use the same database and filter by user=request.user. Do you have any links or documents / youtube videos I should watch to do this in a highly recommended way.

sick mason
glossy scroll
#

hey guys i have a javascript question

#

Im sending an array like so

$('#proceed').click(function(){
        var items = [];
        $(':checked[data-assetid]').each(function(index,value){
            var assetid = value.dataset.assetid;
            items.push(assetid);
        });
        var data = {
            'csrfmiddlewaretoken':$('input[name="csrfmiddlewaretoken"]').val(),
            'item':items
        };
        $.post( "/test/", data,function(data){
            alert(data);
        });


    });
#

but what im receiving is

{'csrfmiddlewaretoken': 'B9XLe2X4tj7DGoist0liricYmTayfSYibxHDbruEl78Kgf1c1smobwmIwI2SunSm', 'item[]': '23271161534'}
#

why is that bracket there

#

I have not set it in the dict but its automatically being added when its sent to django

terse vapor
#

how can i add uuid into the flask module?

terse vapor
#

it keep shows the error sqlalchemy.exc.CompileError: (in table 'patient', column 'subid'): Compiler <sqlalchemy.dialects.sqlite.base.SQLiteTypeCompiler object at 0x7fbf5afe6dc0> can't render element of type UUID

rustic sky
#

Okay I am genuinely stuck

#

well, I'm gonna wait after this person

vestal hound
#

and authorisation

#

what framework are you using?

versed lotus
wary flint
wary flint
terse vapor
#

That make sense ig

heavy oak
#

hey i added a css file with html using vsc and when i see the preview it is working , but when i run my server using python manage.py runserver and it is showing only html file not the css file effects coming

opaque rivet
#

@heavy oak your page is probably cached. Hard reset the cache with ctrl + F5

heavy oak
#

it worked thank you

jovial cloud
opaque rivet
#

@wary flint Yes, but to access request.user you need a method of authorization, to actually get a user object from the request.

final latch
#

need help storing user input from a html form into a txt file but it wont work idk why, everything works on windows but wont work on ubuntu for some reason

final latch
#

nope its html/php related

#

thats why i put it here

#

idk if this is supposed to be strictly python tho but i assumed not necessarily since its a webdev chat

vestal hound
#

e.g. asking for non-in-depth help with your JS frontend that connects to a FastAPI backend is usually okay

#

but if it's like a PHP backend...maybe not πŸ˜”

graceful leaf
#

i got this error please help

cerulean badge
#

can i test stripe webhooks in production without stripe cli?
i created a endpoint but the event is not recieving

civic crater
#

Hey i have a text field stored in my database.
But when i show that in my html template the new lines doesn't show the new line.

cerulean badge
#

use linebreaks filter

#

{{ text|linebreaks }}

civic crater
#

but i also want to use safe filter

cerulean badge
#

you can chain filters

civic crater
#

like this {{ text|linebreaks| safe }} ?

#

no it doesn't worked

cerulean badge
civic crater
#

done this {{text|linebreaks|safe}}
it shows new line
but dont render it in safe filter

cerulean badge
#

why you need safe?

#

for markdown?

civic crater
#

because i want to use html snippets

civic crater
cerulean badge
#

use the markdown package

civic crater
#

ok leme try

#

bro it worked when i did changed the position of safe filter
like this : {{text|safe|linebreaks}}

#

TY

cerulean badge
#

lol np

graceful flax
#

Hi,
I'm using DRF
I wanted to know about if DB queries are transactional, I'm making use of postgres

For instance my current code is

group = Group.objects.get(id= <id>)
member = Member.objects.get(id=<id>)
current_points = group.points
member.previous_points = <some int(ex:20)> from <somewhere>
member.save()
group.points = member.previous_points + current_points / <some int> (Assume there's a division by zero exception thrown here)
group.save()

Is the data to member object saved or is it omitted until everything is succeeded?

#

What I understood is by default it uses autocommit mode

inland oak
#
  1. linux like Windows has file and folder permissions for reading/writing/executing. Perhaps you don't have writing rights in your linux folder.
#

P.S. Small advice, consider developing from ubuntu desktop if you are deploying to ubuntu server.

#

It will make life much easier

#

Since you would test your program in your development area in advance to work for linux

#

It is one of twelve app rules actually

odd belfry
velvet yew
void heron
#

Hey guys, can i do a question about html and css here?

maiden heart
#

Can anyone hop on a quick call and explain to me and a friend some key concepts about web communication? somewhat related to the requests library.

hazy night
#

Hello everyone, I currently have a pending question in the help-avocado section in regards of a Django question if anyone is available I would much appreciate the help !πŸ™‚

timber vortex
quick cargo
#

no

#

github pages are purely static e.g. raw HTML, JS and CSS

timber vortex
#

hmmm

#

thanks

maiden heart
#

Can someone explain to me the concept of Keep-Alive & Connection Pooling? in the voice channel is preferred

native tide
#

how can i debug a site like this , not sure if its called debug or wtv

merry dust
#

anyone uses django consistently?

torn arrow
#

is there any option that i can make a free website with my own hetzner server? i want to make a bot who links my website where you can register

opaque rivet
#

Only browsers enforce cross origin requests, so does anyone know if you requested a server resource from another origin and you used django-cors-headers, would the request be successful, or would it be blocked?

fiery zenith
#

hello where can i please find illustrators to do this?

terse vapor
#

<a href="/update-patient/{{patient.subid}}" this is my html code for a button, and i made the route to /update-patient/patient.subid, but whenever i click on it, it always brings me to update_patient/{{patient.subid}}

#

how can i fix it?

native tide
#

hi

#

how do i turn a datefield into a string

#

in django

native tide
# native tide how do i turn a datefield into a string

Same way as datetime.date should work:

>>> from datetime import date
>>> foo = date.today()
>>> foo
datetime.date(2021, 9, 18)
>>> str(foo)
'2021-09-18'

generally - when you call sth like print(foo) it should return str automatically.

white cove
#

Hello i have a question. What stack usually django goes in?

nova pewter
merry dust
#

LOL

#

can you give more context @white cove ? are you talking about what frontend stuff django plays well with?

white cove
white cove
pastel knot
#

im trying to display in image located in my static file but from within my vue app

stray notch
fiery turret
#

reCaptcha isnt allowing captchas from my local area IP address

#

i put in 192.168.1.166 and it is saying invalid domain for site key

pine torrent
#

what are the steps to be professional back end developer with Django

dense cloak
cerulean badge
#

(context django) when i have login required to a view and someone who is not logged in tries to post request to that url then he is redirected to login page and after login do they get redirected to that previous url with post request?

civic crater
#

hey what is recommended to make a login/logup systm in django?
by making a auth app?

pastel knot
# wooden ruin wym

I'm rendering my Vue app from within a Django template but I can't get an image to show up

meager anchor
#

let's solve it here - where is the connection failing? do you get the request in nginx, but get an error in your app? do you get an error in nginx trying to connect to the app?

meager anchor
# pine torrent what are the steps to be professional back end developer with Django

there's no predefined way of how to become a professional developer with anything. imo, what you are looking for is to work with django until you find yourself comfortable enough to build your apps in it easily, and follow best practices of the community. it's also always a good idea to help out with open source projects using django, if that interests you

meager anchor
stark tartan
#

Please

marsh canyon
#

@stark tartan hey, we wouldn't want anyone to post invite links publicly on the server

#

and it can be unsafe in some situations

stark tartan
#

Sorry but I have to slove problem fast

#

I deleted now

marsh canyon
#

you can always carry out discussion in our voice channel and ask for stream perms if necessary

pale wadi
#

hey i want to download pycharm for web development does the base community version support html , css and javascript? or i need to buy the professional version?

stark tartan
#

Hey I am deploy django channel on liunx sever with nginx it is socket connection is failing over https

If some one have knowledge please

meager anchor
#

post your full question

#

which error are you getting, from where, how did you configure it

meager anchor
#

wss:// is encrypted, and your site doesnt have any ssl configured. so wss will most likely fail while doing the tls handshake

stark tartan
#

Website is working fine

#

But WS creating problem

#

In HTTPS mode

#

Did you ever done thess thing

meager anchor
#

your nginx config mentions gunicorn.sock, are you running this under gunicorn? judging from the channels docs you need an ASGI server to server websockets

stark tartan
#

Yes

#

Shall I send that

meager anchor
#

use a server like daphne or uvicorn

stark tartan
#

Can you come on VC or other thing

#

It's important bro

quasi summit
#

Sorry guys, I don't know where else to ask so I'm asking here. I'd like to have a domain like awake.com and want to create different mails for different services so I know which asshole company leaks or sells my mail to others. What do I need to buy (VPS? Just a Domain?) to establish a system like that?

mild matrix
#

Should we learn HTML or its not required for web development

#

I learnt python basics

#

And want to go for web development

#

I study computer science not biology

#

I will take it as yes

stark tartan
mild matrix
#

Ok

#

I thought by different library html would not be required

#

In python

stark tartan
#

Thanks for support

coarse yoke
#

hey there! can I enabled on the heroku gzip compression?

potent sundial
#

I am running django with gunicorn inside a docker container on port 8000
I also have a nginx web-server set up listening on port 80 and redirecting requests to upstream server on 127.0.0.1:8000 (django docker container) it all works well, however website is also accessible through http://domain_name.com:8000 and I can't find out how to prevent it, can anyone help me figure this out?

crisp cosmos
#

hey guys, maybe someone could help me finish setting up my project with django+vue+webpack?

#

my dev.py settings:

from .settings import *

DEBUG = True
ALLOWED_HOSTS = ["*"]
MIDDLEWARE.append("debug_toolbar.middleware.DebugToolbarMiddleware")
INSTALLED_APPS.append("debug_toolbar")
INTERNAL_IPS = ("127.0.0.1", "localhost")

WEBPACK_LOADER = {
    "DEFAULT": {
        "BUNDLE_DIR_NAME": "",
        "STATS_FILE": os.path.join(BASE_DIR, "frontend/webpack-stats.json"),
        # 'STATS_FILE': BASE_DIR.joinpath('frontend', 'webpack-stats.json'),
    }
}

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
]
MEDIA_URL = "/dmedia/"
MEDIA_ROOT = os.path.join(BASE_DIR, "mediafiles")

STATIC_URL = "/static/"
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")

VUE_ROOT = os.path.join(BASE_DIR, "frontend\\static\\")

#

CUT FROM settings.py :


import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(
    os.path.dirname(os.path.abspath(__file__))))
STATICFILES_ROOT = os.path.join(BASE_DIR, "staticfiles")



# Application definition

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "ObjectMgr",
    "webpack_loader",
]

ROOT_URLCONF = "ObjectMgr.urls"

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [
            os.path.join(BASE_DIR, "templates"),
        ],
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": [
                "django.template.context_processors.debug",
                "django.template.context_processors.request",
                "django.contrib.auth.context_processors.auth",
                "django.contrib.messages.context_processors.messages",
            ],
        },
    },
]

WSGI_APPLICATION = "ObjectMgr.wsgi.application"


# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.sqlite3",
        "NAME": os.path.join(BASE_DIR, "db.sqlite3"),
    }
}

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/

STATIC_URL = "/static/"


#

index.html

{% load render_bundle from webpack_loader %}
{% load static from staticfiles %}

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>frontend</title>
  <meta http-equiv=X-UA-Compatible content="IE=edge">
  <meta name=viewport content="width=device-width,initial-scale=1">
  <link rel=icon href="{% static 'favicon.ico' %}"> {% render_bundle 'chunk-vendors' %}
</head>

<body><noscript><strong>We're
      sorry but frontend doesn't work properly without JavaScript enabled. Please enable it to
      continue.</strong></noscript>

  {% for i in 'abc' %}
  <strong>{{ i }} DJANGO PART</strong>
  {% endfor %}

  <div id=app>
  </div>
    {% render_bundle 'app' %}

</body>

</html>
#

wsgi.py

"""
WSGI config for ObjectMgr project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ObjectMgr.settings")

application = get_wsgi_application()

#

urls.py

import os

from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.urls import path
from django.views.generic import TemplateView
from django.views.generic.base import RedirectView
from django.views.static import serve

favicon_view = RedirectView.as_view(url=os.path.join(settings.STATIC_URL, "favicon.ico"), permanent=True)

urlpatterns = [
    path("favicon.ico", favicon_view),
    path("", TemplateView.as_view(template_name="index.html")),
    path("admin/", admin.site.urls),
    url(r"^static/(?P<path>.*)$", serve,
        {"document_root": settings.STATIC_ROOT}),
    url(r"^dmedia/(?P<path>.*)$", serve,
        {"document_root": settings.MEDIA_ROOT}),

    url(r"^media/(?P<path>.*)$", serve,
        {"document_root": os.path.join(settings.VUE_ROOT, "media")}),
    url(r"^img/(?P<path>.*)$", serve,
        {"document_root": os.path.join(settings.VUE_ROOT, "img")}),
    url(r"^js/(?P<path>.*)$", serve,
        {"document_root": os.path.join(settings.VUE_ROOT, "js")}),
    url(r"^css/(?P<path>.*)$", serve,
        {"document_root": os.path.join(settings.VUE_ROOT, "css")}),
    url(r"^fonts/(?P<path>.*)$", serve,
        {"document_root": os.path.join(settings.VUE_ROOT, "fonts")}),
]

if settings.DEBUG:
    import debug_toolbar
    urlpatterns = [
        url(r"^__debug__/", include(debug_toolbar.urls)),
    ] + urlpatterns

#

vue.config.js:

var BundleTracker = require('webpack-bundle-tracker')
var WriteFilePlugin = require('write-file-webpack-plugin')


module.exports = {
  outputDir: (process.env.NODE_ENV === "production" ? 'dist' : 'static'),
  publicPath: '/',

 devServer: {
    publicPath: "http://localhost:8080/",
    headers: {
      "Access-Control-Allow-Origin": "*",
      "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS",
      "Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept, Accept-Encoding, Accept-Language, Access-Control-Request-Headers, Access-Control-Request-Method",
      "Access-Control-Allow-Credentials": "true",
    },
  },

  chainWebpack: config => {
    config.optimization.splitChunks({
      cacheGroups: {
        vendors: {
          name: 'chunk-vendors',
          test: /[\\\/]node_modules[\\\\/]/,
          priority: -10,
          chunks: 'initial'
        },
        common: {
          name: 'chunk-common',
          minChunks: 2,
          priority: -20,
          chunks: 'initial',
          reuseExistingChunk: true
        }
      }
    })
  },
  configureWebpack: {
    output: {
      filename: 'js/[name].js',
      chunkFilename: 'js/[name].js'
    },
    plugins: [
      new WriteFilePlugin(),
      (process.env.NODE_ENV === "production" ?
        new BundleTracker({
          filename: 'webpack-stats-prod.json',
          publicPath: '/'
        }) :
        new BundleTracker({
          filename: 'webpack-stats.json',
          publicPath: 'http://localhost:8080/'
        })
      )
    ]
  }
}
#

first problem in index.html:

'staticfiles' is not a registered tag library. Must be one of:
admin_list
admin_modify
admin_urls
cache
i18n
l10n
log
static
tz
webpack_loader

if I change import from {% load static from staticfiles %} to {% load static from static %} I get another error related to webpack configuration that I cannot fix

In template /ObjectMgr/templates/index.html, error at line 12

WebpackBundleLookupError at /

Cannot resolve bundle chunk-vendors.
#

Any help with this would be much appreciated

terse vapor
velvet yew
crisp cosmos
native tide
#

I'm having some trouble with authentication with my web app and I"m getting this error, any ideas how to fix it?

#

I'm using firebase and react

solar lodge
#

Whenever my client API tries to connect to my sio web server it returns this error ```
Traceback (most recent call last):
File "/usr/local/lib/python3.9/site-packages/quart/asgi.py", line 311, in call
await self.app.startup()
File "/usr/local/lib/python3.9/site-packages/quart/app.py", line 1757, in startup
await gen.anext()
File "/app/run.py", line 43, in func
await sio.connect(url="http://172.20.128.2:5000")
File "/usr/local/lib/python3.9/site-packages/socketio/asyncio_client.py", line 144, in connect
raise exceptions.ConnectionError(exc.args[0]) from None
socketio.exceptions.ConnectionError: Unexpected status code 404 in server response

crystal stag
dusk portal
#

oo

solar lodge
native tide
#

how should I write a docker-compose and Dockerfile for a flask backend with postgres?

cerulean badge
#

(context django) how do i pass the next url to redirect to after login to login_required for a specific view?

stark tartan
cerulean badge
raw compass
dense cloak
#

error

relevant code

def user(value):
  with open('allowedKeys(v1).json', "r") as E:
    k = json.load(E)
    try:
      return k[value]['name']
    except KeyError:
      return "Error 404 user not found"

def V2_encode(name, key):
  with open("allowedKeys(v1).json", "r") as E:
    l_E = json.load(E)
    l_E[key] = {"name" : name, "key" : key, "attrs" : {"Private" : "None", "Admin" : False}}
  with open("allowedKeys(v1).json", 'w') as E:
    json.dump(l_E, E)

def V2_decode(name):
  with open("allowedKeys(v1).json", "r") as E:
    k = json.load(E)
    try:
      return dict(k[name])
    except KeyError:
      return "account not found."

@app.route(f'/dev-point/{set_route()}/<name>')
async def ocn(name):
  V2_encode(name, assigner.give_id())
  return V2_decode

@app.route('/')
async def return_landing():
  return redirect('/landing')

@app.route('/landing')
async def call_():
  return await render_template("landing.html")

@app.route('/login/@<name>')
async def asd(name):
    return await render_template('the-game.html', name=user(value=name))
  


@app.route("/sign-up")
async def aksj():
  return await render_template("sign-up.html")

@app.route('/sign-up', methods=['POST'])
async def on_():
  key = assigner.Create()
  txt = (await request.form)['text']
  V2_encode(txt, key)
  login_key = V2_decode(txt)['key']
  return redirect(f'/login/@{login_key}')

if you have an answer please ping me :D

true kernel
#

Hey people

#

How to render a dummy page until the real one is loaded?

#

a page like this

#

Is it possible that I send data as it is computed, instead of waiting for it all to compute and then send?

cerulean badge
#

(context django)
pq = Product.objects.annotate(sales=Sum('items__quantity'))
when i loop over pq and print sales of every product it prints them correctly
but when i pq over this it doubles the sales anyone knows why?
pq = Product.objects.annotate(sales=Sum('items__quantity'), rating=Avg('reviews__rating'))

warm patio
#

hey yall, how do youll use react and django in production with authentication and everything, i use http proxy middle ware to proxy api calls but it only works in dev mode not when deployed on prod and i need proxy since the user doesnt get saved in the request if i dont proxy

opaque rivet
# true kernel a page like this

You'll need to use a JS frontend framework, you can render a skeleton page and then populate that page with data from AJAX API calls which happen asynchronously

true kernel
#

alright, good. Where do I start learning this?

opaque rivet
true kernel
#

I know some react

#

i dont know any AJAX

opaque rivet
true kernel
#

no

#

what it do

opaque rivet
true kernel
autumn hedge
#

I'm migrating my flask + uWSGI stack over to FastAPI + Uvicorn but would hope uvicorn has a multi-application mode

#

multi-application mode should allow us create multiple processes per FastAPI applications

#

The way uWSGI doe it by using the emperor mode. Emperor mode will watch a folder of ini config files. Each file corresponds to a single python app.

final meteor
#

Hello Everyone
https://datatables.net/examples/api/multi_filter_select.html

This url has a datatable
i want to reduce the column widths of this datatable so that it takes as less of the horizontal space as possible.

I am trying to add more columns here and it goes out of the page width and table starts horizontal scroll.

autumn hedge
final meteor
#

i tried responsive: true,
but it will strip off columns automatically to fit the view. it will only show the first X columns that fit in the webpage

#

i was able to get around this by

<style>
  table.dataTable tfoot th,
  table.dataTable tfoot td {
  padding: 0px 0px 0px 0px;
  border-top: 5px solid #111
}
  table.dataTable tbody th,
  table.dataTable tbody td {
  padding: 5px 5px
}
</style>
paper vigil
#

when I zoom out... to see the page smaller... my page breaks. I have it set for cross-browser compatibility so I'm not sure why this happens

versed python
#

Layout?

paper vigil
#

yes

paper vigil
jovial cloud
# sleek copper How can we fix that?

I don't know. The Response object in flask is designed to return the request body as html so for sites with inline css, you won't have issues but if they have external resources(like css, js), you cant have access to those resources

versed python
#

Maybe use rem units so that everything scales proportionally

paper vigil
#

I'll try it

versed python
#

I'd recommend you to look for solutions online

#

There might be better ones

paper vigil
#

I am

native tide
#

Hello everyone,

I am facing a problem relating to my FastAPI - backend with my Vue - frontend. I have a CORS middleware, and having Axios connecting my "http://localhost:5000" (Fastapi - backend) with my Vue - frontend. But whenever I access my "http://localhost:8080" (Vue - frontend), it's showing raw html, and saying it has no JavaScript enabled. (My JavaScript is 100% enabled, btw..) I'll attach an image of the data returning on the webpage ("http://localhost:8080" (Vue - frontend).

If someone maybe knows what I am doing wrong, please let me know, I would really appreciate that! If more information needed, please let me know.

Thanks in advance.

inland oak
paper vigil
inland oak
native tide
#

I will, thanks a lot for your fast reply @inland oak !

past cipher
#

How do you preserve new lines in Jina?

 Hello Sir,

I can't see my grades:/

new lines aren't keep with the above text

late fjord
#

It has been a while since I didn't visit discord, at first I didn't know anything, just some html a little bit of css, python and django. things now changed

#

I want to learn flutter but to learn flutter you should learn dart, should I do that? I am just looking for advice, btw, I don't know js. which one should I go for.

cursive pine
#

Folks is there a way to get color palletes in bulk? Copy paste hex codes in bulk for generative art?

#

Perhaps a 100-500 pallettes all together?

quick aurora
#

Can i make web site in Android?

warm igloo
warm igloo
# quick aurora Can i make web site in Android?

Can you explain? Android is an operating system. Using a browser on an Android device you can visit a website. But what do you mean "make web site in Android"?

Can you make one in Java or Kotlin (the primary languages used for Android App development)? Sure you can. But it has nothing to do with Android. You'll look for web frameworks for Java or Kotlin.

warm igloo
quick aurora
cursive pine
warm igloo
#

I don't fully understand.

You can make a website in HTML, CSS, and JS (the basic stack) and you can visit from an Android device.

Or you can build a website in the same languages Android apps are developed in (though you'll still need HTML, CSS, JS [likely]) depending on what the site is you want to build.

You can even use web languages like JS to build out entire apps and cross-compile them to both iOS and Android using Flutter, React Native, Cordova, and a dozen other projects.

fallow cairnBOT
warm igloo
quick aurora
warm igloo
quick aurora
warm igloo
#

No. You can use a text editor. Just gotta get it hosted somewhere once you're ready. Netlify.com, GitHub Pages, free hosting sites or plans.

quick aurora
fiery turret
#

I am using gunicorn, nginx, and flask (following corey schafer's linux deploy walkthrough) and nginx isnt serving my static files

#

thats my nginx config

#

and here is my app

#

the path is correct /home/connors/flask/flask_app/static

#

i have looked online and havent found anything that has helped

#

when i go to 192.168.1.236/static/main.css i get a 403 error

true kernel
#

Django problem: I want to render a page, while I do some computations, and then render the page again. How can I do that?

fiery turret
#

NGINX doesnt have permissions to look at my static files. How do I elevate NGINX permissions???

#

idk how to give nginx permission

inland oak
fiery turret
#

chmod -R 777 /home/connors/flask/

#

changed to static folder still no cigar

inland oak
fiery turret
inland oak
#

which linux server do u use

fiery turret
#

this is running on ubuntu server on a raspberry pi 3b+

inland oak
#

service ufw stop

#

try using this

#

it will disable your firewall

#

which can be an issue

native tide
#

i am making a react project that uses discords oauth2 and integrates with flask and when u click a button on the react side it redirects to the flask discord oauth2 but i cant think of a way to make sure authentication has taken place on the react side so they cant just type in the url manually, any ideas?

fiery turret
#

im sure there is some really stupid user error here

inland oak
#

there will be two text files there with some details perhaps

fiery turret
#

access.log: 192.168.1.166 - - [19/Sep/2021:18:20:19 +0000] "GET /static/favicon.ico HTTP/1.1" 403 134 "http://192.168.1.236/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:92.0) Gecko/20100101 Firefox/92.0" a bunch of these

#

error.log: 2021/09/19 18:20:19 [error] 3906#3906: *31 open() "/home/connors/flask/flask_app/static/favicon.ico" failed (13: Permission denied), client: 192.168.1.166, server: 192.168.1.236, request: "GET /static/favicon.ico HTTP/1.1", host: "192.168.1.236", referrer: "http://192.168.1.236/" a bunch of these

inland oak
#

u know, it looks familiar

#

referrer.... is a wort of some security mechanism i think, although it can be not involved here

#

what's your nginx config file for starters

fiery turret
#

i have tried it with and without the slash at the end

#

In this Python Flask Tutorial, we will be learning how to deploy our application to a Linux Server from scratch using Linode.

If you would like $20 of free credit towards a Linode account, then you can use my link here to sign up:
https://linode.com/coreyschafer

We will be covering the entire deployment of a Flask application. This includes s...

β–Ά Play video
#

im following this walkthrough

#

everything has been just fine up until now

inland oak
#

slash at the end

fiery turret
#

i tried it just now again and still no dice

#

restarted nginx after adding too

inland oak
#

lets remove server_name for now

fiery turret
#

like this?

inland oak
#

yeah

fiery turret
#

nope

inland oak
#

and add location /static/ {

fiery turret
#

im sorry this is so frustrating

inland oak
#

slash at the end of it too

fiery turret
#

nope

inland oak
#

Β―\_(ツ)_/Β―

#

at this stage I exhausted blindly shooting the target

#

only real look would work I guess

#

I would guess a filesystem permission problem I think

#

perhaps chmod was not enough to solve the issue

#

@fiery turret try moving your project to /web folder (which lies at the root of your system) (create the folder)

#

and hosting it from there

#

I think you could have some conflicts with that you are trying to host it from your home user folder

#

even chmod, could be not enough for nginx to access it

fiery turret
#

i cant cd into /root

inland oak
#

do cd /

#

and mkdir web there

#

i said /web path, not /root/web

#

don't forget to apply chmod -R 777 at this folder after you are done

jovial cloud
# fiery turret

Try changing your alias to /home/... /static; without the last forwardslash

fiery turret
#

(venv) connors@flask-server:/web/flask$ gunicorn -w 1 run:app
-bash: /home/connors/flask/venv/bin/gunicorn: No such file or directory

#

oh wait

inland oak
#

create venv from zero

#

python3 -m venv venv

#

venv can't be moved, it will have its internal absolute paths broken

abstract knoll
#

hello

#

mf

#

@dusty moon dont worry he is gay

fiery turret
#

hes the most helpful person on this server

normal pebble
#

!mute 887097812704182283 πŸ”Ž

lavish prismBOT
#

:incoming_envelope: :ok_hand: applied mute to @abstract knoll until <t:1632080394:f> (59 minutes and 59 seconds).

dusty moon
fiery turret
#

im installing requirements.txt

inland oak
#

we could have resolved it also, by launching nginx with root rights πŸ˜‰

#

but whatever, that is the solution too

fiery turret
#

THANK YOU

#

holy cow, bro you dont even know

inland oak
#

it works? πŸ˜‰

fiery turret
#

i have been tearing my hair out for 2 and a half hours

#

yeah it works

inland oak
#

πŸŽ‰

fiery turret
#

can i put up my firewall again?

inland oak
#

sure

#

make holes for http/https traffic in it on your own if necessary

#

and allowing incoming connections to flask at 8000 port from localhost too, if necessary ;b

fiery turret
#

all working fine thank you again

#

im gonna go drink some water and take a walk

inland oak
#

just kidding

opaque rivet
#

What do you guys think of this form design?

floral herald
#

when a create a new user I got "Direct assignment to the forward side of a many-to-many set is prohibited. Use groups.set() instead." this error.

wooden ruin
#

svg's are cool

fiery turret
#

Im trying to create a supervisor, but it cant find the location to my gunicorn

#

is there a way to find where its located?

#

ive tried using 'find' but didnt work

#

nvm im a genius

fringe aurora
remote hawk
#

I have a question as:

#

Which library is usually used to make a website using python?

#

or framework, like what's market requirement right now!

wooden ruin
remote hawk
native tide
#

,.p

lean cedar
#

Hello, everyone

#

I have a few questions about getting django set up. Should I install system wide? Also, if I install on virtual environment do I have to install django through pip every time on separate env under the folder associated with it?

fringe aurora
lean cedar
#

Great, thank you fr! So for example would the code look like this:

cursive sorrel
#

Hi all

#

I'm having a slight problem on something that I suspect is stupidly easy

#

if we imagine I have the following data structure:

    pass

class ModelB(models.Model):
    a = ForeignKey(ModelA)```
#

and I run the following queryset:
A.objects.values()

#

I have no idea how to get values from Model B

#

I want to do something like this:
A.objects.values(ModelB__id)

#

but just not sure how to get values when the foreign key is held on the other table (so to speak)

indigo kettle
#

you can get the related objects like
A.modelb_set.all()

#

that returns a query of all the modelb objects which have a foreign key pointed to modelA

cursive sorrel
#

ooo that's interesting

#

is there a way to be more specific and only select the desired fields from Model B

indigo kettle
#

yes, but I never do that. I think it is using values as you're trying to do

#

it's just a normal query so you can do normal query things

#

A.modelb_set.filter(id=5)

#

for example

#

I guess you can do A.modelb_set.all().values('id', 'some_other_field')

heavy oak
#

hey i am showing an error in django when i import module from my app floder for example if my apps name is sample when i import from sampleapp.module import user(my models name) and when i run the server it is showing sample.sampleapp module not found pls help

cursive sorrel
#

thanks so much @indigo kettle ... will google the hell out of it

indigo kettle
#

np!

#

@heavy oak did you add your app to the apps list in your settings.py

heavy oak
#

yea

indigo kettle
#

and where is the error happening?

#

what are you trying to import?

heavy oak
#

when i import the module and run my server using python manage.py runserver it is saying

from sample.sampleapp.models import User ModuleNotFoundError: No module named 'sample.sampleapp'

indigo kettle
#

You have two imports that I think are trying to import the same thing

#

I think you can delete the first line

heavy oak
#

yea thanks it worked πŸ™‚

heavy oak
# indigo kettle I think you can delete the first line

can you tell me an example that my edit text is recieving the messge
<form class="box" action ="register" method="POST"> <h1>REGISTER</h1> <input type="text" name="Rusername" placeholder="Username"> <input type="text" name="Remail" placeholder="Email"> <input type="password" name="Rpassword" placeholder="Password"> <input type="text" name="Rconfirmpassword" placeholder="Confirm Password"> <input type="submit" name="RegisterBtn" value="Register"> </form>

heavy oak
# heavy oak

when i run a print function over here it is not working

indigo kettle
#

you are trying to print something inside of an html file?

heavy oak
#

i just want to know if my input funciton works or not like if i wrote something on username and click register i need to know that it is accepting the name how do i know it

heavy oak
stable coral
#

i'm following a flask blog tutorial, and after implementing blueprints, my site is messed up

#

It looks like this

#

when it should actually look something like this

#

bruh... I deleted everything in the css file and pasted it back in and now it's fixed

#

I've had this issue many times where flask shows messed up looking websites for no reason

#

Anyone know the cause?

tawny pollen
#

it’s a mapping between URLs and the view functions that should be called for those URLs.
what does "mapping" mean?

tribal python
civic crater
#

Hey

#

What is MultiValueDictKey error in django?

cerulean badge
#

logo_django2

class Product(models.Model):
  name = models.CharField(max_length=200, unique=True)
  price = models.DecimalField(max_digits=10, decimal_places=2)


class Order(models.Model):
  user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        related_name='orders',
        on_delete=models.SET_NULL,
        null=True
    )
  placed = models.DateTimeField(null=True, blank=True)


class OrderItem(models.Model):
  order = models.ForeignKey(
        Order,
        related_name='items',
        on_delete=models.CASCADE
    )
    product = models.ForeignKey(
        Product,
        related_name='items',
        on_delete=models.CASCADE
    )
    quantity = models.PositiveIntegerField(
        default=1,
        validators=[MinValueValidator(1)]
    )

how would you annotate each product with the sum of its orderitems quantities that have order__placed__isnull=False?

floral herald
#

What's the best way to login with email in django djoser (jwt based authention)

odd belfry
late fjord
hoary brook
#

Hello everyone, I'm creating a website where users can upload files to the server, but I can't manage to construct the full file path when I want to delete it again. This is how I am saving the file, so how can I get the full path to remove it again?

def save_sheet(sheet):
    # Rename file and return full file name
    _, f_ext = os.path.splitext(sheet.filename)
    sheet_fn = secrets.token_hex(8) + f_ext
    sheet_path = os.path.join(app.root_path, 'static/user_content', sheet_fn)
    sheet.save(sheet_path)
    return sheet_fn


@app.route('/file/new', methods=['GET', 'POST'])
@login_required
def new_file():
    form = FileForm()
    if form.validate_on_submit():
        # Construct full file path to save and pass to file instance
        sheet_file = save_sheet(form.sheet.data)
        sheet_path = url_for('static', filename=f'user_content/{sheet_file}')
        created_file = File(title=form.title.data, subject=form.subject.data, author=current_user, sheet=sheet_path)
        db.session.add(created_file)
        db.session.commit()
        return redirect(url_for('dashboard'))
    return render_template('create_file.html', title='Upload File', form=form)```
#

Feel free to @ me if you can help! Thanks.

next oxide
#

hi guys

late fjord
#

Hi

next oxide
#

Hi guys can someone help me with this
Im trying to move the "about us" to the right a little bit and it will be fixed there no matter what
Can someone recommend me how to do it
Thanks guys

late fjord
#

You can put them both in a div ```
<div>
<img>
<a>About us</a>
</div>

#

and in your styles you can do div { display: flex; postion: fixed; top: 0; left: 0; }
you are also forgetting to put these :::::::

#

:

stark tartan
#

Hey anybody use AWS 300$ credit please ping me I want ask some questions

late fjord
#

@next oxide

next oxide
#

Tks I’ll try

jovial cloud
hoary brook
cerulean badge
#

(django) how do i pass the url to redirect to after successful login with redirect?

pearl ore
#

hi!!

cursive pine
#

Folks how does one convert animtaed GIFs into animated SVGs?

cerulean badge
#

(django) any libraries to have mobile no. and otp based authentication?

eternal blade
#
LOGOUT_REDIRECT_URL = ...
LOGIN_REDIRECT_URL = ...```
cerulean badge
#

its already solved but thanks

#

(django) any libraries to have mobile no. and otp based authentication?

true kernel
#

Hey I need some celery help

#

This my views file

from django.shortcuts import render, HttpResponse
from .tasks import *
from django.core.cache import cache

# Create your views here.
def home(request):
    # cache.set('name', 'ayush', 2)
    set_name.delay(10)
    name='shreya'
    print(cache.get())
    if cache.get('name'):
        name = cache.get('name')
    return HttpResponse('Hi, from celery- '+name)

This my tasks file

from celery import shared_task
from time import sleep
from celeryApp.models import Hero
from django.core.cache import cache


@shared_task
def set_name(duration):
    sleep(5)
    cache.set('name', 'ayush', 10)
    return None

But the page still shows name as 'shreya', and not 'ayush'

lost snow
#

Hey guys need some wise advice...
please...
I need to get a job or atleast a internship in 6 months. I need to develop knowledge about web development.
I only know the basic knowledge of python.
(Print string in reverse, print triangle pattern ,etc)
I am not sure about front end and backend development...
Can I become a good backend developer by only knowing django , flask .
Do I have to learn about DSA,HTML , CSS,etc????
Which one can i avoid as a backend developer

nova pewter
#

You can skip DSA imo, but you should know basic html tags no matter what you do in web dev.

nova pewter
hazy night
#

Is anyone available for an issue with serving media files ?

digital edge
#

What is the most widely used modern stack for python in 2021?

#

i'm talking front end backend DB middleware etc

inland oak
digital edge
#

ok and what DB is most often used with that

inland oak
digital edge
#

i'm just looking for the most marketable set to verse myself in since i haven't dove too deep in the python end of professional web/app dev

#

but i enjoy python more than anything else i work with so it seems like the understandable thing to pursue

digital edge
#

i don't really like JS

hazy night
#

Well last time I wrote a lot and no one replied I wanted to make sure someone was available but ok here I go:
I’m currently writing on mobile*

I have in my media file a folder named 15 with pdf files in it. My goal is to be able to click on the hyperlink that is on a table according to the patient & open up that pdf file.

Now I have my Django href ready and they display accordingly to the patient. However when the link is clicked I’m getting a page not found and I’ve been trying to figure out what could be set up wrong along the lines of either settings, my model, my html template, or urls & perhaps my view.

I can give any further information as a screenshot as code snippets are quite difficult right now for mobile

inland oak
#

backend is anything, for python it is django and fastapi popular

digital edge
#

i see

#

and you're saying django is most often paired with postgreSQL?

inland oak
#

you can actually do some front with python frameworks, but it is quite limited in what it can do

inland oak
#

from SQL family

#

for a single person

limber dew
#

what do you mean by its limited ?

inland oak
#

or you are limited to html/css only

#

extensive JS usage is not really good looking there without frontend frameworks

inland oak
#

plus I use Redis for caching and messaging queues

#

different types of DBs fit different tasks

hazy night
#

This is an example : of the main page (127.0.0.1:8000/show) show which is my html template

#

My file hierarchy as demo as root is as followed :

>demo
>media
   /15
     All the pdf files
>patients (main app)
>static 
Db.sqlite3
Manage.py```
#

For my media url and root it is as followed :

MEDIA_ROOT = β€œUsers/Dany/Desktop/demo/media”```
#

In my urls.py it is set up as followed for media along with the proper imported modules :

   Urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT```
#

Inside my show.html which is my one and only html file serving the table and database I have

{for pat in patient %}
<Td><a href = β€œ(β€˜\media\{{pat.file_name| urlize’}}” target = β€œ_blank|_self|_parent|_top|framename”>{{pat.file_name}}</a></td>
#

For the model I’m only going to be referring to the file field :

class Patient(models.Model:
file_name = models.FilePathField()

#

I’m sorry for the extensive post but I want to give as much detail possible, if any more details are required or needed for further assistance please do not hesitate.

#

Any help would be appreciated

nova pewter
#

any good tutorials i can follow to learn drf?

hazy night
#

EDIT: managed to resolve the issue FINALLY after two days attempting this. The resolution was to change the

<Td><a href = β€œ(β€˜\media\{{pat.file_name| urlize’}}” target = β€œ_blank|_self|_parent|_top|framename”>{{pat.file_name}}</a></td>

To:


<Td><a href = β€œ\media\{{pat.file_name| urlize’}}” target = β€œ_blank|_self|_parent|_top|framename”>{{pat.file_name}}</a></td>

#

Thanks guys ! I knew the rubber duck theory would help πŸ˜‚

#

If anyone has any suggestions to recommend please don’t hesitate ! Just @ me and I’ll be pending improving the app, thanks again !

tranquil fossil
native tide
#

So i have this in django:

class SliderViewSet(viewsets.ReadOnlyModelViewSet):
    """
    API endpoint.
    """
    queryset  = Text.objects.raw(''' SELECT * FROM text WHERE id in (SELECT MAX(id) FROM text GROUP BY domain_id ) order by date_visited desc limit 10  ''')
    serializer_class = SliderSerializer
    permission_classes = [permissions.IsAuthenticated]

It seem this does not refresh everytime i do a get request, only when i restart the server.
How can i make sure that everytime i do a get request the api refresh the info that it have?

random sand
#

Hello I want to make a note-taking app

#

Any suggestions

warm igloo
#

How far have you gotten? What suggestions are you looking for (front end, back end, db, interface questions, what?)

warm igloo
# native tide So i have this in django: ```python class SliderViewSet(viewsets.ReadOnlyModelV...

I think you need to consider this "queryset - The queryset that should be used for returning objects from this view.Typically,you must either set this attribute, or override the get_queryset() method. If you are overriding a view method, it it important that you call get_queryset() instead of accessing this property directly, as queryset will get evaluated once, and those results will be cached for all subsequent requests."

Above is from this tut: https://github.com/subhra2508/django-rest-framework-tutorial

I'm not a big Django user, but some examples I've seen override get_queryset in your viewset class and that helps make sure that the query runs every time and not just the first time django fires up the viewset.

This seems fairly unintuitive.

warm igloo
tiny snow
hazy night
versed python
bright spindle
#

A query such as this one:

Poll.objects.filter(
   Q(group__public=True) | 
   Q(
      Q(group__owners__in=[user]) | 
      Q(group__admins__in=[user]), 
      group__public=False)
   ).order_by('-created_at')

Is creating a ridiculous amount of duplicate query objects, does anyone know why this happens?

#

the only thing i want is to filter if the group is public, or the group is not public (but the user is an owner/admin of the group)

bright spindle
#

narrowed it down, apparently it duplicates itself everytime Q object is comparing something, 5 members = 5 duplicates + 2 owners = 2 more duplicates

hazy night
#

Hate to be another again on this thread, but I’m trying to hyperlink a folder all the files inside.

Example:
Media/4182554/all pdf files

#

I’m receiving a 404 issue β€œdirectory indexes are not allowed here”

#

If needed above I have details of the project including file hierarchy, settings, models, urls

#

Sorry if there is some grammar issues or some things don’t make sense, I’m pretty fried from working on this clients hcms haha

hazy night
#

My question is at the end of it:

How can I click this hyperlink to open up said folder and serve all the files inside of it ?

glad karma
#

can someone pls suggest good front end dev resource?

umbral rock
#

freecodecamp to learn html and css seems like the way to go

nova sonnet
#

whos tryna hold this wood while i code?

native tide
#

i need a good project

#

who got a project idea

#

pls

glacial yoke
#

how can I make an axios post request to my django db, from my react app

axios
      .post("/api/message", {
        message_author: personaname,
        message_text: newmessage,
      })
      .then((response) => {
        console.log(response.data);
      })
      .catch((err) => {
        console.log(err);
      });

when I run the code above, considering that personaname and newmessage are both strings, it just doesn't work
someone, help, please

native tide
#

pls help

light cloak
#

Hello hello

#

I'm wondering if anyone knows whether it is okay or not to modify something within base Django

#

Specifically, I've modified a line in formsets.py in site-packages which completely sorts out an error I've been getting

#

Is this a bad thing?

tribal python
#

It's probably unadvisable

#

If the error your getting appears to be a Django issue it would be prudent to create an issue if one doesn't exist for it

#

If it is not intrinsic to Django, you'd best to fix the issue in your application

#

Rather than modifying Django to work around your own issue

#

Of course this is all very general information

#

I'm not personally familiar with Django, and I am not looking at your code or the Django code you've modified

#

So I cannot give anything concrete

#

But in general yes, it tends to be bad practice to in place modify a third party library that you're using

#

And unrelated but@native tide please do not bump help channels in other chats, be patient. If someone is available to help they will.

#

Anyway, hope that helps @light cloak ^^

light cloak
#

@tribal python I thought that might be the case. It's a shame because Django is apparently not really geared towards dynamic forms, which is what this issue revolves around. An error is being thrown up because I'm using an attribute of Django which has an index of None, and the error is due to index being compared to an integer further in the code. Very frustrating. Thank you very much for your answer though!

tribal python
#

I mean, if you can propose a change to Django that wouldn't negatively affect any other circumstance but help improve applications such as yours, it could definitely be worth bringing to them.

light cloak
#

Would be interesting to know if it wouldn't negatively affect other applications - I'm fairly inexperienced so I doubt I'd be able to know either way - but I'll see if I can submit a ticket and get them to perhaps take a look at it πŸ™‚ Good suggestion

native tide
#

Hi

#

I'm trying to add a field to my model in django for that I made a migration like this


from django.db import migrations, models
import uuid


class Migration(migrations.Migration):

    dependencies = [
        ('interface', '0011_auto_20210627_2247'),
    ]

    operations = [
        migrations.AddField(
            model_name='post',
            name='postid',
            field=models.UUIDField(default=uuid.uuid4, unique=True),
        ),
    ]
#

when I try to run it i get an error

DETAIL:  Key (postid)=(85fd7975-0fc8-427c-a0e5-f0c387524bce) is duplicated.
dusty moon
#

Is JavaScript useless outside web development?

opaque rivet
warm igloo
#

it's also sometimes used as a scripting lang inside of other tools

dusty moon
#

So, I can build a regular old app which is just a normal executable with a normal GUI?

#

Like Python or any other language does

warm igloo
#

not sure off top of head, but there is Electron which allows you to make desktop apps with HTML/CSS/JS

#

slack, vscode, and other apps you may have used use Electron

#

discord desktop app -maybe-

dusty moon
#

Oh, ok.

#

So, node.JS is for server stuff and networking and generally boring stuff?

warm igloo
#

haha, I guess .. can build whole websites with it, run api services, I've written some scripts in it that never even touch the web but just run on a schedule

technically nodejs is inside electron too which sets up some cool things you can do between the client js and the backend js

#

but yeah if I were to make a desktop gui, I wouldn't look to js first

dusty moon
#

Oh, cool.

#

Well, thanks for the explanation, I appreciate that!

warm igloo
#

any time

normal eagle
#

yo ppl, can a css wizard help me out, I am having trouble with a flexbox thingy, I would prefer dm's since i can explain better and not clutter this channel, thanx!

native tide
#

hi

#

how can I get a user's IP in flask?

#

request.remote_addr isn't working

#

Thank you

native tide
#

mobile apps, web apps front end and backend, 2d/3d games, and even hardware programming like arduino

warm igloo
# native tide how can I get a user's IP in flask?

Yes, you can. But not while on replit it seems. Likely replit, for safety reasons, is launching all of your code in an independent container and then serving up the content via proxy.

For instance, when you go here: https://DazzlingIgnorantApplicationprogrammer.thebouv.repl.co

You can see that I'm echoing out request.remote_addr and that the value is a non-routable private address. Likely the address of the proxy making the request.

So a visitor makes the request, it passes through some "stuff", something ELSE makes the request, returns it, and then THAT is showed to you.

Same thing could happen if you had Cloudflare or something in front of your app. You likely will end up with the IP of the load balancer, NOT the address of the user (unless the load balancer itself is setup to pass through the ip but they usually do that via X-FORWARDED-FOR headers). It can get tricky but as far as I can tell you can't really get around it on replit due to how they do their setup. A traditional host wouldn't be like that (unless of course the aforementioned load balancing is in front of it).

warm igloo
#

You can even see X-Forwarded-For on there. But even that address isn't the visitor for instance.

#

As when I visit I see 35.191.15.131 and that isn't my address.

#

That IP is for GCP which is probably where replit.com is hosted.

#

((or a host is using GCP, and that host is hosting replit))

#

GCP meaning Google Cloud Platform

native tide
#

cleared it up

#

πŸ™‚

warm igloo
#

you're welcome

native tide
#

whats beige #

#

nvm

carmine talon
#

Hello, I'm building some cool app with django and drf. But I'm a embarrased how my code is with drf serializers. They are a bit complex and have to juggle with requests that may have an instance or not.
I have a lot of "if self.instance:" conditions in object and field validations. It makes the reading hard.
How can I avoid this and split the code better ? Two different serializers for creation and update ?

weary pebble
#

Hi there! I'm doing this website where there are three buttons(they represent 3 products) which when clicked need to display their corresponding prices. Could someone please help me out with this? I was thinking this could be done with js but idk how

lost snow
#

How can I download Google app engine in windows 10?
I already have Python 3 installed.
I download something called "Google Cloud shell" and it looks like command prompt.
I don't know what to do? Someone helpe out...

stark tartan
#

Is django rest framework is necessary to learn as we also have to learn React with it??

#

If I am looking for jobs with django

mild lichen
#

should i ask about my doubt in android studio here?

civic crater
heavy dagger
#

do i need to learn js if i have a good knowledge of how django works?

manic frost
#

But you don't need JS to make a website - depending on what website, of course.

frosty plinth
#

Can anyone help me out with the helium module?

civic crater
native tide
# dusty moon Good to know

don't though. Just use it for browser interaction you can't achieve with css/html. phone users prefer native as js is the slow 90s tech built into chrome. Also don't use electron to bundle a 120mb chrome just to run a few hundred lines of js. Just learn something native. Maybe Unity or Unreal for game dev as they are performant and dont run like a dirty 90s browser tech that needs replacing.

dusty moon
native tide
dusty moon
#

Good one.

hollow charm
#

Hey guys i have a quick question. I have an api endpoint that has pages of data in json format that i'm getting with grequests. It updates every 5 minutes (+- 10 seconds). What would be the best say to store those 200 pages of data with it's ETAG attached (so i can compare it to the new one and replace it if it was updated)?

#

sorry if wrong chat

native tide
#

use a json db. i.e. coucdb or mongo. then you can just use a http api to update it

#

couchdb has that built in. really simple. mongo a little harder than couch but you get mongo ql and its more popular.

#

JSON dbs have http apis built in. so often you're wasting your time parsing when you could have a view with a map/reduce function

hollow charm
#

ah so those db use json internally? I was using mySQL and it was kinda counterintuitive to connect to the database every 5 seconds just to retrieve ETAG

native tide
#

serilaising to json is a waste of time IMO return html whenever you can. But as you said you have json to begin with . i'd stick with json

hollow charm
#

yeah i have no control over api sadly

native tide
#

couchdb you can learn in a day or 2. it stores json blobs. you can have API endpoints built into the db that you POST GET from. using the same json blob.

#

so if its change just POST it

#

and it will update

hollow charm
#

amazing. I gonna look into Mongo since i see it quite often. TYVM

native tide
#

ye. i think it has a native http interface now. it never used to.

past cipher
#

How to loop through this dict with nested data?

{'English': 
    {'student': 'John Doe', 'coursework': 'English List 2.3', 'status': 'Accepted', 'comment': 'Very nice bit of coursework, John.', 'grade': '89'}, 
     'student': 'Scott More', 'coursework': 'V3 Ttest', 'status': 'Not Submitted', 'comment': '', 'grade': ''}
#

With Jinja

#

nvm just realised its not a nested div

#

the second student section is missing brackets

stark tartan
#

How much time is required to learn django rest freamework

opaque rivet
#

@past cipher ```
{% for student in your_dict['English`] %}

{{ do_something_here }}

{% endfor %}

past cipher
#

yeah the problem is when I create the dict on the backend

#

i've been having trouble all day with it

opaque rivet
#

@past cipher what is the problem?

past cipher
#
 grade_info = []
course_exists = False  
teacher_courses = TeacherInformation().fetch_teacher_courses()