#web-development

2 messages · Page 132 of 1

lilac belfry
#

Okay ty

quick cargo
#

all gonna be the same speed rendering wise though shrug

wanton ridge
#

i recommend flask before django. I am learning and using flask@lilac belfry

#

but it's all up to you

lilac belfry
wanton ridge
#

then it's fine

lilac belfry
#

I’m gonna probably try sanic

#

It seems good

toxic flame
#

at the end of the function

return redirect("url")

#

if you have the url named after something then its even better

#

for instance

#

path("", mainPage, name="index")

#

Then the "url" would be "index"

wanton ridge
native tide
#

yep, do it with flask flashing

native tide
wanton ridge
#

i don't know jinja2, i am just learning flask

native tide
#

flask templates use jinja2

wanton ridge
#

ohh i see

native tide
#

also if you are using some sort of form from WTforms I'm pretty sure you can do something similar by accessing form.field.errors

wanton ridge
#

i will check it

wanton ridge
# native tide flask templates use jinja2

like flash('Invalid Email') and the in html i just create a div and {% with messages = get_flashed_messages() %} then copy the boostrap alert-danger and do it 3 times?

native tide
#

I think this this problem would be more easily solved by just showing the form.field.errors below each field

#

And flashed messages used for one time alerts, like a success message

wanton ridge
#

ahh ok thanks a lot

hasty valve
#

can someone help me with django

#

my signal does not work

native tide
#

@hasty valve sure, can you show us your signals?

wanton ridge
#

{% with messages = get_flashed_messages %} {% if messages %} {% for message in messages %} {(message)} {% endfor %} {% endif %} {% endwith %}

TypeError: 'function' object is not iterable. Can anyone help me with this
native tide
#

For messages in get_flashed_messages()

#

No need for the with block

hasty valve
# native tide <@517230607139602432> sure, can you show us your signals?

from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.dispatch import receiver
from .models import Profile

@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
instance.profile.save()

#

it does not work

#

it's in a seperate signals file

#

@native tide

native tide
#

So profile.objects.create(user=instance) is not saving anything?

Where are you testing this? In manage.py shell?

#

profile = Profile(user=instance)
profile.save()
Should be good

wanton ridge
#

flash("Username must contain only characters and numbers!")

File "C:\Users\richi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\flask\helpers.py", line 423, in flash

session["_flashes"] = flashes

File "C:\Users\richi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\werkzeug\local.py", line 350, in __setitem__

self._get_current_object()[key] = value

File "C:\Users\richi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\flask\sessions.py", line 102, in _fail

raise RuntimeError(

RuntimeError: The session is unavailable because no secret key was set.  Set the secret_key on the application to something unique and secret. What i am doing wrong here
hasty valve
native tide
#

@hasty valve not sure what you mean here. How are you testing your post_save receiver?

#

with python manage.py shell?

#

if so, you have to import both your models AND your signals, which from your previous message looks like you aren't importing your signals.

hasty valve
#

i'm testing it on my website

native tide
#

Not sure why that isn't working

#

Do you know if the signal is being ran at all

ruby plover
#

hi, is anyone able to help me #help-bread pls? im stuck, i have no clue how to proceed

oak drum
#

Small question, on Django, if I decide to load the templates per app (a.k.a., APP_DIRS:True), how do I reference the path to the template on the view?

fierce canyon
#

I keep getting this error: "Uncaught TypeError: Cannot read property '89753857873166336' of undefined"
Anyone know what's up?

function fetchData() {
                const xhr = new XMLHttpRequest(); 

                xhr.open("GET", "inventory.json", true); 

                xhr.onload = function () { 
                    if (this.status === 200) { 

                        obj = JSON.parse(this.responseText); 
                        return obj;
                    } 
                    else { 
                        console.log("File not found"); 
                    } 
                } 
                xhr.send(); 
            }

            var data = fetchData();
            
            function getParameterByName(name, url = window.location.href) {
                name = name.replace(/[\[\]]/g, '\\$&');
                var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
                    results = regex.exec(url);
                if (!results) return null;
                if (!results[2]) return '';
                return decodeURIComponent(results[2].replace(/\+/g, ' '));
            }

            var userID = getParameterByName('userID');
            var items = data[userID];
warm junco
#

Does anyone have a quick suggestion on a quick way to setup up an Ubuntu box to receive webhooks? Can that be done easily with Flask? What other dependencies does it need? Nginx? WSGI?

warm igloo
#

Depends? XD

#

for testing? flask or fastapi and you can just use the built in python webserver

#

public and hosted and scalable? yeah there will need to be more involved

warm igloo
#

For instance, try to refactor it so that you do the lookup in the onload if status is 200 instead of doing a return cause it isn't working the way you think it is.

wicked elbow
#

anyone know why im getting a 404 error all of a sudden on my static files. nothing has changed as far as i know

#

errors in console:

m:1 Refused to apply style from 'http://127.0.0.1:8000/static/frontend/stylesheet-main2.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
m:14 GET http://127.0.0.1:8000/static/mobile/main.js net::ERR_ABORTED 404 (Not Found)
#

solved, i turned debug off, which put django into production mode. since django isnt built to serve files, it wasnt serving the static files anymore

fierce canyon
abstract magnet
#

Is django hard to learn

wicked elbow
abstract magnet
#

What is the hard part

glad patrol
#

i am displaying icon on my logout text

#
<a class="nav-item nav-link mr-3" href="{{ url_for('logout') }}">
<b><i class="fa fa-sign-out fa-2x" type="image/x-icon" style="color: red"></i>Logout</b></a>```
#

but it display like this

oblique kite
#

How to store access token without using session?

native tide
#

Hello everyone, is there anyone who has already used validators in django?

native tide
native tide
#

anyone know whats the best way to store images with django? I was thinking of having an image upload and then saving it to imgur or some sort of cdn, and saving urls in db

wicked elbow
native tide
#

continuing to save directly to your server would probably run up the hosting bill compared to uploading to some sort of cdn, I think I'll work with some apis here.

wicked elbow
#

its just no easy to do and be user friendly. set a file size for uploads. or shrink the files server side. otherwise just give them an input to put the url of their image in. but its extremely not user friendly to force users to sign up for another service simply just to upload a profile image for example. youd be surprised at how many images fit in small spaces.

wicked elbow
#

and 3rd party hosting puts you at the mercy of the 3rd party for download speeds to display it

hard cargo
#

Is there a HTML validator extension for VScode?

lavish prismBOT
#

Hey @novel dome!

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

novel dome
#

Hi guys. I am trying to get this project up and running but for some reason doesn this django web application refuse to start and I have no idea where to look. I know that it runs on another computer in the team but I cannot get it running at all.

django.core.exceptions.ImproperlyConfigured: Cannot import 'test'. Check that 'minitwit.apps.TestConfig.name' is correct.

https://paste.pythondiscord.com/facidegeyi.sql

dreamy pecan
#

Good morning! I'm trying to generate a XML file using the writexml method from the minidom module. Does anyone know why the root is next to the version thing?

misty goblet
#

in django, how would you set a field be changed once specifically False -> True and not the other way around?

latent dagger
dreamy herald
#

Wondering if I can get some help with Django, I'm trying to migrate a blog post model. And get this error:

django.db.utils.IntegrityError: column "author_id" contains null values

I added null=True onto the author, but that didn't seem to help.


  class PostObjects (models.Manager):
    def get_queryset(self):
      return super().get_queryset().filter(status='1')

  title = models.CharField(max_length=200, unique=True)
  slug = models.SlugField(max_length=200, unique=True)
  author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='wiki_posts', null=True)
  updated_on = models.DateTimeField(auto_now=True)
  content = models.TextField()
  created_on = models.DateTimeField(auto_now_add=True)
  pub_date = models.DateTimeField('date published')
  status = models.IntegerField(choices=PostStatus, default=0)
  objects = models.Manager() #default manager
  postobjects = PostObjects() #custom manager
  
  # class Meta:
  #   ordering = ('-pub_date',)

  def __str__(self):
    return self.content
  
  def was_published_recently(self):
    return self.pub_date >= timezone.now() - datetime.timedelta(days=1) ```
latent dagger
toxic flame
#

also a quick suggestion and a question, why would you return self.content uwu

#

maybe you dont use the admin panel provided by django, but like if u do it might look messy i dunno

dreamy herald
# latent dagger try adding `blank=True` for your `author_id`

With blank=True, I get this error

You are trying to change the nullable field 'author' on engineeringtheorypost to non-nullable without a default; we can't do that (the database needs something to populate existing rows).

I also tried adding a followup default='', but that landed me back to my first error.

dreamy herald
latent dagger
#

Also in the article they are user POST instead fo User, maybe that could be where the issue resides

outer pier
#

Hii, I want to use service worker with django with angular as my front-end for push notification I tried many libraries over web and could nt find that solve my problem . If I used node as my backend everything works fine . could somebody help me to do the same with django

arctic sentinel
#

I am trying to migrate it but can't. Where is the problem Please help me. Thanks in Advance.

arctic sentinel
#

no

#

is it required

toxic flame
arctic sentinel
#

??

native tide
#

@arctic sentinel show us your INSTALLED_APPS in settings.py

arctic sentinel
#

After api.apps.ApiConfig I have given,

#

Which I have nit given that time

#

Taking screen shot

#

Then

#

Then This crap is coming

#

And Now I am banging my head against the wall

glad patrol
#

hi need help regarding flask

outer pier
#

what actually is that

toxic flame
#

maybe its the "api" lib

#

not sure whats that

#

if you're trying to make an api using drf is a good choice as well

#

There is also alot of method on making an api

#

csrf_exempt is also a good thing when its apos

#

Apis

native tide
# arctic sentinel

INSTALLED_APPS is a list, you forgot a comma between api.apps.ApiConfig and rest_framework

#

There's your solution

native tide
upper perch
#

Could someone help me get oriented?

I'm wanting to self host a simple markdown/hugo theme'd site with images that are updated every few minutes.

What tools should I be using for this? Do I build with hugo then host with nginx? Am I able to run hugo server inside tmux and have users be directed to that port?

When I change images in /static/images/..., will they update for the user or will they see old cached images?

(edit: I think hugo server is only for testing while building, and nginx is how we're meant to host?)

abstract magnet
#

Can someone give me good css frameworks

#

Is there any good tutorials for bootstrap

oblique kite
#

Hello guys ..
Attached is the code to get access token from cache which expires every 10 mins. So every 10 mins I have to refresh the token but I'm not able to calculate the expiry and call refresh token API.

native tide
#

nice font/color scheme

cunning mortar
#

Hello, noob here. Is there any good tutorial to make a login system with flask + pymongo?

glacial wigeon
#

Can someone tell me how do you set up pre-orders in ecommerce websites? I'm trying to build one with django and would like to have this functionality present. But I'm stumped as to how this works...

native tide
#

@glacial wigeon you can have an 'Orders' model and have orders with a specific type, e.g. preorder or not

#

BooleanField

native tide
native tide
glacial wigeon
native tide
#

@glacial wigeon yep!
Either give the Product model a boolean field, or the Order model to specify a pre-order. Both work!

dreamy herald
toxic flame
native tide
#

@toxic flame this is null = True

Blank just specifies whether the field is required in forms.

#

@dreamy herald can you show me the error? I cant see replied msgs on phone

toxic flame
#

Hmmm i see

native tide
#

hi

#

guys

#

so where I can learn flask

#

?

warm seal
native tide
#

thx @warm seal

haughty cape
#

can i get some help

native tide
haughty cape
#

@native tide

#

You decent and web scraping

abstract magnet
#

can someone help me on hosting a website

#

im about to buy this host but i want to make sure i can use my code for it

#

can anyone help im using django

ruby plover
#

anyone good with flask free to guide/help me? ive been stuck on this issue since yesterday and i dont know how to proceed #help-chili

native tide
#

I used a validator to catch the errors and show them directly in the browser on the phone field.

#

When I fill the field with a number less than 10, it displays a message such as:

#

I don't understand what is happening

#

Can someone help me?

whole sierra
#

@native tide

#

show the function in your views

native tide
#

wait!

toxic flame
#

You're returning nothing to the website

native tide
toxic flame
#

ignore the urls its not the urls

whole sierra
#

ok

#

so

#

add the following

#

context['form'] = form

#

remove {'form': form}

#

and replace that with context

#

lets see what returns

native tide
#

Okey, i try this

toxic flame
#

ok i need to read more i am blind

#

xd

whole sierra
#

@toxic flame lemme try fix this for a sec bud

toxic flame
#

heh

whole sierra
#

also, instead of posting a screen shot of the code

#

type ` three times and then add py and close with three more

native tide
#

it doesn't work!

whole sierra
#

show us the code

native tide
#

`def details(request):
if request.method == 'POST':
form = UserFormDetails(request.POST)

    if form.is_valid():
        form.save()
        return redirect('thank')
else:
    form = UserFormDetails(initial={'username': request.user.username, 'email': request.user.email})

    return render(request, 'home/signup.html', context['form']= form)`
whole sierra
#

no this isnt what i said

#

here just copy this last part

toxic flame
#

you should rewrite the whole code for him

whole sierra
#

context['form'] = form

return render(request, 'home/signup.html', context)

#

implement that on the last two lines

toxic flame
#

Its also not necesarry for a "context", his method also works

native tide
whole sierra
#

i think he wants to return the name to the page

#

@native tide you can just remove 'context' all together if youre not planning on showing it on the html page

toxic flame
#

Im curious where this goes

whole sierra
#

@toxic flame respect the chat and dont type unless you want to contribute

toxic flame
#

I would but you suggested me to be quiet for a moment

native tide
#

`def details(request):
if request.method == 'POST':
form = UserFormDetails(request.POST)

    if form.is_valid():
        form.save()
        return redirect('thank')
else:
    form = UserFormDetails(initial={'username': request.user.username, 'email': request.user.email})
    context = dict
    context['form'] = form

    return render(request, 'home/signup.html', context)`

even that doesn't work

whole sierra
#

how long have you been coding in python

#

you need a better understanding of the language to accomplish a successful django project, but I will fix this for you

native tide
#

Finally, wouldn't it be a version problem?

whole sierra
#

no

#

you dont have a basic understanding of dictionaries

#

so i dont understand why you are attempting to create a django project

#

it will be very difficult

#
def details(request):
    if request.method == 'POST':
        form = UserFormDetails(request.POST)

        if form.is_valid():
            form.save()
            return redirect('thank')
    else:
        form = UserFormDetails(initial={'username': request.user.username, 'email': request.user.email})
    context['form'] = form

    return render(request, 'home/signup.html', context)
#

wait

#

dont copy that yet

#

what is your html file called @native tide

#

signup.html or home/signup.html

#

@native tide

toxic flame
#

It's not the html location's fault. If it was the error would be invalid template uwu

native tide
whole sierra
#

ok

#
def details(request):
    if request.method == 'POST':
        form = UserFormDetails(request.POST)

        if form.is_valid():
            form.save()
            return redirect('thank')
    else:
        form = UserFormDetails(initial={'username': request.user.username, 'email': request.user.email})
    context['form'] = form

    return render(request, 'signup.html', context)
toxic flame
#

honestly i dont think this is gonna work

native tide
#

It raise an error: context is not define

whole sierra
#

@toxic flame stop

#

no reply

#

just stop

toxic flame
#

Look azza, if you don't know what you're doing don't

whole sierra
#

@toxic flame cmon man go away

#

find something better

toxic flame
#

You're wasting this man's time

whole sierra
#

if you dont have anything just stop

toxic flame
#

i do

toxic flame
#

Whatever my free time is over

whole sierra
#

@native tide send a screenshot of the page

native tide
#

before or after the error?

whole sierra
#

send a screenshot of the page that shows up @native tide

native tide
whole sierra
#

so the page is working now?

#

the error is gone @native tide

native tide
#

No, that is before to fill fields

#

Okay, thank you both for helping me out. I think I need to rest a little, maybe I'll find the loophole.👍

toxic flame
#

lol

austere relic
#

In HTML/CSS, if I got two images, one larger as background and one smaller as subject, how can I place the smaller relative to the bigger one and then scale them together so they fit the display?

#

for example, position the smaller one exactly at pixel coordinates X,Y of the bigger one

native tide
#

where should i start learning flask?

arctic sentinel
twilit needle
glad patrol
#

i have index.html page it require image to upload after i upload image the label choose file still remain same i need to change the label instead of choose file-> filename.png i use custom-file label

#
<div class="row mb-5">
        <div class="col-md-6 m-auto mb-5">
        </div>
    </div>
    <div class="row">
        <div class="col-lg-12 pt">
            {% if form %}
            <form method="POST" action="" enctype="multipart/form-data">
                {{ form.hidden_tag() }}
                <div class="form-group">
                    {{ form.picture.label(class="custom-file-label", for="files", id="files", label="files") }}
                    {{ form.picture(class="file custom-file-input", type="file") }}
                    {% if form.picture.errors %}
                    {% for error in form.picture.errors %}
                    <span class="text-danger">{{ error }}</span></br>
                    {% endfor %}
                    {% endif %}
                </div>
                <div class="mt-4 text-center">
                    {{ form.submit2(class="btn btn-outline-info") }}
                </div>
            </form>
            {% endif %}
        </div>
    </div>```
#

i try this but it didn't work

#
 <script>
            $('#files').on('change',function(){
                //get the file name
                var fileName = $(this).val();
                //replace the "Choose a file" label
                $(this).next('.custom-file-label').html(fileName);
            })
        </script>```
cloud slate
#

hey so i was trying to create a simple graph with chart.js, but it dosent display anything its just blank idk why tho ```html

<!DOCTYPE html>
<html>
<head>
<title>sample</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
</head>
<body>
<canvas id="lineChart" width="900" height="400"></canvas>
<script>
var ctx = dccument.getElementById("lineChart").getContext("2d");
var lineChart = new Chart(ctx, {
type: "line",
data: {
labels: ['1', '2', '3', '4', '5', '6']
datasets:[
{
labels: "Data Points",
data: [89, 43, 128, 122, 113, 12]
fill: false
lineTension: 0.1
}

            ]
        },
        options: {
            responsive: false
        }
    });
</script>

</body>
</html>```

#

and those datas are recived from flask

cold portal
#

maybe its just my eyes, but "ctx. " doesnt look right

#

new Chart(ctx. {

#

shoudlnt it be ,

cloud slate
#

yea i fixed that its still the same

wicked elbow
#

anyone know how to add modwsgi to apache. its installed, but i cant seem to get it to show up

turbid estuary
#

anyone knows SQLAlchemy?

followed = db.relationship('Follow',
                                foreign_keys=[Follow.follower_id],
                                backref=db.backref('follower', lazy='joined'),
                                lazy='dynamic',
                                cascade='all, delete-orphan')

can you explain the backref part in this
as far I know, the value to backref could be used by the other table, to access this column stuff, right? and the other table would have a "variable" called follower(from backref) to access this column,
its like this column followed exits in table Follow under the name of follower
☝️ is that all good?
ping me to reply please

native tide
#

Who is good on django please ?

wicked elbow
native tide
reef jackal
#

guys should i learn django or ruby on rails ? ping me if you have an answer

native tide
#

try both and choose the one you like the most

toxic flame
#

These r some major parts of deployment

opaque vigil
#

If someone is more experience with react-stripe-js, I would appreciate any help.

native tide
#

Would I be able to get a job in web development with a pre computer science degree?

vale mesa
#

Hi, Everyone, As a web developer, I am looking for a remote job. Could you help me?

abstract magnet
cold portal
cloud slate
#

yea i did that

#

long back lol

#

but thanks

haughty cape
#

Whats the best python webframe?

toxic flame
#

There is no "best" there is prefered hehe

tulip estuary
#

Which is the "preferred" ?

toxic flame
#

I prefer django

#

though others might prefer flask

#

Flask is lighter though

native tide
#

both have their pros and cons

#

but i would suggest flask

#

its easier to start with

tulip estuary
#

Great ! Thanks to you both

toxic flame
#

Yea flask for beginners good

#

Because its light weight

#

But django is also good and its alot simpler than flask

#

Django is "monolithic" but it really isnt.

night pilot
#

Hello, how can i add Meta Tags to a html file that will display the meta data on discord? (flask)

#

nvm, ignore it

toxic flame
#

Anyone got an django socket resources I could learn from would be nice to link me :)

wind kraken
#

Hey, quick question using Flask SQLAlchemy. Any way to get a default value of a column?

opaque vigil
#

Hello everyone.

I am trying to integrate stripe into my project, but I am having a small problem with my Pay Button disabled attribute.

I am following the basic example of react-stripe-js.

My components in one file:

CheckoutForm and InjectedCheckoutForm: https://pastebin.com/XSr54pMt

The other component where I am calling the function loadSprite that returns a property (this works fine), and I am assigning it's value to a state, so I can pass it to the sprite prop in the Elements component that came from the parent component CheckoutForm.

ViewMembers.js: https://pastebin.com/swvCeQQd

The problem is even though loadSprite function is called, and the prop gets the right value (I am checking this using React Debug tools), the button in the parent component 'Pay', it's still disabled.

Maybe someone can notice something I could not. I asked this question on stackoverflow as well, and I did not have much luck. Here is the link if you are interested - https://stackoverflow.com/questions/66132737/react-stripe-js-button-for-pay-always-stays-disabled

I am sorry If I am asking this again, but I have not had much luck.

haughty cape
#

Does anyone want to start a web development business? If so dm

elder nest
#

is there a way to upload images to my website with a custom link like mydomain.xyz/image/dfoksdfljsdflsjf and python code can upload images to the link

#

its flask

left jungle
wicked elbow
# toxic flame Wsgi? Htaccess?

wsgi is setup htaaccess is setup, im getting a python error module not found encodings error so i think its a venv problem, still working on it

wicked elbow
left jungle
#

Ok, thanks

pulsar copper
#

How does Flask handle scripts responses i.e. JavaScript's operations? I'm planning to create several clickable buttons on a webpage I'm building and attach an **event handler **on each of these HTML elements. So when a user clicks on any one of the buttons, the page displays the corresponding result of a specified function output (defined in a Python script)

warm igloo
#

@pulsar copper Well, that's a pretty loaded question. Hopefully you understand that Flask doesn't care about JavaScript at all. They don't talk to each other whatsoever. In your example, the JS you mention runs on the client, makes a call to the server, and there Flask app can respond to the request and return data. It doesn't care or know that it was JS, only that an http/https request was made and it should respond. It is up to you as the Flask dev to decide how to respond. Returning JSON for example.

#

It's very important to understand the client/sever relationship in web apps. I can't tell you how many times I've had to explain this to even seasoned devs.

pulsar copper
#

@warm igloo Speaking of JavaScript, can you pass in an instantiated Python class instance object (or its method, for that matter) to a function definition in JS?

echo hound
#

You can pickle python objects so they can be sent via https as a bytestream. But js won't know what to do with it...

warm igloo
#

Literally all you can pass back and forth is data. So in the pickle example from Busykoala, you can send a string representation of an object, but that doesn't matter. It's just a string.

pulsar copper
echo hound
toxic flame
#

yep

#

Anyone here experienced with socketio on django?

#

The documentation sure is detailed for nodejs ( express ) but like for django there is very few

#

there is certainly a library for it on python but like not too detailed

pulsar copper
elder nest
fathom lynx
#

hello everyone? somebody here had ever used a pwa?

native tide
#

Any online courses plz??

#

For web

ember halo
#

@native tide Freecodecamp and Mozilla

abstract magnet
#

can someone help me with css bootstrap

flint berry
#

Resources for PHP?

wicked elbow
#

looking for honest help setting up an apache server with mod_wsgi for django
ive been trying to get it setup for like 5 days now. im so sick of messing with it and the documentation is absolute trash

frail junco
#

Can anyone suggest good courses or videos for web development for data analysis using python?

twilit needle
dreamy herald
#

I asked this question the other day, but wasn't able to find a solution. Hoping a new set of eyes would help.

I get this error:

I have a django model:


  class PostObjects (models.Manager):
    def get_queryset(self):
      return super().get_queryset().filter(status='1')

  title = models.CharField(max_length=200, unique=True)
  slug = models.SlugField(max_length=200, unique=True)
  author = models.ForeignKey(User, on_delete=models.CASCADE)
  updated_on = models.DateTimeField(auto_now=True)
  content = models.TextField()
  created_on = models.DateTimeField(auto_now_add=True)
  pub_date = models.DateTimeField('date published')
  status = models.IntegerField(choices=PostStatus, default=0)
  objects = models.Manager() #default manager
  postobjects = PostObjects() #custom manager```

I have tried addding, null=True or blank=True on the author Foreignkey, but still get an error.
#

I have also been using makemigration and migrate each time I make changes too.

dreamy herald
#

So it looks like I was able to fix it, by delete all my other migrations and then remaking the migration. What's the downside of what I just did?

tropic mason
#

Hi guys, what linter, static analyser, or anything do you use to avoid errors like this?

qs = MyModel.objects.filter(something='ooo')
qs.pk # qs is a QuerySet not a MyModel instance, and it will raise a runtime error
wicked elbow
toxic flame
#

.filter filters every object

tropic mason
toxic flame
#

In the model

#

Hmmmm

tropic mason
#

i know how to solve the issue, my question is how to avoid it

wet wasp
#

cab I interrupt your talking for one sec I have a very small question ?

tropic mason
#

@wet wasp sure

wet wasp
#

thank you

#

basically I am trying to change the value of <textarea> by using js but each time it change it for one second and then delete it direcly anyone have any idea why is that happening to me?

#
function B() {
            let v = document.getElementById("Binary").value;
            let h=B2T(v);
            document.getElementById("Text").value = h.toString();
        }
        function T() {
            let v = document.getElementById("Text").value;
            let h=T2B(v);
            document.getElementById("Binary").value = h.toString();
                }
#

these are the function that I use them to change the value

#

but it change for less than one sec and goes back empty

toxic flame
#

how r u running the function uwu

#

Via a button? on windows load?

wet wasp
#
 <form method="POST">
        <textarea id="Text" rows="20" cols="100" placeholder="Enter the text"></textarea>
        <br>
        <br>
        <div class="Jan">
            <button class="space" onclick="B()">Binary To Text</button>
            <button class="space" onclick="T()">Text to Binary</button>
            <input class="space" type="reset">
        </div>
        <br>
        <br>
        <textarea id="Binary" rows="20" cols="100" placeholder="Enter the Binary"></textarea>

    </form>
wet wasp
toxic flame
#

Hmmmm i dont see any flaws in it

#

I am on my phone and cant test it directly sry

wet wasp
#

it's fine

#

but it's really weird

tropic mason
#

make sure that you don't have any extra js included that might mess around with you

winged path
#

Hello we are looking for dev to new project "enzy" if you know how to use python in scale 9/10 dm Me for more informations

wet wasp
tropic mason
wet wasp
#

let me send everything

tropic mason
#

add type=button to the button tag

toxic flame
#

Very true

wet wasp
#

@tropic mason man I been trying to solve it for more than an hour

#

thank you a lot

tropic mason
#

yw

wet wasp
#

it worked

tropic mason
#

you might want to check out addEventListener and how to prevent the default behaviour of events

tropic mason
pulsar copper
#

I'm building a Flask-based webpage and I'm having trouble **displaying ** an **image ** when clicking a button on a HTML page.. I've attached an event handler to the HTML button element and then created a function in JS which should display and make the image visible when the button's been clicked.. but nothing shows up 😦

tropic mason
pulsar copper
tropic mason
pulsar copper
tropic mason
pulsar copper
river flower
#

Hey guys do you know any great flask tutorial to guide me through the framework?

#

That is not too long. I want to have a good overview so I can start building and experimenting with things.

glass orchid
#

Hello guys and girls of course 😉

lofty matrix
#

Hey, for the web apps I've made with Django, a lot of times I will have "settings" that I want to configure on the site from an admin page while the site is running. Say, for example, a setting that lets you disable and re-enable user registration. I've handled this by making "singleton models" where I store a single object in a database table, but this seems to go against what databases are designed for. Is there a best practice for handling this type of configuration?

peak pasture
#

Hi which course is good for web development on udemy? angela yu or colt steele?

native tide
#

What do you think about async web-frameworks for python?
Nowadays I'm thinking about to start a new project with fastapi.

#

Django vs Flask?

west wren
#

Using Flask SQLAlchemy and I'm not sure as to the purpose of a ForeignKey with a backref already in place.

Say I have an Author class with the following relationship:

stories = db.relationship("Story", backref="author", lazy=True)

In my Story class, I can then access the author id using mystory.author.id. Is there any point to including a ForeignKey reference to that user in that case (as below)?:

author_id = db.Column(db.Integer, db.ForeignKey(".id"))  # or story.author.id
near pendant
#

can anyone help me with some django issue ?

native tide
#

How can i make a html form that could change a python script?

hybrid bobcat
#

Yo so in vs code I wanna say like if I type a class, and then “.”, it’ll show me all the attributes and methods of the class, what extension is that called? Or what are the vs code extensions that can do that?

#

Oh nvm

#

I found out one of them

#

It’s called Pylance

swift sky
#

so uhh question
i assume flask is utilizing workers
since it's a wsgi server, when it runs locally
i ask because I'm trying to schedule tasks, and it's such a pain
dealing with concurrency issues

native tide
#

im making a d.js bot and are using mongoose

#

everytime i do nr.bal

#

it replies 10 seconds after

#

MongooseError: Operation datas.findOne() buffering timed out after 10000ms

#

this appears in my console^

cold portal
#

So I’m not sure how to even search this. I have a form text area that I’m resizing with the little handle on the bottom right. I can pull that over the submit button and the scroll bar doesn’t change so can’t scroll down on the page. Is that overflow?

toxic flame
#

Or you have some dns problems

native tide
#

e

toxic flame
#

Firebase

native tide
#

Could someone help me with my web server?

barren moth
#

if I was writing an api server, what library would I want to use?

#

this won't be serving webpages at all, but should be scalable

vivid bear
#

@barren moth I think you and I have different ideas about what constitutes scalable

#

I'm working with ARU. We need a reasonable choice for a back-end API server that runs behind an NGINX reverse proxy, which will eventually be configured to round-robin requests between multiple machines. The back-end servers do not necessarily need to communicate with each other

#

Right now our code just extends http.server

#

Projects we're considering, though haven't researched, include Django and Twisted. In the past I've used cherrypy but I'm not sure if I want to use it here

worldly mist
#

Hey. I know this is an ambiguous question, but is it possible, and if so, is anybody interested in, making a search engine with Python?

#

Django in the backend.

toxic flame
#

Wouldnt take more than a day

worldly mist
#

@toxic flame , do you mean me, or somebody else?

toxic flame
#

oh, you.

#

The project

worldly mist
#

Seriously?

twilit needle
#

so earlier I had a django project with a single app but with lots of models.
Now, I have split the single app into multiple apps. But now, I need to make a lot of imports

from django.shortcuts import get_object_or_404
from rest_framework import generics
from rest_framework.pagination import LimitOffsetPagination

from rebox_django.apps.core.views import (PutAsCreateMixin, FlexibleObjectMixin, MultipleFieldMixin)
from rebox_django.apps.core.views import (PutDeleteAPIView, ListBulkDeleteView, EmptyBatchUpdateView)
from .models import (Channel, Category, Box, Upload)
from .permissions import (DeleteUploads, ManageBox, DeleteBox, ManageChannels)
from .permissions import (SendUploads, ReadUploadHistory, AddStars, RemoveStars, ManageUploads, EditUploads)
from .serializers import (ChannelPositionSerializer, CategoryPositionSerializer)
from .serializers import (UploadStarSerializer, UploadSerializer, BoxSerializer, ChannelSerializer, CategorySerializer)
from .serializers import (PartialBoxSerializer, PartialUploadSerializer, PartialChannelSerializer)
from .serializers import (PartialUploadStarSerializer, PartialCategorySerializer)

Is this normal?
Because I split it down, to keep all my abstract classes, I have an app called core

worldly mist
toxic flame
#

Backend yes

worldly mist
toxic flame
#

I usually take so long for the fronted

worldly mist
twilit needle
#

django encourages real Rapid development

worldly mist
#

The backend is what I need help in.

toxic flame
#

Yea ikr

#

Uwu

worldly mist
#

Yeah, I know Django well.

toxic flame
#

What 3rd party site are u gonna use

#

I'm sure youre not gonna scrape the entire web

worldly mist
#

No, I don't want to google it in the backend 🙂

#

No, is it possible to actually scrape the web?

toxic flame
#

Yes but it will cost you several millions of dollars or your pc will burn down the first few days

worldly mist
#

You know, build what these google guys built back in 1998.

toxic flame
#

Sigh

#

There are millions and millions of websites out there

#

Millions and millions of combined char for a domain

#

your pc isnt gonna just take a day to collect every single data

worldly mist
#

Well, how did Google do it back then?

#

And how do they do it now?

toxic flame
#

I dont know ask google

worldly mist
#

Yeah, they have millions of dollars now, but in the 1990s??

toxic flame
#

They do it now by having the user register their website to be listed on google

worldly mist
#

Oh, I see.

#

Is it possible to just build something.

toxic flame
#

If you're doing a search engine just use a third party api uwu

#

It's also good practice to learn how to use apis

#

I have to go cya

worldly mist
#

Sure.

#

Can anybody tell me if it's possible to do a search engine which requires people to sign up their site?

toxic flame
#

Yes of course everything is possible

worldly mist
#

Hey, is it legal to tell my age out here?

worldly mist
toxic flame
#

i dont think freedom of speech is illegal

toxic flame
worldly mist
#

No, but some people make it a crime to give out even your own PI.

#

well, so I'm just 13.

#

Not terribly experienced.

#

Know Python for only around two years.

#

have school.

barren moth
cerulean vapor
#

<@&267629731250176001>

nocturne jetty
#

!pban 736654399392186459

lavish prismBOT
#

:incoming_envelope: :ok_hand: applied ban to @fast kiln permanently.

cerulean vapor
#

@barren moth Starlette / FastAPI are the most cutting edge of those projects in terms of both speed and use of asynchronicity. Django is more for user-facing stuff -- lots of convenient features but not the fastest.

#

Aiohttp is more a base-level toolkit for doing asynchronous I/O

#

also, nothing says this all has to be built on one thing. Django could be used for things that are convenient but not performnce intensive

native root
#

!warn 756281664090538066 That's not something appropriate to say here. Please don't do that again.

lavish prismBOT
#

:incoming_envelope: :ok_hand: applied warning to @toxic flame.

toxic flame
#

oh sorry

barren moth
#

which is why that is being considered

cerulean vapor
barren moth
#

NGINX

cerulean vapor
#

or Nginx, yes

barren moth
cerulean vapor
#

but really, anything that supports WSGI or uWSGI (for async) will work

#

I'd pick at least one of those things I mentioned and try building something with it. Don't succumb to decision paralysis. Just start building stuff with something and see what the experience is like

barren moth
#

so is there a relationship between starlette and fastapi?

#

I heard that fastAPI was built on Starlette

cerulean vapor
#

FastAPI is fully compatible with (and based on) Starlette. So, any additional Starlette code you have, will also work.

#

Starlette is the substrate; FastAPI is built atop Starlette

barren moth
#

so start with starlette if it doesn't work, fastAPI

cerulean vapor
#

Starlette might be a little low-level, but sure

barren moth
#

what do you mean?

cerulean vapor
#

there might not be enough in Starlette to build the things you want without doing that much more heavy lifting. FastAPI may be more convenient

#

that's also why frameworks like Django are useful, they provide a lot of stuff that people often have to roll when making a site: user management, for isntance. But that comes at the cost of it being pretyt topheavy and not the fastest

#

but again, you could use Django for the "convenient but slow" stuff and FastAPI for the, well, fast API stuff

barren moth
#

so use them both in tandem

worldly mist
#

Hello, everybody.
I'm planning to build a search engine with Python in the backend. A real search engine, not the kind which Googles the query in the backend. I understand that it's pretty complex to crawl the whole internet, so I want users to register their site.

If you're interested, and you're good at

  • Django or
  • HTML/CSS/JS (for the frontend, obviously. Especially if you're good at CSS. I'm horrible at design.) or
  • Requests, BeautifulSoup, or Scrapy. Or any packages related to scraping or the internet,
    then DM me @worldly mist .

Thanks.

manic frost
worldly mist
#

I'm not recruiting

#

It's not paid or done by a business or anything like that.

dense zephyr
#

you kinda are

worldly mist
#

But it'll be hard to discuss the project here, so I thought I'll create a seperate channel.

#

If that's wrong, I'm sorry.

manic frost
#

Well, realistically, large-scale indexing is not something to be built with Python.

worldly mist
#

Shall I delete the message?

#

C or C++?

dense zephyr
#

they are very similar

#

cpp is a superset of c

#

so just chose one

manic frost
#

well... no

worldly mist
#

yeah, but I don't really no them well.

#

I know Python.

manic frost
#

C++ is not similar to C anymore, C++ allows quite a bit more abstraction and safety

worldly mist
#

Is it even possible?

manic frost
#

I wouldn't write anything in C. C++ or Rust, I guess.

worldly mist
#

OK.

manic frost
#

I'm not sure what your goal is. If you don't want to pay anyone or make a paid product, why not make the project open-soucre? @worldly mist

manic frost
#

by "anymore" I mean more like since the start of the century

worldly mist
#

So I thought, if they DM me, I can add them.

worldly mist
#

And I don't really want to share the code online.

#

Is that allowed?

#

I'm new to this place, just joined today.

manic frost
#

Why do you not want to share the code?

worldly mist
#

So not terribly good with the rules and regulations.

dense zephyr
#

os > cs

#

4 lyfe dawg

worldly mist
#

Just.

dense zephyr
worldly mist
#

Yeah, you could say that.

#

I have a few friends who are developers, too.

#

And don't want them to get the code and make it their own...

#

Yeah, I don't want to open source it, but I don't exactly want to do it myself.

#

Anybody who's sincerely interested is free to join.

dense zephyr
#

arent there os licenses or something

#

idk

worldly mist
#

There are.

#

But you know, it's just safer to keep it private.

manic frost
#

@worldly mist
A closed-source project that doesn't make any money won't attract much attention. Thousands of open-source projects thrive, and many of their maintainers profit from it.

Thankfully, we don't treat intellectual property like barbarians. If someone steals your code, it's a crime. You don't have to hide it or anything.

The primary way of collaborating on open-source project is a version control platform like GitHub or GitLab. You can start your project there, and share a link to it.

worldly mist
#

so that only the people who are really working on it can get it.

dense zephyr
#

so you are also talking from a security perspective

worldly mist
#

Yeah.

manic frost
#

If someone steals your code, it's just crime. But if you keep your code private and someone steals it, you can't even prove that it's your code.

dense zephyr
#

^

worldly mist
#

So the plan is, start a channel. Anybody who wants to join can. I add them as colabs in my github repo.

manic frost
#

Well, we only allow open-source collaboration because otherwise, we can't see what things you're up to in a private group. That's just a practical limitation.

worldly mist
#

Is it valid if I add all the moderators to the repo and the channel?

manic frost
#

That's just unnecessary burden, and... it's not really closed anymore, is it.

worldly mist
#

What's not really closed?

#

Sorry, I just realized I keep saying channel. I mean server.

#

Surely it's not forbidden to start my own server and invite people to it?

manic frost
#

Just to be clear, we're not going to make our whole moderation team watch over your server. If you want to share your project here, it needs to be open-source. Which is also the only viable way to grow it, as I said.

#

Surely it's not forbidden to start my own server and invite people to it?
No, you can't advertise a server here. For the same reason: we can't moderate every single server you're sharing.

worldly mist
#

Oh.

#

Is there any other allowed way.

manic frost
#

Outside of here, for example on r/Python (on reddit) or some other resource, you could share your project.

worldly mist
#

OK.

#

I'll try putting it on Reddit.

#

Is it OK to advertise a group there?

dense zephyr
#

didnt know there was a python subreddit

#

lol

manic frost
#

For the reasons described above.

#

Now let's finish this extremely off-topic discussion, or move to off-topic if you have any more questions.

dense zephyr
#

mangodb

#

that's the best name

#

ever

eternal blade
#

sorry accidentally sent a message

dense zephyr
#

still best name ever

eternal blade
#

lol, thanks

gray creek
#

Hello, I'm working with Flask at the moment. Anyone know how I can do nested routes? like if I have an account route, how do I specify an account/kits route?

polar nova
#

hell

#

i think you need to do something like thi

#

you can specify your route in app route via seperating by /

quiet ridge
#

Hello I wanna make a project if you are interested to know and join we then please dm me...

polar nova
#

Can you indicate that what is your project about?

silent nexus
#

Hi there!
I am looking for a web developer with knowledge in SQL. I am looking to code a dashboard for my discord bot that uses OAUTH2. I have no idea where to get started and am looking for someone to give me some serious help in getting started.

past cipher
#

esydysy is not being printed, so I know the socket isn't working

blissful eagle
#

Hey there,
I need help in sending html emails from celery tasks in Django.
In my task function, I am not able to get email_template file (.html)

zinc fjord
#

I'd first check if the file you're trying to access is really the file you want to access (log the path and see where it is), then I'd check the file permissions

wanton ridge
#

How can i set a div col-md-5 to the center?

shy willow
#

hey, is anyone here familiar with django-cryptography?

past cipher
#

or if thats bootstrap im sure it has a text-center class to align elements

#

or even use flex justify-content: center

wicked elbow
#

anyone know why viewset.ModelViewSet wont post with a foriegnkey involved? ive tried, both the slug value, and and the primary key, and neither of them work.

glass orchid
#

Hi Guys and Girl, i come here because i've a question (may be esay for you, i hope)

#

In django project, in a view i need to mix informations from several models. for the moment in my view i do : tag_1 = model_name.objects.all() and i do this opération for each table (so three times)

#

but i would like create a new object for extract only few information

#

betwen the 3 table i've table relation by foreignkey

frigid fiber
#

I want add page navigation button I on my django app, but I don't know which keywords should i search for on Google
is there any django expert can give me some advice?

glass orchid
#

Hi Jet

#

in your HTML file juste after your data tou can write :

#

{# Mise en forme de la pagination ici #}
{% if is_paginated %}
<div class="pagination">
{% if page_obj.has_previous %}
<a href="?page={{ page_obj.previous_page_number }}">Précédente</a> —
{% endif %}
Page {{ page_obj.number }} sur {{ page_obj.paginator.num_pages }}
{% if page_obj.has_next %}
— <a href="?page={{ page_obj.next_page_number }}">Suivante</a>
{% endif %}
</div>
{% endif %}

#

and you can replace "Précédente" and "Suivante" by pictures or logo with a special font

#

in your view.py do you use listview from django.views.generic ?

gleaming basin
#

hhu

neat briar
#

Can somebody help me setup Dockerfile for django app?

full frigate
#

Hey guys. I often create tools that uses flask/django to automate some work. I think it could be useful for some people and I want to share it. But I don't know how to manage the project to be user-friendly (I think about case how someone will set this application up, how to deploy it and stuff like that). Do you know any popular tools written in python using flask/django that I can look at github? I know that apache airflow is using flask for example, but I want more to see if there's some pattern

jovial sleet
full frigate
#

I mean that someone that wants to use my tool, could can do this easily, fast and with pleasure 😄 Not exactly user interface. Besides that I want to know how I can share tools like that in a proper way, how big players are doing this - should I create maybe some installing script, or maybe should I use docker for this (I don't have experience with docker yet)

#

simpler question would be - do you know any popular tools written in python that uses flask or django, besides apache airflow? because i have hard time explaining what i really mean, and I want to look at some real-world example

cyan flint
#

might be breaking the rules here, is there a freelancer channel in here?

fallow void
silent nexus
fallow void
silent nexus
fallow void
#

Maybe check simple ORMs like peewee if there is not much data.

silent nexus
buoyant shuttle
#

why is sqlite the default db for django?

#

always wondered

fallow void
buoyant shuttle
#

is it possible to build a Large project, with django + sqlite3

fallow void
#

You can
But DB performance would be bottleneck if you gonna get lot of traffic.
Since sqlite is just a single file DB

granite iris
#

Is there a way to create an application that clicks and interacts with websites, even if those websites do not have API?

#

Or even pull data from these websites instead of just a rudimentary click

fallow void
granite iris
#

Thank you

keen acorn
#

Hey, does anyone know a js library that has "area under the curve" functionality built in? I was looking into NVD3 and it doesnt seem to have it

#

By that I mean like the user can select and drag an area on a graph and it automatically calculates the area under it

granite iris
#

@fallow void Wow it looks like they allow you to use the product commercially as well and grant you all royalties. This is very generous. Thanks again

buoyant shuttle
#

which db is suitable for high traffic,

fallow void
# buoyant shuttle which db is suitable for high traffic,

It depends on how much traffic you are expecting.
But some dbs are made with specific needs.
Like for logs and textual data you can consider elasticsearch.
For data that is very much structured, you can consider relational ones like postgred or mysql.

fresh cape
#

What is the modern equiv of bootstrap. Most of my work has been backend forever. I learned some bootstrap + flask many moons ago for quick/ui web stuff

#

is there a new cool/easy alternative

#

or I must go for css/javascript and sell my soul?

native tide
hybrid bobcat
#

So basically im using this Django template engine for html and I need to load static files so i can use them to style the html and images and js stuff. but like them wont load for some reason i have this static folder in the app folder and then i specified it as STATIC_URL='/app_name/static/' and then in the html file, i did

{% load static %}
....
<link href="{% static 'folder/name.css' %}">
....
<h1 class="text-class">Hello</h1>
....

but then it just doesnt work and no errors are given so idk
oh btw i also did put
django.contrib.staticfiles in the INSTALLED_APPS array

full frigate
#

I'm not sure but try to set STATIC_URL='/static/' and leave the rest as it is and try if it works

hybrid bobcat
full frigate
#

Hmm sorry I don't have a clue what could be wrong, but maybe someone else does

hybrid bobcat
barren moth
#

Thoughts of Sanic vs FastAPI? I've heard about both and that Sanic is async and FastAPI is not.

native tide
#

Besides those two choices, for startups, I still recommend Django. The ecosystem modules are just too good.

barren moth
#

Hi

summer dirge
#

@barren moth
so the way most web frameworks work, they either implement the ASGI (async) protocol or the WSGI (sync) protocol
some frameworks come with their own server, but most allow you to switch out the actual server running the website
the advantage of that is, someone can implement a better more efficient server, and a lot of frameworks can benefit from that. the disadvantage is the small bit of hassle of actually deploying the site.

while you're developing you dont need to worry this at all, most frameworks have a small server built in, just for developing. the built in server should NEVER be used in production tho.

barren moth
#

Ah

#

Why not?

summer dirge
#

the development servers are usually quite insecure, and also inefficient

barren moth
#

Ah

vestal hound
#

Sanic is basically async Flask

#

FastAPI is its own thing

barren moth
#

Yeah, I figured that out

#

Wait

barren moth
vestal hound
#

in the case where generating the response is "fast" and doesn't have to wait for external entities "much"

#

a sync web framework is fine

#

Django is sync too

#

although the limitations of WSGI are becoming more and more obvious in today's world, I guess

barren moth
#

Yeah

vestal hound
#

nevertheless

barren moth
#

Why would you ever want to build sync now

vestal hound
#

it's still perfectly possible

vestal hound
barren moth
#

How is async more complex?

#

Don't you just use async and await keyword

#

... Should I go back to reading 101 guides lol

vestal hound
#

quick example

#

when you await, you don't know what code will execute next

barren moth
#

Because you don't know if it'll run that function or a different function?

vestal hound
#

something like that?

#

you know how the event loop works, right

#

what happens after you give up control

#

depends on what tasks are currently queued

barren moth
#

Possibly but I don't have a thing attached to that name

vestal hound
#

i.e. nondeterministic

barren moth
#

Aka idk what an event loop is

#

But i probably do just not know its name

vestal hound
#

it's a common implementation of async

#

so basically

#

you have a "backlog" of tasks that are running

#

when the one with priority awaits

#

it pauses

#

and the next one starts running

#

until it awaits

#

then the next one, and so on

#

the machinery that handles all this is called the event loop

barren moth
#

So only one thing in async is actually running at a time?

vestal hound
#

yes?

#

what is your understanding of async

#

it's concurrency, not parallelism

barren moth
#

Okay, I get it now

#

Just switching between what's running a lot

#

While awaiting something it can do other stuff

#

Which is why you have to use the async sleep if you want to pause, otherwise it pauses the entire script

vestal hound
#

yes

barren moth
vestal hound
#

few reasons

#

one, if you have shared mutable state

barren moth
vestal hound
#

it becomes harder to understand when that shared mutable state is changing

#

simple solution: have no shared mutable state

barren moth
#

What is a shared state?

vestal hound
#

say you have a global variable

#

all coroutines have access to that global variable

#

they can be said to "share" it

barren moth
#

Oh

#

And they want to edit it

#

It's not a constant

#

Then yay! Race conditions or w/e

vestal hound
#

because you choose when to give up control

#

but, yeah

barren moth
#

Okay, I think I get as much as I'll get without messing around

native tide
#

The problem with async = not much adoption yet on Python

#

If you want rock solid, you go with something like Pyramid.

#

Like - how much benefit does async really give you at a cost of confusing your juniors?

toxic flame
#

So paypal payments on notify actually returns the inovice id

#

gonna Integrate stripe now

#

uwu

#

then coinpayments

#

owo

#

so kewl i love coding

wicked elbow
#

anyone know how to return a different serializer then the posted serializer with basic integration of viewsets.ModelViewSet? i have to post with id to set the foreign key, but need it to return the username associated in that foreignkey not the id

native tide
#

lets say you have two models, Subscribers and Newsletters linked via a third table SubscriberNewsletters. If you've defined the relationships, you can go [x.newsletter.name for xin subscriber.newsletters.all()]

#

kind of vibe

tribal spade
#

Flask beginner here! I assume when I deploy my Flask app, it's gonna exist on a server computer (running Linux?) somewhere out there, and so when it "deploys," we have that computer run flask run to set up the app? Do I have that right?

small crest
native tide
maiden tulip
native tide
#

is_production = os.getenv("ENVIRONMENT","").lower() == "production"

#

That's saved me years of my life 🙂

tribal spade
#

Thank you Rod[]!

#

And Timo

maiden tulip
barren moth
#

DYNO?

maiden tulip
#

heroku uses dyno as an environment

#

I could perhaps also try to use another getenv but the SO-post suggested the use of DYNO and it works for me @barren moth

native tide
forest pumice
#

Hey I'm having trouble with Flask if anyone can help. I am trying to retrieve database model objects from the flask session for a cart system

#

I get Object of type Keyboard is not JSON serializable when passing my list of cart dicts to render_template

native tide
#

on ASP.net core MVC with identity framework, I'm getting this thing that says and I can't find the html to remove it anywhere in my project. There are no external authentication services configured. See this article for details on setting up this ASP.NET application to support logging in via external services.

native tide
forest pumice
#

Adding to the cart handled in the item route

#

and manipulating the cart session is in helper.py

native tide
#

You need to provide a serialization method for Keyboard class or use something like this

#

for row in resultproxy: row_as_dict = dict(row)

#

row2dict = lambda r: {c.name: str(getattr(r, c.name)) for c in r.__table__.columns}

forest pumice
#

It's commented but I remade the same data structure but this time I re-query the item instead of using the one that was stored in the session dict

#

Passing this seems to work fine, this is where my confusion is

native tide
#

Because entries is a dict already. Keyboard ORM class is not JSON serializable, so if you want to JSON serialize it, you can do something like this.. let me submit a quick PR to show you..

forest pumice
#

But even doing entries[x] = {"item": session["cart"][x]["item"], "quantity": session["cart"][x]["quantity"]} breaks

#

My goal was to have a simple system where I could just pass session["cart"].values() to the template rather than re-querying every time cart is viewed

native tide
forest pumice
#

Oh interesting

native tide
#

That code does look very hacky though. I would turn the session into a dataclass.

forest pumice
#

Oh yeah what I had commented in cart was awful

#

Because I was trying to understand what I was missing

#

So like, why in the inventory route, can I pass a query result directly?

native tide
#

Well, you can pass the query to the renderer, but somewhere along the line, you are trying to JSON encode it

forest pumice
#

Okay I committed a working version

#

If I actually put the item obj into the dict in place of the dummy x, it throws the error on trying to add to cart

wicked elbow
#
class PostUpload(viewsets.ModelViewSet):
    permission_classes = [
        permissions.IsAuthenticated
    ]
    serializer_class = PostsUploadSerializer

    queryset = Posts.objects.all()
    queryset = queryset.filter(soft_delete=False)

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(PostsSerializer(serializer.data, context=self.get_serializer()).data, status=status.HTTP_201_CREATED, headers=headers)
  File "C:\Users\kenda\.virtualenvs\safespace--lAQnTUa\lib\site-packages\rest_framework\relations.py", line 467, in to_representation
    return getattr(obj, self.slug_field)
AttributeError: 'int' object has no attribute 'username'
``` anyone know whats wrong?
#

trying to create with pk for the foreign key, then converting to the response i need for display. 'int' object refers to the pk, and username is the field it should display. for more information

native tide
trim timber
#

I'm not really sure if this goes under web development but can somebody help me web scrape a number off of a website? I am very confused.

full frigate
#

Give us some details

trim timber
#

I want a way to extract the number 16. I was told that the number is probably loaded dynamically using javascript. I was told that I should use Selenium to extract it, but is there any kind of way to do it using BeautifulSoup or something else?

full frigate
trim timber
#

Okay, thanks. I will check it out

mossy sinew
#

why i cant donlowd flask ??

full frigate
#

You can get the one you are interested with and then use requests.get(url), in response you will have json with all data that you need

mossy sinew
#

can somebody help me pls ??

trim timber
#

@full frigate Oh, that's nice. I know this might be a lot to ask for but could you perhaps show me the code it would require to get the number 16 from the picture I sent. I am a beginner so I doubt that I will be able to figure it out on my own.

full frigate
#
import requests

response = requests.get("https://one-versus-one.com/get-stats-data?first_player_id=834&second_player_id=1548&type=statistics")
data = response.json()

now data is a dict with all information that you need, now you can access it

#

and now you need to access that data you need so:

goals_1st_player = data['ranking']['firstPlayer'][0]['bar-value']

Didn't check if it works but it should

#

To make your work easier - take that "data" and paste it into some online json formatter. Find where is data you need in this structure and then use python to access it

trim timber
#

Damn, thank you so much man 🙂

full frigate
#

You're welcome 🙂

full frigate
mossy sinew
full frigate
#

Looks like you have issues communicating with PyPI. Try this solution:

pip install flask --trusted-host pypi.org --trusted-host files.pythonhosted.org

type this command in terminal

wicked elbow
#

anyone decent in django, i have a really tough question, been searching for an answer, tried a bunch of different things to no avail

#

i need a different response on post to a foreign key. the response is the pk, but i need the rest of the fields, not the pk to be returned. It has to be posted with the PK to the foreign key or it wont post at all. and yes, ive even swapped it to a separate class, still cant get it to work and passing the serializer.save through the other serializer and its not working either.

#

another note, its form data thats passed, so my the normal method of swapping of post doesnt work. so im scratching my head at what to do

wicked elbow
#

i found a work around for now, but seem incredibly stupid to have to re query the db for the response data after a post to get the data i need, but it is what it is i guess

turbid estuary
#
@api.route('/users/<int:id>/timeline/')
def get_user_followed_posts(id):

in this view function, I have a line in code which generate a url
prev = url_for('api.get_user_followed_posts', id=id, page=page-1)
, so here comparing with the "route",
users = api.get_user_followed_posts
<int:id> = id
timeline = page=page-1
☝️ is this all correct?

shy willow
#

hi, is it possible to make a django api invisible for users in a browser?

#

and only be accessed by the front-end?

#

so basically I would be filtering requests from the front end only

#

is that possible?

fallow void
shy willow
#

no

#

I was actually about to try to learn about token authentication, but I thought maybe there is a simpler way

fallow void
#

One way is CORS Access Control Allow Origin

shy willow
#

actually, I had that setup

#

I needed to implement it, since the frontend coudnt access the api

#

but I don't know much about it

grizzled sand
#

Hey everyone, how can I do next/previous post on detail_view page? (django). Cant find info about that, *link on some doc. will be fine for me. *

fallow void
#

You can use same to whitelist your front end

shy willow
#

hmm one sec

fallow void
#

Check if this helps

shy willow
fallow void
#

Server sets it in the response headers

shy willow
#

actually, I just noticed I have CORS_ORIGIN_ALLOW_ALL = True in the django setttings.py

#

is that what's causing it?

fallow void
#

That's it.
But AFAIK modern browsers honors these headers
But if you have sensitive data, you should also have authentication

shy willow
#

I removed the CORS_ORIGIN_ALLOW_ALL = True and added a CORS_ALLOWED_ORIGINS list, but it still allows me to visit the endpoint on my browser

fallow void
#

I am no expert on django
But by chance, are you using DRF or some other app?

full frigate
#

Does CORS access control allow origin makes those requests made by frontend invisible? Or does it just disable to send request to backend from "other" hosts?

shy willow
#

what's DRF?:D

#

ah yes

#

django rest framework, that's what I'm using

fallow void
#

Maybe it has different way to it
I am not very confident

misty goblet
#

Hello, I am trying to setup my api (made using django rest framework) so that you can authenticate in two different ways: tokens for another program to interface with it and a session auth for other client browsers. Any ideas for the best way to go about that?

random lava
#

Hi, ive got a problem.
im trying to use a list from python in a js script.
python code:

test=["Zonos", "Reaio"]
return render_template("dashboard.html", test=test)

Html Code:

<p id = "test">test</p>

JS code:

<script>
    var test = "{{test}}";
    document.getElementById("test").textContent=test;
</script>

output:

&#34;Zonos&#34;, &#34;ReAio&#34;

Any clue why it has all these weird characters ?

native tide
#

Since when did we get a Web Dev channel

#

Anyone here /bottle/?

native tide
native tide
misty goblet
#

No one should be able to use both

misty goblet
#

ie every client will either use one or the other

#

so there isn't really a preferred one

native tide
misty goblet
#

in that case does it matter which is first

native tide
#

so in that case all of your clients will be authenticated at least one way

misty goblet
#

I see

#

Would it make much of a difference performance wise if I was to rewrite that or would it not really matter?

native tide
#

e.g. have a custom middleware?

misty goblet
#

yeah

native tide
#

i wouldn't see it making a big performance change

#

you could even just modify an existing middleware, such as token auth

misty goblet
#

that's nice, I was originally planning on making a custom auth class that determined how a client was authenticating.

#

I have to write a custom token auth anyway

native tide
#

cool, let me know how it goes, i've been wanting to write some sort of custom middleware soon too just to learn about it

#

also how exactly does session auth work with a seperate frontend, e.g. react? I have never got my head around it

mystic grove
#

from flask import Flask, render_template
app = Flask(name, template_folder='../templates')

@app.route("/")
@app.route("/home")
def home():
return render_template('home.html')

@app.route("/about")
def about():
return "<h1>About Page</h1>"

if name == 'main':
app.run(debug=True)

#

getting jinja2except templatenotfound

#

anyone can help?

native tide
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.

native tide
#

^ btw

mystic grove
#

yes

#
app = Flask(__name__)

@app.route("/")
@app.route("/home")
def home():
    return render_template('home.html')

@app.route("/about")
def about():
    return "<h1>About Page</h1>"



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

I even tried this

native tide
#

btw you have an empty app route:
@app.route("/")

#

you should remove that

mystic grove
#

I think that is not the issue

mystic grove
native tide
#

take a screenshot of your files/folders

#

also is this error when you visit /home?

mystic grove
mystic grove
grizzled sand
#

How is works python post.get_next_by_created.get_absolute_url in django, i'm getting nothing on detail view all time.

native tide
# mystic grove i am getting it anyhow

that looks right to me, with the templates in the root folder.

strange. I'm not too familiar with flask but what I'd do is remove the empty app route and re-create the templates folder as thats the default that flask looks for. sorry that i cannot help further with that - not too experienced w/ it

marsh kite
#

I have a problem with spotipy

#

Is it possible in any way to authenticate using user's login and password?

native tide
#

Yo

#

Anyone here use Bottle?

#

Also why the hell is bottle so slow

#

like absurdly slow

turbid estuary
native tide
#

@turbid estuary don't spam for help in every channel dude

turbid estuary
#

where else would I go for web-dev query

native tide
#

you just wait for someone to help you

turbid estuary
#

on was general channel, and one is web-dev

native tide
#

Also just ask your question

turbid estuary
turbid estuary
native tide
#

what's your question?

toxic flame
#

That's not actually a specific question

#

If someone does say yes then you'd ask him the question

native tide
polar nova
#

have anyone deployed django code to google cloud ever?

haughty cape
#

can some here help me

potent plover
#

Help, I have a problem with submitting the textarea of a Captcha in Python selenium. Thanks for you time. Here is the Stackoverlowlink for more information: https://stackoverflow.com/questions/66188276/cant-submit-captcha-textfield-python-selenium

native tide
#
app = Flask(__name__)

@app.route('/')
def my_form():
    return render_template('index.html')

@app.route('/', methods=['POST'])
def my_form_post():
    text = request.form['text']

    processed_text = text.upper()
    #return processed_text
    return redirect(url_for('returnit'))
@app.route('/saved_text')
def returnit():
    return processed_text

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

this returns NameError: name 'processed_text' is not defined

#

can anyone help

potent plover
#

Help, I have a problem with submitting the textarea of a Captcha in Python selenium. Thanks for you time. Here is the Stackoverlowlink for more information: https://stackoverflow.com/questions/66188276/cant-submit-captcha-textfield-python-selenium

native tide
#

-_-

long zinc
#

Would anyone be able to help me with a flask_pymongo / jinja2 issue I'm having? I'm able to iterate over multiple MongoDB records, but a single record doesn't show in the template

#

'''
@app.route('/users/<username>')
def user_profile(username):
users = mongo.db.users.find_one_or_404({'username': username})
return render_template("user.html", users=users)

@app.route('/users/')
def get_users():
users = mongo.db.users.find({})
return render_template("user.html", users=users)'''

#

user.html template

'''{% extends "base.html" %}

{% block body %}

{% for x in users %}
<tr>
<td>{{ x['username'] }}</td>
</tr>
{% endfor %}

{% endblock %}'''

native tide
long zinc
#

It works if I take out the for loop

native tide
#

im pretty sure

native tide
#

like this @native tide

#

ah I see

muted stump
#

hey my css files are not working

nova nacelle
muted stump
nova nacelle
#

I'm on a mobile rn, but did you defined the path correctly?

#

@muted stump

muted stump
#
{% load static %}
<html lang="en">
<head>
    <link rel="stylesheet" type="text/css" href="{% static 'main.css' %}">
    <title>{{ title }}</title>
</head>```
#

this is the code

nova nacelle
#

Does it load the same old css?

muted stump
muted stump
nova nacelle
#

@muted stump Use Ctrl+f5 to refresh the page

#

It's probably the browsers cache

muted stump
#

oh ok

#

nope not working

nova nacelle
#

Did you define it in urls?

muted stump
muted stump
nova nacelle
#

The path right there

muted stump
#

oh

#

path('', views.home, name="main-home"),

#

what to add into this

toxic flame
#

Show me your settings

#

specially the last bottom few line

#

S

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

STATIC_URL = '/static/'
#

@toxic flame here

nova nacelle
#

Ill check in, if on my pc sometime later

toxic flame
#

Yea

#

You are missing one line

#

Paste this line

muted stump
#

@toxic flame which line??

toxic flame
#
STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ]```
#

And you have to move your static directory outside of home

#

Move your static folder to the location where manage.py is located.

toxic flame
nova nacelle
#

also the urls

toxic flame
#

no

nova nacelle
#

The +static thing?

toxic flame
#

that's usually for media

#

But if you dont know how to setup static on deployment, then sure.

nova nacelle
#

Should always have em done together

glass orchid
#

Hi Every body i face to an issue in django project when i pass an argument more than 9 to my url, it's don't working i have an error NoReverse Match Found

distant trout
#

is there anyway I can load in an embed iframe without letting it use the current cookies for that site that is current stored?
right now i have an embed on my site that is able to access the login session of that i am already logged in with on the main site
but i dont want it to have access to those cookies

glass orchid
#

re_path(r'^edit_planification/(?P<pk>\d)$', views.PlanificationUpdate, name='edit_planification'),

#

when pk is more than 9 it's KO and manually i've the same probleme

#

so if i POST url http:// ...... /edit_planification/1 (to 9) it's ok

muted stump
#

@toxic flame it works thx

glass orchid
#

and when i POST url http:// ..... /edit_planification/10 (or more) it's KO

#

someone had and idea ?

verbal canopy
#

Hello, i have this ```py
users = ['d']
@app.route("/")
def home():
with open("index.html", "a") as file:
for a in users:
file.write(f"<h1>{a}</h1>" + "\n")
file.close()

with open("index.html", "r") as f:
    x = f.read()
return x
#

I want it to be displayed as is the squarre in the middle of the site

#

can anyone help me?

toxic flame
#

owo

random lava
#

Hi, got a problem.
I have a list that i converted to json but cant get the first value.

<script>
    var bot_names = "{{ bot_names_filtered | safe }}";
    //^ should equal ["zonos", "reaio"]

    document.getElementById("test").textContent=bot_names[0];
</script>

Output = [

toxic flame
#

Maybe don't put it inside ""

#

Since it's [ which is hypothetically the first index of a string

random lava
#

even if i did [2] it just does the first character of the string

toxic flame
#

Have you tried taking it out of the "?

#
var cars = ["Saab""Volvo""BMW"];
#

This is how an array in js is

#

No ""

random lava
#

do they not ?

toxic flame
#

What

#

Here

rustic pebble
#

@random lava That is not correct

#

You should have this:

let bot_names = {{bot_names_filtered}}

Because when you use {{}} inside "" the value gets rendered as a string, its basically the same as str(bot_names_filtered) or bot_names_filtered.toString()

#

Or another option you have is this:

let bot_names = JSON.parse("{{ bot_names_filtered | safe }}")
#

This one is what I like more ^^

#

@toxic flame This is the correct approach

toxic flame
#

yea i said remove the "

toxic flame
#

Works as well

#

But if you're trying to turn it into json format

rustic pebble
#

No

#

JSON.parse deserialises the list

toxic flame
#

Actually, json.parse working with an array may produce an error, not sure.

muted stump
#

hey ah i am gonna need to make a db that can be accessed outside my website so should i use ORM

#

or use a proper db like postgres

muted stump
#

hey can anyone help me out. i need to make a custom system for my django website

#

custom user forms, no ORM and i should be able to access the db from outside of the website

native tide
#

An ORM is just a translation layer, even if you use the ORM in Django (which you should), you can still directly access the database via the Python Postgres or MySQL client depending on your setup. @muted stump

#

Django < translation layer > ORM < connection > Database < connection > Other Python Programs

tardy heron
#

Hello. How to do a progress-bar for the client on server-side unzipping of images from uploaded archives? #help-mango

native tide
#

@muted stump The better pattern is to create a REST API so that the applications that need to modify the database write via the Django models. If you need to just read the data, straight out of databases works.

muted stump
#

hey how can i get data from user to my django things

toxic flame
#

Wot

shy willow
#

how come the auth token doesn't change in django?
as I understand, every time a new request has been made, a new token is generated, or have I mistaken something?

muted stump
#

how to use sessions in django