#web-development

2 messages · Page 17 of 1

modern acorn
#

I have a Windows server

rigid turtle
#

RIP

#

Run Docker for Windows

#

Easy to setup

#

Then you can just put your code in a nginix container I think

modern acorn
#

shit's getting complicated just to deploy a damn app loll

candid basalt
#

Deploying apps the right way was never easy. =]

modern acorn
#

Fairly easy with just javascript and php

rigid turtle
#

10 years ago this would require a team

#

It's easy to forget just how complicated this all is "under the hood"

modern acorn
#

If I only had the interest to learn it, but I just need to deploy this app and i'm not going to touch python in a long time

#

the size of the project doesn't even need python but its the only language i knew a little bit from

#

there's only like 30 lines of code lol

candid basalt
#

You have options to either do it quick and easy with all the implicaions or do it properly. Just pick the one you see fit.

modern acorn
#

Like genuinely it’s just one front page with a html table

#

That will be accessed and viewed by some employees

#

But they wont change anything from the web

upbeat forge
#

Do you know any Software, where client can easily change website text and pictures and is easy to use, because my client want to be able to change pictures and text. Or do I have to create one...

candid basalt
#

Just about any CMS out there.

#

You can start with wordpress and move on to others if you don't like it.

#

They are billions. (c)

gritty halo
#

Hey im pretty new to django and kinda confused on where the main bulk of code would go

#

also wondering where/what file i would put code for a user that sends a request

meager anchor
#

Did you check out the tutorial?

#

If you use the manage.py commands it will usually give a good structure

gritty halo
meager anchor
#

Yes

gritty halo
meager anchor
#

python manage.py startapp

candid basalt
gritty halo
#

@meager anchor ahh i see

#

thx

#

Any reason when i create my new app in django the files are red? and not the normal grey

candid basalt
#

Which IDE do you use?

gritty halo
#

pycharm

candid basalt
#

It might mean they are not staged for commit if you are using Git or some other VCS.

gritty halo
#

im using git

#

to get rid of it would i just commit the changes

candid basalt
#

Well you can stage them for commit by selecting and pressing ctrl+alt+a, if I'm not mistaken.

gritty halo
#

yup used command line, pushing them made them normal again thx

candid basalt
#

👍

rough magnet
#

hey guys quick question

#

is there way to host a flask website for free?

#

i only want to host it for a school project

candid basalt
#

I think I saw something from Google in that regard.

#

But it requires Have an upgraded billing account. An upgraded account is ready to be charged for use, as opposed to a free trial only account. which may not work for you.

#

I used their services for a while - they are rather good.

modern acorn
#

so ive tried to make my website public

#

by setting the ip to 0.0.0.0 but even then its not reachable

#

even using xampp and apache, i can only access the site locally on the machine

#

is windows preventing it from hosting on the public ip or something?

rigid turtle
#

Did you allow it though windows firewall?

#

It blocks all inbound connections by default

modern acorn
#

yeah i figured it out thanks

#

i can access it locally within the same network now

#

but not publicly though

rigid turtle
#

That's probably your home router's firewall

#

You'll have to configure it to forward the port

#

Check the documentation for your router, it should have instructions on how to do so

queen fiber
#

Hey guys how do I get around this "blocked by CORS policy"
I have a client who wants to have a site load data from a xml file with javascript. I'm trying to do that but it seems javascript can't access local files.

whole goblet
#

how come this doesnt work <a class="btn btn-primary" href="{{count_url}}" alt="See details" role="button">Link</a>

"Not found: '/href='"

candid basalt
#

!t ask

lavish prismBOT
#
ask

Asking good questions will yield a much higher chance of a quick response:

• Don't ask to ask your question, just go ahead and tell us your problem.
• Try to solve the problem on your own first, we're not going to write code for you.
• Show us the code you've tried and any errors or unexpected results it's giving
• Keep your patience while we're helping you.

You can find a much more detailed explanation on our website.

candid basalt
#

What framework is it, what templating engine is it?

#

Where is the error displayed, i.e. what outputs it?

rare oar
#

hey guys some advice as I'm new to Django

#

I have a site that displays lists of matches. These matches have an optional 'Tournament' that they can have a relationship with. On my django view I want to be able to filter the matches by the tournaments. I made a Django form that does a get and returns the Tournaments in there. However I'm pretty new so I am having trouble with a couple of things

#
1) How to set a default value for the form. I'm doing this in the view right now if form.is_valid() returns False, but it means I get an error message on the page on first load. Basically it just returns the very first object.

2) How to add a 'None' type of filter (since the relation is not required). is this something I append to choices? 
wary mantle
#

What's some of the best looking and simple CSS frameworks out there?

grand badge
#

bootstrap

candid basalt
#

And it's numerous derivatives.

wary mantle
#

Any alternatives?

dawn void
#

@wary mantle I'm currently using Bulma, entirely css with only a couple more advanced things requiring js/jquery depending on if you are using something like react/vue/etc

covert radish
#

can a django wizard tell me the difference between those two? thanks!

minor anchor
#

Seems like assertNotEqual is a method, and assertNotEquals is a function?

covert radish
#

just warped there with my wheel click (goddamnt i love pycharm)

fluid horizon
#

they are the same, assertNotEquals is deprecated

#

not really django-related though, they're related to unittest

covert radish
#

thank you

native tide
#

and by that I mean what do I put in

{% url '' %}
ripe pecan
#

I've been using pytest instead of unittest and I like it @covert radish

#

@rare oar In your model, do you have blank=True for that field?

#

@whole goblet how are you constructing count_url in your view?

rare oar
#

Hi I fixed it. I decided to change to a model choice field

ripe pecan
#

Nice, and you fixed (1) as well?

rare oar
#

Actually I should say that I got advised to change

#

Yeah all good.

ripe pecan
#

Awesome!

gritty halo
#
    if request.method == 'POST':
        print('Raw Data: "%s"' % request.raw_post_data)
    return HttpResponse("Ok")```
#

is this correct? Im getting a 403 error and idk if its this or my code elsewhere

gritty halo
#

nvrmind think i got it

wraith trench
#

In my django app I'm using JSONField, and for some values when trying to save them as json value I get "Unicode low surrogate must follow a high surrogate.", is it possible that I have to first convert that value, to something else?

gritty halo
#

Forbidden (CSRF cookie not set.) Is this a client issue?

candid basalt
#

It depends. Most probably you forgot to add {% csrf_token %} to your form template.

gritty halo
#

would i need a form template since im only using django as a server and not for browsing?

dawn void
#

you will either have to disable csrf or something else that escapes me at this time

gritty halo
#

ive thought about that but doesn't csrf make it ur server secure or is there other ways I can ensure security from a client to server

little crown
#

Hello,
I need help with blocking Pop Ups from an IFRAME using JavaScript...
If an iframe has a target link that pops up I want to be able to block that...
I know there is sandbox attribute in html but the page i iframe happen to have a sandbox detector... I would be really thankful if anyone has an idea for blocking out these unwanted pop ups

calm solar
#

anyone know why gunicorn -w 4 -b 127.0.0.1 hello:app returns "No module named flask" where sudo python3 hello.py works just fine?

#

both flask and gunicorn are installed inside the vertual

timid arrow
#

could be a circular import

#

there are only 2 reasons for import error:

  1. circular import
  2. thing is not in the python path
calm solar
#

yea i got it. multiple copies inside and outside of the vert

#

its now running but can't hit it from web browser.

native tide
#

in Django is there a way to have links on words in the TextField? I know about urlize which makes http... links clickable but I want to make some text within the field as a clickable link.

ripe pecan
#

@gritty halo if you're using a Django form, then there's an option to disable csrf for that particular form. But if not, I'm not too sure

#

@native tide can you do that with a raw text field without getting Django involved? If so, you can most likely do it with Django

calm solar
#

i followed this tutorial to a T and everything worked as it was supposed to except for the very end. When I go to the IP address, it just shows me the NginX default page.

#

Anyone have any thoughts on what I'm missing?

meager anchor
#

are you accessing the site that you set up in nginx?

#

did you put the vhost in /etc/nginx/sites-enabled?

#

did you reload nginx?

#

if nginx can't find any matching vhost, it will dispatch to the default page, or if you don't have any set, it will pick any

calm solar
#

yes yes and yes.

#

im definitely new to python/flask but come from a lamp background. so im sure i'm just missing something easy

meager anchor
#

what helps me most with figuring out nginx issues is debug logging

#

in your error_log directive, probably in /etc/nginx/nginx.conf, add debug to the end of the line (before the ;)

#

validate it just to be sure, then reload

#

issue your request again, but run a tail on the nginx error log somewhere

#

it should tell you what decisions it's taking to dispatch

calm solar
#

let me give that a whirl. i'm new to python/flask/nginx (come from a lamp stack bg) so most of this is over my head.

#

so error_log /var/log/nginx/error.log; to error_log /var/log/nginx/error.log debug;?

meager anchor
#

Yeah

gritty halo
#
def postRequest(request):
    if request.method == 'POST':
        print(request.POST)
    return HttpResponse("Ok")``` fixed it typo...
ripe pecan
#

You mean @csrf_exempt?

calm solar
#

is sudo systemctl restart myproject the propery way to make updates to a website?

strange thorn
#

that is the proper way to restart a systemd service

calm solar
#

and say i just want to change some html how what is the proepry way to get it to reload there?

strange thorn
#

that entirely depends on how you are running it

calm solar
#

nginx,uwsgi,flask

mossy anchor
#

anyone has any experience in deploying a rest api behind a google load balancer? i keep getting random 502 errors that shuts my service down

mossy anchor
meager anchor
#

@calm solar you copy the html files to where uwsgi reads them - that should be enough

ripe pecan
#

@meager anchor Not necessarily, might have to restart the server

#

Sorry, I'm specifcally referring to non-html files, mb

#

@calm solar To restart uwsgi type: sudo service uwsgi restart

meager anchor
#

that only works if you have a init script or systemd service with the compat thing iirc

calm solar
#

thanks @meager anchor i'll take a look at those docs this morning

modern vale
#

Hey guys. Let's say I have an article model, how can I make it so that articles have some sort of publishing mechanism?

#

Meaning. An article can be create, but not made publicly available. Or a publicly available one can be unpublished?

kind steppe
#

Maybe add a visible field to your article model?

#

That way you could set it to false and it wouldn't display live (check if visible is false before sending results to client) or set it to true and have it be shown

modern vale
#

I've been looking for maybe an article or something to explain it a bit better...

#

Is the visible field a type of field, sorta like a slugfield? Cuz it is I can't find it on the docu :/

kind steppe
#

you'd have to create it as a new field in your model, set it to be a Boolean (True or False)

modern vale
#

(Thanks for your help btw, very much appreciated)

#

Simple enough...and then use signals to trigger it?

#

I feel like this is one of those things where I'm going to feel extremely dumb for not being able to figure it out

kind steppe
#

I don't really know what you mean by "signals" I'm afraid

modern vale
#

Pretty useful imo, check it out when you have a chance

kind steppe
#

ah right, not too familiar with django so I'll look now

#

Right, so you could use this but it'd be a lot easier to filter this from when you get articles from your DB

#

Give me a minute to get my laptop

modern vale
#

Thank you so much Joseph, I really appreciate your help!

kind steppe
#

ok so

#

in your article model

#

you need a field with the type models.BooleanField(default=False)

#

call it visible or published or whatever

modern vale
#

Understood, that's what I was thinking too...Go on. Thanks again

kind steppe
#

that default basically means that if you create an instance of the model and you don't specify published then it will be that value

#

next up

modern vale
#

Right

#

So then, it'd be a matter of being able to change published or unpublished with a button on the admin interface and then using the view to filter the articles based on that field?

kind steppe
#

indeed

#

I think you can use the .filter() method for that

modern vale
#

So now my thing becomes...I don't want it to be, a drop down? You know. I'd like it to have two buttons Save and Publish

#

In the view you mean?

kind steppe
#
published_articles = Article.objects.filter(published=True)
modern vale
#

Ahhhhhhhhh

#

starts to feel like an idiot

#

That makes sense

kind steppe
#

Haha, no worries

#

And as for the publish and save

#

that would also be easy

#

since you can have one route which saves the article (sets published to False) and one route which publishes the article (sets published to True)

#

I don't have the most Django knowledge but I'm sure that there is a simple enough way to achieve that

modern vale
#

Sorry to cut you off, but do you mean URLroute/path?

#

As in, make one view to publish article and one to save it?

#

(I understand, but this is still very helpful. Thank you)

kind steppe
#

You could do it that way, or I think that you could also use one route and check the contents of the form

#

Just give me a minute to check something

modern vale
#

No worries, please take your time

kind steppe
#

Okay yeah, as I thought there is a way to do this with HTML forms

#

So

#

If I have the following

    <form method="POST">
        <input name="username" type="text"/>
        <input name="submit1" value="submit1" type="submit"/>
        <input name="submit2" value="submit2" type="submit"/>
    </form>
#

Actually, are you using Django to generate your article submission forms?

modern vale
#

JFC...I think I just thought of something

#

Give the form two buttons. Save and Publish.

kind steppe
#

yep

modern vale
#

And then do something like

#

if the user wrote this article but its not published, display to them anyways

#

Maybe?

kind steppe
#

yep

#

but with this approach

#

when you submit this form

#

your browser sends this data

username=Joseph&submit2=submit2
#

now as you can probably guess submit2 means that I submitted the second button

#

If you check whether the save button or the publish button was clicked you can decided whether to set published on the Article to True or False

modern vale
#

At the article submission view

#

AND THEN IN THE EDIT VIEW, JUST DO THE SAME THING

#

JFC, you're a genius

#

Not sure why none of this occurred to me before

kind steppe
#

Haha

#

Feel free to ask if you have any problems implementing this

modern vale
#

Thank you so much!

kind steppe
#

No problem

modern vale
#

Another quick thing to bounce off of you...so, you think this approach will require another view in which the user sees all the articles they've written/published?

#

I think so but I'm not sure. I could just do a ListView and sort by author, which is a field in my model

kind steppe
#

Yeah that sounds reasonable

#

Have a page like that which then displays the title of the article, some metadata (date of publishing, tags whatever) and then a link to the edit page

modern vale
#

So

#

In the admin page, when you click on an individual article. How is it that we add the publish action to this?

#

Is it based of another view or form? Trying to find info but can't seem to make it work

modern vale
#

Hey Joseph

#

So, I seem to mostly have it working. Only thing I'm a bit confused about is. How do I add a custom button/action (the publish button) on the admin interface?

#

No admin actions that work on the changelist but per object

ripe pecan
#

Have you read the Django book?

modern vale
#

The documentation? Of course.

#

But what I don't understand is. I wann add a custom action button (for each article in the admin panel, not the changelist)

ripe pecan
#

I haven't really read your question, so this might not help, but here it is anyway

#

Try taking a look through that?

modern vale
#

@ripe pecan , this answers part of my question so thank you!

gritty halo
#
    if request.method == 'POST':
        print(request.body)
        body_unicode = request.body.decode('utf-8')
        body = json.loads(body_unicode)
        print(str(body))
        content = body['uid']
        print(content)
    return HttpResponse("Ok")```
#

prints out b'{"username":"testOne","ccValue":4,"uid":"8dUkj3KL","date":"12\\/12\\/12"}' {'username': 'testOne', 'ccValue': 4, 'uid': '8dUkj3KL', 'date': '12/12/12'} 8dUkj3KL

#

the first one is valid json if the 'b' and ' are removed, the second one is valid json if its " instead of ', does anyone know why im getting this? or how to get proper json out?

ripe pecan
#

Yes, JSON requires ""

#

Instead of ''

gritty halo
#

How can l fix it to that?

ripe pecan
#

I'm not sure what the context is... How are you getting that data

gritty halo
#

From my client

ripe pecan
#

Oh oops didn't see that

gritty halo
#

Doesn’t make sense that it changes from “ to ‘ that tho pretty confused

ripe pecan
#

Which version of python are you using

gritty halo
#

3.7

ripe pecan
#

Hmmm, I'm not 100% sure about this, just a guess, but try not decoding it

#

Comment out the decode line and see what it prints

#

I believe json.loads does the decoding in newer versions of python

gritty halo
#

Ok I’ll try

#

R u saying load just request.body

ripe pecan
#

json.loads(request.body)

gritty halo
#

Ok

ripe pecan
#

Also, I think part of the problem may have been you were doing print(str(body)) rather than print(body)

gritty halo
#

the str doesnt effect it

#

i tried both ways

#

and doing what you said gives me this ```{'username': 'testOne', 'ccValue': 4, 'uid': '8dUkj3KL', 'date': '12/12/12'}

#

which still doesnt have the ""

calm solar
#

i'm working my way thru a flask tutorial. why does the content change when i hit refresh a lot? it's a very simple script. is it a matter of loading not finishing before rendering?

gritty halo
#

@ripe pecan figured it out i needed to use json.dumps()

#

apparently python will conver to single quotes for whatever the reason and that changes it to be double

ripe pecan
#

@gritty halo huh.. I didn't know that, thanks for letting me know

ripe pecan
#

@calm solar how does it change?

calm solar
#

it doesn't at the moment. i can switch it back.

#

its the oddest thing. i've done a lot of web dev and haven't seen anything quite like it

#

and of course it doesnt do it anyore

#

oh well

modern vale
#

So...

#

I turned on local memory caching and now Django is giving me an TemplateDoesNotExist at /users/login/

#

But the thing is, I'm using the built in auth by using this

#

path('users/', include('django.contrib.auth.urls')),

#

At the project level URL

gritty halo
#

How to detect if its a mobile connection in django?

candid basalt
#

Mobile connection or mobile device?

winter pagoda
#

What are people's experiences with proxies? I'm trying to use Selenium combined with browsermobproxy to be able to read packets in. But it's proving a huge headache.

#

Sites that load just perfectly well with Selenium fail to work when using BMP to login, and looking at the Javascript Console it seems like the packets aren't the same

modern vale
#

Hello all, just a quick Django question: I have a template that connects to a detail view. The model "Articles" has a "created_on" field and an "edited_on" field. In my template, I am comparing the two values.

#

When I do this:

#

% if object.created_on != object.edited_on %}
<p> Edited {{ object.edited_on }}</p>
{% endif %}

#

*{% if object.created_on != object.edited_on %}
<p> Edited {{ object.edited_on }}</p>
{% endif %}

#

But even when they are both the same, as in. The article is published as soon as its written (I have a boolean field, isPublished) it still displays both fields

#

What am I doing wrong?

#

I think it has something to do with using timezone.now but I'm not sure...

#

created_on = models.DateTimeField(default=timezone.now, editable=False)
edited_on = models.DateTimeField(editable=False)

#

How can I make this work in a way that is timezone aware?

#

Also, can anyone advise on the use of Django_extensions?

#

It seems like using that would solve many of my problems

ripe pecan
#

Do this in your template to print out the values of both: {{ object.edited_on }} {{ object.created_on }}. Or just look at the context using the Django toolbar

#

Google: how to make datetime timezone aware python. That might bring something up

modern vale
#

Thanks @ripe pecan

#

Anyone have any good guides to adding buttons to an admin detail view? (I.E extending the admin templates or perhaps the change form?)

#

I don't want an admin actions. For example, just a button that changes a boolean field. isPublished = False -> isPublished = True

ripe pecan
#

Do you have an isPublished field in your model?

modern vale
#

That is example. Are you familiar with django_extensions?

#

Would you like me to post my model code?

ripe pecan
#

I am not familiar with django_extensions

modern vale
#

Pretty great to not to stuff manually

#
from django.db import models
from django.core.cache import cache
from django.urls import reverse

# Import our user model, so we can attrib more than user to an Article. Like IRL.
from user.models import UserModel

"""
Add Django extensions for:
* Automatically create time stamps (created: DT field, modified: DT Field)

* Automatically create "active", "inactive", "activate_date", "deactivate_date"
  we will use this for implement the publishing function on articles.
  
  It uses Choices to implement this functionality.
  
* Automatically generate a slug for our URLs from our title fields
"""

from django_extensions.db.models import TimeStampedModel, ActivatorModel
from django_extensions.db.fields import AutoSlugField


class Article(TimeStampedModel, ActivatorModel):
    # Fields required by test

    title = models.CharField(max_length=100, unique=True)
    body = models.TextField()

    # Attrib each article to a user/s

    authors = models.ManyToManyField(UserModel, related_name='authors')

    # We use this field to automatically gen slug from title

    slug = AutoSlugField(populate_from=['title'])  # Make slug from title

    """
    Let's def the string repr of the model to make it look nice in the admin interface
    Let's also def absolute URL and create reverse lookups...
    Mostly because its complete masochism to change object URLS in the future if you dont
    And finally, let's override the save method to flush the cache on every object save as per the specs
    """

    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        cache.clear()  # On Article save, flush cache
        super(Article, self).save(*args, **kwargs)

    def get_absolute_url(self):
        return reverse('article_detail_view', kwargs={'slug': self.slug})  # Use slug instead of PK (Int)

modern vale
#

@kind steppe Are you free by chance? 😃

kind steppe
#

I am here, hello

modern vale
#

Hey man. Thanks for responding. I've actually fixed the issue I asked about previously by using django_extensions...the problem was that I was generating one field using timezone and another using auto-add-now

#

But now I have another question, if you have a moment

#

I would like to add a button to the top of the change form of the Article model to change the objects state from "inactive" to active

#

Not an admin action...but a simple button that changes the state. I've tried looking into it on my own, but I can't get it right. I think it has something to do with either extending the default admin template or, modifying the default ModelForm

modern vale
#

Anyone?

ripe pecan
#

🤷

#

I'm not sure

fickle token
#

Is the best option for web development using python Django?

modern vale
#

Depends on the scale of your project

#

I would recommend Django...but, full disclosure, I use Django almost daily so I'm biased

fickle token
#

Hmm

#

What’s the one which will be more useful in the long term?

ripe pecan
#

There's quite a few depending on your needs

#

Django and Flask are the two big ones

#

Django is not going anywhere

#

Sanic is pretty popular too

#

If you're building just a backend API and you're familiar with Django, there's also the Django Rest Framework

modern vale
#

How do I add a button to my object change form on the admin panel?

#

I would like the button to change a field when clicked

serene dove
#

anyone tried it before

timid arrow
#

looks cool, especially swagger generation

#

but I'd prefer opposite way, when it generates some stubs using a swagger

native tide
#

How good is the udemy course on Django? I pirated all of it's videos recently

deep cave
#

!warn @native tide I told you not to discuss piracy on this server.

lavish prismBOT
#

:ok_hand: warned @native tide (I told you not to discuss piracy on this server.).

modern vale
#

lmfao

#

This guy is bold

#

Would it be cool to ask a Jquery question here or nah?

#

So...I'm using local memory caching with my Django page. I would like to write a small piece of Jquery to poll the site for updates, and if it find one, refresh the browser

arctic ingot
#

hello , i have a page html and this page has a several titles and tables album and tracklists like this :

#

and i want put these information automatic in wordpress posts :

#

i want to put these information (title then album_table and then trackilist) and publish it , and again put the title two and album... and publish , how i can do it ? please any can helo with this ?

ripe pecan
#

@modern vale why poll? Is there no way to subscribe to changes? I feel polling could be expensive

modern vale
#

@ripe pecan Need help with an assignment, can't seem to figure it out

#

They specify I need to use JQuery to do it...so that's what I need to do

ripe pecan
#

how are you thinking of doing the polling?

modern vale
#

I have no idea where to begin really...

#

So there are articles on the homepage right?

#

These articles have a field, published. When its set to true. They show up. Else, they dont. But every so often I'd like the script to check if there are any new ones and just add them to the DOM

#

But I don't really know how I'd go around doing this...I'm a backend guy. I'm sh*t at front end

ripe pecan
#

Okay, but do you have an API you hit with your front-end to see if there are new posts?

#

Or is the backend just serving up straight HTML

#

I think what you need to do is the first thing. Create an API that responds with all published posts. Hit the API using jquery's ajax method. The response that you get back will be what you will use to populate the list of posts dynamically using jquery.

modern vale
#

I'm using Django. No rest or GraphQL.

#

I'd like to just insert a script into the home template and have it poll that way, with the same URL

#

It makes me feel dumb cuz, I can do all this other stuff...but not figure out how to write a simple jQuery script lmfao

ripe pecan
#

Right, but if you're just serving up a template, you'll only be notified about the changes on page reloads. Is that okay?

paper wagon
#

Hi folks,
I was working on web application with PHP and developed a MVC model by myself. Now due to some reason we are shifting to python.
I have some experience with Django framework. But Now with my new web application I want to develop it in python and I will design my own MVC model in it.
I am not sure that I will be able to do it python So, can you guys help me with some knowledge.

  1. Can I use python to create my own MVC model without Django and Flask?
  2. Will it be feasible and good option to create my own MVC and not using Django or Flask?
candid basalt
#

Yes, probably no.

paper wagon
#

@candid basalt Did you ans my question?

candid basalt
#
  1. Yes. 2. Possible, but suboptimal.
#

@paper wagon yes.

paper wagon
#

@candid basalt Thanks mate. Can you provide me some ref to get started I tried googling it but couldn't find it web app only with python

candid basalt
#

But I recommend going with Flask instead as it's lightweight and versatile enough to build just about anything on top of it.

#

Django is "batteries included", very powerful, but customizing it's internals may not be easy due to how everything is stitched together.

#

And it will not be a good idea ty try and change it's paradigm to MVC.

#

@paper wagon

paper wagon
#

Sure Mate will Try Flask if its work out with my requirement. ALso WSGI in python seems a difficult to implement as if I'm going with flask I guess

candid basalt
#

👍

#

@paper wagon also check jinja for templates and sqlalchemy for ORM.

untold fern
#

How can I change the default template folder

#

I've been searching online but none of those links has helped me solve the problem

candid basalt
#

Default template folder of what? Framework? Lib?

ripe pecan
#

People please be more descriptive

untold fern
#

Flask sorry 😅

modern vale
#

@ripe pecan , I would like it to poll the homepage for changes every so often. If the script detects a change, reload the page OR add the elements to the DOM

#

Either or would work

#

Also, thanks for your help man. If I ever become a millionaire, you'll most def get a statue in your honor on my porch

#

Also, remember that I'd like to do this with JQuery...meaning, the script is running in the background after the page has loaded

wary mantle
#

Anybody know why I'm getting this error?

  File "app.py", line 29
    return redirect(f"/mc/{yname}")
                                 ^
SyntaxError: invalid syntax
``````py
        if not yname:
            flash("Missing your name.")
        else:
            if not usersname and not pmessage:
                return redirect(f"/mc/{yname}")```
fluid horizon
#

check if you're using python 3.6

wary mantle
#

Ohh. K that's why.. thanks 😄 👌

ripe pecan
#

@modern vale let's hope you become a millionaire then ;)

#

@modern vale I feel like we're talking past one another. Let me start from the beginning. The status for the posts is updated on the server, yes? You need to use jQuery to check the status of the posts. But jQuery only works on the client side. Do you understand, generally speaking, how the server and client communicate with each?

modern vale
#

Yes

#

@ripe pecan Again. This is just a simple Django app.

#

Django renders the page. I would like the script to "fetch" the page at an interval

#

If the script find that the page has new articles, it refreshes the user's browser

#

OR just adds those elements to the DOM

ripe pecan
#

Right, so to "fetch" the page, if you don't want to do any REST stuff, you need to do a GET request using jQuery to get the HTML. And then, you can use jQuery to see if there's been a change

candid basalt
#

Is that not limited by the same origin policy?

native tide
#

I got a couple of issues with URLs

sturdy sapphire
#

you should ask your question, not ask if anyone is good with it

#

!t ask

lavish prismBOT
#
ask

Asking good questions will yield a much higher chance of a quick response:

• Don't ask to ask your question, just go ahead and tell us your problem.
• Try to solve the problem on your own first, we're not going to write code for you.
• Show us the code you've tried and any errors or unexpected results it's giving
• Keep your patience while we're helping you.

You can find a much more detailed explanation on our website.

sturdy sapphire
#

you where told this before, please read the message and ask your question

sturdy hare
#

Anyone here familiar with Flask? I have a weird problem related to flask-sqlalchemy mapping. Specifically, when defining a relationship on a model that cannot be found, the app fails to run (example of someone else experiencing this is here: https://stackoverflow.com/questions/49504077/sqlalchemy-exc-invalidrequesterror-one-or-more-mappers-failed-to-initialize-c).

The issue is that this is only detected/errors out on prod, but running locally or my test suite doesn't detect this error. It's weird as I would expect it to in the tests, especially because one or more of my tests import the said model in which case that error should appear right?

#

Anyhow it's a trickier one and thought maybe someone here might have some experience with this?

sick shell
#

Hey please help me 😦 I need help cause i'm doing some docker architecture where i have an Ngnix in front of two docker instances (uwsgi + django). The two docker instances need to talk over http with each other. But when one is trying an http query to the other (via the Ngnix) django complains about the HOST header being not compliant to the RFC 1034/1035. i mean i KNOW that but this is coming from a save enviornement so i need to disable this check anyone has a clue?

ripe pecan
#

@candid basalt No, I don't think so

candid basalt
#

I think server you are trying to post to has to cooperate via sending appropriate headers.

ripe pecan
#

Yeah, maybe you're right. Even for GET requests?

wary mantle
#

Hey,
So I am a complete beginner at web-development. I have a flask app, I have a VPS and I have PuTTY . I got my flask app to run, although, now... How do I host it to a domain? 😄 .The question is quite vague, it's because I'm quite new to all of this. 👍

modern vale
#

@ripe pecan How do? :/

#

So you have a VPS hosting your app and you'd like to connect a domain to it?

wary mantle
#

yea

#

@modern vale

modern vale
#

Man, that sounds really complicated. You'd have to setup a DNS server and do a whole bunch of stuff

#

Do you know how to use git?

wary mantle
#

no

ripe pecan
#
$.get('https://your-url.com', response => doSomething(response));
#

@modern vale

modern vale
#

@ripe pecan Ahhhhh, ok. Now I just have to figure out how to compare the currently loaded version with the one it grabbed and if there's new content. To reload.

#

@wary mantle If you learn how to use git, you can use Heroku to deploy your apps. And then adding a domain to your app will be easy

ripe pecan
#

@modern vale yup, if you need any more help, lemme know

modern vale
wary mantle
#

@modern vale I don't want to spend anymore money on hosting (I'm quite tight), and Heroku doesn't support custom domain on free plan.

modern vale
#

Yes it does 😐

#

I've hosted my apps on Heroku with custom domain for free

wary mantle
#

Don't you have to input your bank details though?

#

@modern vale

#

Also, doesn't Heroku have a limit of 500hours or something.

modern vale
#

Anybody have a good tutorial to dynamically updating pages with Django channels?

ripe pecan
#

I assume you've read this

modern vale
#

Def. But I haven't understood it enough to do what I need it to do

#

(Dynamically update page every time an article is "published"

ripe pecan
#

I think using web sockets might be overkill, but maybe not idk

#

Can u use jquery to update the page?

modern vale
#

I have no idea where to start 😐

ripe pecan
wraith trench
#

Hello, maybe someone could suggest how to do this in django-admin. Basically I have model with let's say 10 categories. And I want to create separate admin view with options as categories and when clicked on them go to view with all posts from that category. Basically Posts View -> Category View -> Edit all posts in that specific category or create a new posts in that category

calm solar
#

anyone here familiar with flask/jinja2/mysql? trying to display a select * from * query on a template.

#

i can get the last line of the query to display but the variable is obviously just being rewritten and only sending over the last instance

woeful swallow
#

Hello everyone, I have been programming for about a year and a half in various languages and became very interested in backend dev in django/flask, is there anyone with experience who can guide me through some resources I can use to learn it and if i should learn both django and flask

#

Also, i would say im okay at front end, but its not my forte, i've heard people say that the frontend can be done by like Vue/React and use django as an API, is it a good idea to pick up on some Front end skills as well?

ripe nebula
#

flask is easier to get started with initially, but it gets a bit messy as you start to add more apps / database / login / crud functionality.
django on the other hand is harder to get started with because you need to learn what all the files do and there's more structure you have to follow, but it's very easy to create a professional and correct (i.e. good database management and all that) because it does it all for you.

personally i prefer django to flask, i would recommend thenewboston's django playlist on YouTube since that's how i learned 90% of what i know

in terms of front end, cant really help you on that one, you should probably learn a backend before a frontend language rather than both at the same time

woeful swallow
#

Thank you, ill check it out

sick ocean
#

When I run my Flask application directly with Python (developement mode?) everything works fine. When I run it through Gunicorn, it persistently fails to find my templates folder and thus the required HTML files. I have tried numerous things, such as changing the template_folder variable, and the path that is passed to render_template() - none have had any impact.

I start gunicorn with gunicorn -b 0.0.0.0:80 wsgi (it still doesn't work without wsgi), and everything launches fine.

Any request for the page will throw this error; https://hastebin.com/uzumacoyid.coffeescript

Code; https://hastebin.com/vubuyazuto.py

Any help appreciated.

abstract orbit
#

i need help setting up my modeled website

#

can anyone help

woeful swallow
#

Im sure there might be someone to answer your question, just ask @abstract orbit

#

!t ask

lavish prismBOT
#
ask

Asking good questions will yield a much higher chance of a quick response:

• Don't ask to ask your question, just go ahead and tell us your problem.
• Try to solve the problem on your own first, we're not going to write code for you.
• Show us the code you've tried and any errors or unexpected results it's giving
• Keep your patience while we're helping you.

You can find a much more detailed explanation on our website.

modern acorn
#

how can you get an error message when the login details in django is wrong

stray prism
#

Hey guys, I'm having trouble getting my program's output into a browser using Flask. I've gotten my main function working in the console, but no output in the browser. Each time I try to run the function, it states that it's missing 3 required positional arguments, but I have supplied them

#

Here's my the beginning of my function ```def darwinChecker(departure_station, arrival_station, user_time):
response = requests.get("https://huxley.apphb.com/all/" + str(departure_station) + "/to/" + str(arrival_station) + "/" + str(user_time), params={"accessToken": jsonToken})
response.raise_for_status() # this makes an error if something failed
data1 = response.json()
train_service = data1["trainServices"]
print('Departure Station: ' + str(data1['crs']))
print('Arrival Station: ' + str(data1['filtercrs']))
print('-' * 40)

#

And here's the flask bit: ```@app.route("/darwin-test")
def darwin_page():
return darwinChecker(train_station['home_station'], train_station['connect_station'], user_time['morning_time'])

#

The arguments are in a dict here: ```train_station = {'work_station': 'whs', 'home_station': 'tth', 'connect_station': 'ecr'}
user_time = {'morning_time': ['0821', '0853'], 'evening_time': ['1733'], 'connect_time': ['0834', '0843']}

#

Any ideas? I can post the full code if needed

timid arrow
#

can you show the error trackback?

cursive granite
#

I have a issue maybe some good o'l django developer can help me with. I'm trying to import a bootstrap template I have & port all the scripts & stylesheets into the project but I have one stylesheet that I cant seem to get imported which I highlighted in the screenshot. All my other CSS files will port but this one is just not wanting to go through if anyone has any suggestions I'd really apreciate it

stray prism
#

@timid arrow ```127.0.0.1 - - [21/Dec/2018 15:23:45] "GET /darwin-test HTTP/1.1" 500 -
Traceback (most recent call last):
File "c:\python\lib\site-packages\flask\app.py", line 2309, in call
return self.wsgi_app(environ, start_response)
File "c:\python\lib\site-packages\flask\app.py", line 2295, in wsgi_app
response = self.handle_exception(e)
File "c:\python\lib\site-packages\flask\app.py", line 1741, in handle_exception
reraise(exc_type, exc_value, tb)
File "c:\python\lib\site-packages\flask_compat.py", line 35, in reraise
raise value
File "c:\python\lib\site-packages\flask\app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "c:\python\lib\site-packages\flask\app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "c:\python\lib\site-packages\flask\app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "c:\python\lib\site-packages\flask_compat.py", line 35, in reraise
raise value
File "c:\python\lib\site-packages\flask\app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "c:\python\lib\site-packages\flask\app.py", line 1799, in dispatch_request
return self.view_functionsrule.endpoint
File "C:\Users\Admin\Documents\Python_learning\darwin-flask\darwinflaskapp.py", line 57, in darwin_page
return darwinChecker(train_station['home_station'], train_station['connect_station'], user_time['morning_time'])
File "C:\Users\Admin\Documents\Python_learning\darwin-flask\darwinflaskapp.py", line 52, in darwinChecker
return darwinChecker()
TypeError: darwinChecker() missing 3 required positional arguments: 'departure_station', 'arrival_station', and 'user_time'

timid arrow
#

just go to line52 of your code

#

there is return darwinChecker() which is causing a problem seems like you haven't put the full code here

#

since it's not visible

stray prism
#

Gimme a sec, I'll upload the full thing

#

The functions arguments get changed, depending on what's in the train_station and user_time so my logic is I'd return what I actually want to see under the '/darwin-test' route

#

If that makes sense

#

I've changed it to return darwinChecker(departure_station, arrival_station, user_time) but this causes an infinite loop in cmd, and no output in the browser

timid arrow
#

what your darwinChecker should do?

stray prism
#

It queries an API that looks at train timetables, and returns the information I want, based on the departure station, arrival station and the journey times you're interested in

#

So you can see in my code that it just prints service information, the request url is say, /dep/dep_station/to/arr_station/time1,time2,etc?accessToken=json_key

#

And those values are the ones stored in the dicts that I mentioned, so you'd define a home station, a work station, and user_time is what time you specifically want to see data about

#

Does that make sense?

#

So in my original code, it looks like this for the morning commute darwinChecker(train_station['home_station'], train_station['connect_station'], user_time['morning_time'])

#

I just can't get this up on browser

#

I've been up against this for days

stray prism
#

I think the return darwinChecker(departure_station, arrival_station, user_time) line is causing my loop, but if I remove it, flask tells me TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement.

#

But I can't get it working without that

coral ridge
#

Hey, I'm working on a project that fetches posts from reddit and displays them in my app.

I'm currently having trouble with i.imgur.com though as the links give me a 403 error when I click them in the app (running on localhost, i suspect this is the problem) but gfycat.com and i.redd.it works fine. I tried to google it but all of the results are about configuration errors of apache/nginx where people can't access 127.0.0.1 themselves

#

Any idea what might be causing the 403 errors with imgur?

#

Ah, Imgur's CDN seems to restrict access to images from a localhost referer.

gritty halo
#

So my client does a post to my django server, if i want to send a status back to the client if the server accepted the post or declined it after doing some query checks how would i do that? Im assuming the client has to be listening to the server for the response it gives back

#

but thats not a get request is it

gritty halo
#

needed json response got it

pine flame
#

Plz someone Know How can I disable django forms errors
Bcs I would like to print them before the form is submit (With js ajax requests)

calm solar
#

Flask/uwsgi. The only way I can get my templates/py/mysql to show updates is to ```sudo systemctl restart myproject

modern acorn
#

What's the best and easiest way to have a search bar, and when you search it puts up a list of items from a database with info about them

#

is there something i can use so ii dont have to reinvent the wheel

pine flame
#

With django?

#

Actually if you Want to print some suggestions use ajax and js

modern acorn
#

I bought datatables it seems interestinig

last forge
#

Hi friends. I’m in Django/Django Rest Framework and trying to filter my api to before a datetime using the django-filter package. The problem is I can’t find any docs that filters date and time together. I have successfully filtered the date AND time but 12-21-18 24:00 does not show up when filtering for before 12-22-18 02:00 (because 24:00 > 02:00)

#

Am I missing something obvious or is this not possible using that little setup I have?

ripe pecan
#

Try this?

#

@last forge

last forge
#

@ripe pecan that looks like it's only dealing with the date, unfortunately, not a date and time on that date.

ripe pecan
#

I mean if you have a datetime object you should still be able to use that approach

last forge
#

You're right, I hadn't woken up yet. It turns out, django-filter can handle this just fine. The documentation doesn't make it super clear that you can use just lte instead of, say, year__lte

#

Your link made me check if just lte would work and sure enough, it did. Because you were right, you should be able to use that approach.

wary mantle
#

Does anybody know any Flask hosting tutorials? I've checked quite a lot and none works for me.
I'm trying to host my flask website onto my domain on freenom. I've already got a VPS and I am able to connect to it through PuTTY.
Please do link any tutorials if anyone knows any python .

eternal wing
#

hey guys, what would you say is currently the least bullshit way to do some form of web components when I don't really care about SPAs and web components, but just want something a bit more robust than jquery? :x

#

I've used backbone, angular, ember, react (with and without redux), and a bit of vue, but I never really liked any of them :D

calm solar
#
DigitalOcean

In this guide, we will be setting up a simple Python application using the Flask microframework on Ubuntu 18.04. The bulk of this article will be about how to set up the uWSGI application server to launch the application and how to configure Nginx to

wary mantle
#

@calm solar I'm not too sure but I think I've tried the second link you sent me. I'll try both of them again just to see if it would work. Thanks for the help!ayy np

wheat trellis
#

Man nodejs is so different

#

I'm trying to learn how to deploy aws lamdba python functions

#

But to use serverless I need to learn nodejs basics

#

I'm guessing npm is equivalent to pip?

#

Or is nodejs more like flask. Le sigh

gritty halo
#

when paypal tells you your json is malformed but jsonvalidator says its valid D:

modern acorn
#

does anyone have experience with datatables and django?

proper hinge
#

!t ask

lavish prismBOT
#
ask

Asking good questions will yield a much higher chance of a quick response:

• Don't ask to ask your question, just go ahead and tell us your problem.
• Try to solve the problem on your own first, we're not going to write code for you.
• Show us the code you've tried and any errors or unexpected results it's giving
• Keep your patience while we're helping you.

You can find a much more detailed explanation on our website.

wary mantle
#

Hey

#

In Flask Production, what should I use instead of app.run() ?

strange thorn
rough magnet
#

can someone explain to me what ElasticSearch really is ?

wary mantle
#

@strange thorn I didn't use NGINX.
Also, I got my website up and running, although to access the website that is hosted by flask, I still need to add the port (website.com:5000). Is there a way I can change this.

patent cobalt
#

The built-in server in Flask is meant for development only. Nix is recommending what you can use as an alternative to that built-in development/testing server.

#

The option Nix is referring to is in that list, as are many other options of deploying your Flask app

wary mantle
#

Oh ok. I'll check it out. Thanks!

#

So does that mean I can take app.run out of the code?

modern acorn
#

I've used DRF to communicate with datatables

#

doesnt work for datatables editor tho

modern acorn
#

Willing to pay somebody with django and datatables knowledge arm

rare oar
#

@modern acorn Elaborate on the problem and maybe someone can help you without paying.

modern acorn
#

I don't know enough to elaborate

#

Datatables isn't exactly made for Django

#

and the only code that i could find to make it work with django just makes you able to display the table

#

but none of the actual edit functionality

#

and i paid like 130 euro for it lol

#

node.js / php and .net seems to be the only supported out of the box

#

All I want is a reliable datatable, to add, remove and edit items from a database

#

which is over 80,000 items, so it needs to be server sided

rare oar
#

oh got it. I was on the lines of thinking you were substituting datatable for database. Not too knowledgeable here but hopefully someone will see and help

candid basalt
#

Django default admin is decent for editing table-like data.

#

Also I believe there are libs for Django datatables integration.

modern acorn
#

It only covered datatables

#

Not datatables editor

#

This

gritty halo
#

Been reading a bit on it but im still confused on how I would make my Django App public to the entire world to connect

candid basalt
#

It's about the same as any other python uwsgi application - nginx+gunicorn works fine most of the time.

gritty halo
#

@candid basalt u have any good tutorial links?

#

@candid basalt my friend was also telling me i can port forward port 80 to my router

#

no idea what that means though either

eager shore
#

@rough magnet its like database, but build for storing and quickly searching data. You would run it next to "real" database like postgresql and store data that you want your users to be able to search on side (like articles)

native tide
#

kannaHeartsWave Hi. I might have misunderstood how websockets work, but;

Is it not possible to send data from a REST API then to a WebSocket server, and later on reading the response from a python bot?
I use aiohttp for both HTTP and Websocket server.

candid basalt
#

@gritty halo I haven't got any good tutorials handy, so google would be your best bet here.

modern acorn
#

I just ended up using crud builder

#

Its nice

steel tiger
#

if im creating a simple but high-traffic flask application, should it conform to the reccomended structure or have a couple python files (routing, models, forms, config) in seperate files and the normal templates/ and static/ folders

#

(no blueprints)

coral ridge
#

@steel tiger just do what makes the most sense in regards to readability/maintainability. Importing modules has a very, very small effect on the speed of the code.

steel tiger
#

👍

#

ill keep it the "normal" way for me.

coral ridge
#

How would I implement something like this in javascript?

Before hover

<picture>
  <source srcset="https://thumbs.gfycat.com/LoneAlienatedAfricanmolesnake-mobile.jpg" type="image/jpeg">
  <source srcset="https://thumbs.gfycat.com/LoneAlienatedAfricanmolesnake.webp" type="image/webp">
  <img class="image media" id="image-lonealienatedafricanmolesnake" alt="alt-text"
  src="https://thumbs.gfycat.com/LoneAlienatedAfricanmolesnake-mobile.jpg" height="640" width="640">
</picture>

After hover

<picture>
  <source srcset="https://thumbs.gfycat.com/LoneAlienatedAfricanmolesnake.webp" type="image/webp">
  <img class="image media" id="image-lonealienatedafricanmolesnake" alt="alt-text"
  src="https://thumbs.gfycat.com/LoneAlienatedAfricanmolesnake-max-1mb.gif" height="640" width="640">
</picture>

I'd like to have similar thumbnails as gfycat has https://gfycat.com/reactions

wary mantle
#

PythonAnywhere or Heroku for Flask?
Which is better for the price?

coral ridge
#

Why not AWS Lambda?

wary mantle
#

Quite complicated to setup from what I've heard. @coral ridge

coral ridge
native tide
native tide
#

exactly, how do you remove the link to the default configuration from sites-enabled directory?

#

I do not have at least 50 reputation so I cannot post my comment there

indigo sparrow
#

Hey there, i have a question about possibility of 1 idea. Originally not mine but some other guy.
Picture home wifi network, I want to anyone logging into the wifi to see a webpage that I prepared for them

#

it often works this way in cafes or at the airports, I hope you know what I mean

#

How one implements such thing ?

#

nvm found materials on tha !

wary mantle
native tide
wary mantle
sharp briar
#

@wary mantle did you add your redirect url to your application?

native tide
#

Using the websockets library for Python 3.x for client-side WS
How do I make it receive events that other clients has sent to the server?

An example:
Client 1 connects to the WS server
Client 1 sends "Hello World" to the server
Client 2 & Client 1 receives the same response the server sends out, even though client 1 originally sent the request.

#

(I run the server myself with aiohttp)

proper hinge
#

You don't have to do anything special

#

Make the server echo the message, and as long as both clients are set up to receive messages from the server, they will get the same message

#

the fact that one of the clients sent out that message should not matter

native tide
#

Well, this is my code atm:

async def main(uri):
    async with websockets.connect(uri) as websocket:
        bleh = await websocket.recv()
        print(bleh)

asyncio.get_event_loop().run_until_complete(
    main('ws://127.0.0.1:8080/ws')
) 

And I am not getting anything back, even when I try to send a simple string from an another client. But if I use await websocket.send("whatever")
I receive "whatever" back.

#

And on the the server part, I am just using the aiohttp websocket example that's on the docs.

proper hinge
#

Can you show the server code?

native tide
#

yes, I'll throw it in hastebin though.

proper hinge
#

Ok well I think the obvious mistake here is that you only receive one message then your program exits

#

you need to have it in a loop or something that will keep listening for messages

native tide
#

Yeah I know that will happen. But I am not getting a single message

proper hinge
#

Hmm I've never used ws with aiohttp

native tide
#

This is exactly what I'm doing, so yeah.

#

I guess I can try to give a try using WS server as well. I'll come back if I run into issues.

proper hinge
#

Just to be clear, you're sending a message right?

native tide
#

yes

proper hinge
#

Cause your client code is only receiving

native tide
#

Oh I know

#

But I am sending it from an another source

#

I am using a chrome extension for websocket connections

#

And I know that part works, since its printing the request on the server-side. As you can see in my hastebin.

#

``2018-12-27 00:55:29,699:INFO:aiohttp.access: 127.0.0.1 [26/Dec/2018:23:55:29 +0000] "GET /ws HTTP/1.1" 101 0 "-" "Python/3.6 websockets/6.0"

``

it's also connecting fine, but does not print anything unless I send it from the same client I receive.

proper hinge
#

I see

#

Sorry I am not familiar with doing this over aiohttp

#

once concern I have is that you're only sending the message to the client that sent the message

#

rather than to every1

#

I think that's what send_str() does

#

not sure

native tide
#

hm, I can try to look into that, good point.

proper hinge
#

What if you send from your python client?

#

then, will it receive the echo?

#

Or you can test the same with your chrome extension if it has a means of receiving messages

native tide
#

It does have receive, and it works fine

proper hinge
#

Ok, so not only does the server print but client also receives it

native tide
#

The red is the request

#

the black is the response

proper hinge
#

I think my suspicion is correct upon further research

native tide
#

Hm yeah, when I tried sending from the python client it did not pop up on the extension

proper hinge
native tide
#

Oo thank you, that'll maybe be it. I'll give it a try, thank you kindly. kittyHeart

proper hinge
#

You're welcome. Definitely follow hubo's advice in the comments there

limpid birch
#

Hello, I am making a flask app, looking for advice on how to protect some endpoints. I have, for example, an endpoint /api/event/create that my javascript client POSTs form data to. Right now anyone from anywhere can POST to that endpoint. I would like it so that only my javascript client can. Advice on how to best achieve this?

I have seen that one way to go about this would be to have user/roles, have users log in to my web client, then POST the form data in addition to something to authenticate the user. Is this the "correct" way to do this or can it be done in a different way? e.g. one that doesn't required users to log in

native tide
#

Okay, I finally set up gunicorn with nginx correctly but now I keep getting redirect errors when I try to go to the page. Another developer suggested that maybe django's settings I have for ssl might be the problem. They look like this

SECURE_HSTS_SECONDS = 10
SECURE_HSTS_PRELOAD = True
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_BROWSER_XSS_FILTER = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_CONTENT_TYPE_NOSNIFF = True
# SECURE_SSL_REDIRECT = True
# X_FRAME_OPTIONS = 'DENY'

Is there something I can do here to stop the TOO MANY REDIRECTS error?

#
modern acorn
#

In Django i want to pass a javascript variable inside of formURL: "{% url 'URL' javascriptvariablehere%}"

#

how can i do that

coral ridge
#

@limpid birch you can make it so that you generate a token and pass that in the header of the request

#

There are plenty of auth tutorials for flask apis

wary mantle
#

@sharp briar Yes, I did add the redirect url.

wary mantle
#

Oh, nvm. I forgot add in /callback to the redirect URL. Thanks!

candid basalt
#

There is something I don't get.

#

The code does check for get_absolute_url property presence, but never uses it afterwards.

#

I wouldn't imagine 'reverse' would use it.

#

What's the catch? The issue is the "get absolute url" function never ever ends up being called.

#

While it should have been...

#

What am I missing?

lapis quest
#

Hello guys can someone help me i have a prob with django i cannot load imgs from static directory
i did what site said but it wont load image

#

nvm fixed forgot to add staticfile dirs into cfg my bad

candid basalt
#
[16:27] DiRaven: There is something I don't get.
[16:27] DiRaven: Source code: https://github.com/django/django/blob/master/django/contrib/admin/options.py#L292
[16:27] DiRaven: Intended behavior: https://docs.djangoproject.com/en/2.1/ref/models/instances/#get-absolute-url
[16:28] DiRaven: The code does check for get_absolute_url property presence, but never uses it afterwards.(змінено)
[16:28] DiRaven: I wouldn't imagine 'reverse' would use it. I checked it, though. Still no luck.
[16:28] DiRaven: What's the catch? The issue is the "get absolute url" function never ever ends up being called.
[16:28] DiRaven: While it should have been...
[16:29] DiRaven: What am I missing?
native tide
candid basalt
#

You should put config files into sites-available directory instead.

#

then

cd sites-enabled
ln -s ../sites-available/your-config-name.conf ./
limpid birch
#

@coral ridge thank you. many, if not all the tutorials I see on token based authentication require having users that log in. Is it possible to have the client authorize without users?

#

I only care that api calls are coming from my website/client. I think I could hard code a token into the JavaScript, but then I don’t know if that’s actually secure at all.

coral ridge
#

Well, it would basically be like an API key

#

But if someone manages to capture the post request that you are sending, then they can see the key/token and abuse it.

native tide
#

@candid basalt so I do not need a config file in both sites-enabled and sites-available?

limpid birch
#

@coral ridge thank you.

candid basalt
#

@native tide config file in available and symbolic link to it in enabled.

native tide
#

ah, I see.

#

I reinstalled the server to start over, should I just delete the /etc/nginx/sites-available/default ?

candid basalt
#

No if it works.

#

Why do you want to delete it?

native tide
#

well I created a mysite.conf in sites-available and wasn't sure if they would conflict or something

#

it does give

a duplicate default server for 0.0.0.0:80

at line 2 [emerg] with sudo nginx -t however

candid basalt
#

Your custom config should not be set as a default server.

#

Or you can replace the default serve with your own if you like.

#

That should also work. It's just default server config may be supplied by the package manager and managed differently in each case.

#

So I'd leave default where it is and add custom config instead.

queen fiber
#

Hey guys how do I stack a column with css flexbox.
Like I have 5 items. I want the first 3 to be in one row then the second 2 to be on the next row

#

is that possible?

ripe pecan
#

yes

#
<div style="display: flex;"> Item1 Item2 Item3 </div>
<div style="display: flex;"> Item4 Item5 </div>```
queen fiber
#

I was able to get it working with another way 😄

ripe pecan
#

sounds good

modern acorn
#

I gave up on trying to get datatables editor to work in Django

#

went with crud instead, works just as good

candid basalt
#

@modern acorn what exactly did you use?

#

I mean what libs for frontend and backend.

modern acorn
#

Datatables for front end up (the non editor version), with django rest framework

#

And django crud views to manage model data

#

Trickiest part was selecting an item in the table and be able to edit that item

candid basalt
#

Hmmm.

#

I see, thanks.

wary mantle
meager anchor
#

pass is a keyword, you can't use that there

wary mantle
#

Ohh, yeah. Thanks!

covert radish
#

anyone knows how to let users add extra fields to their version of the app in django ORM / models?

I tried:

class App(models.Model):
    owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='users')
    name = models.CharField(max_length=100)


class AppField(models.Model):
    # todo: tiered access to the fields
    app = models.ForeignKey(App, on_delete=models.CASCADE)
    name = models.CharField(max_length=100)
    value = models.CharField(max_length=100)

but that makes every new field a string, is there a way you can let users choose what type of field it should be? "number, string, choices (that store multiple values)" etc

#

The end goal is to create something similar to this:
allow users to add and customize fields

it's more powerful than spreadsheets because it allows you to view each row as an individual item on its own page

ripe pecan
#

So basically the schema will be altered dynamically?

covert radish
#

not sure, but i'm trying all sorts of stuff
Here's where I'm at

class App(models.Model):
    owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='users')
    name = models.CharField(max_length=100)


class AppField(models.Model):
    # todo: tiered access to the fields
    app = models.ForeignKey(App, on_delete=models.CASCADE)
    type = models.CharField(max_length=100, choices=test_choices, null=True)
    title = models.CharField(max_length=100, default='')
#

now I have to figure out a way to make an app item, and read the AppField title like a column on a spreadsheet

ripe pecan
#

You want a dynamically updating schema?

native tide
#

Where does gunicorn log errors? I am trying to set up my app with ssl and so far I think nginx is set up correctly (it does not have any errors in its error.log and no errors when checking its status). This means the Internal Server Error can only be coming from gunicorn or the app itself. I set the app to use a custom error page, but I am getting a completely blank one, thus I suspect gunicorn is the reason here.

native tide
native tide
#

but my app does not have user authentication, or users logging in at all

#

so my problem is not there

native tide
#

I narrowed down the problem some more. It is certainly something with my django configuration and not guincorn. This question seems to echo it, but there are zero replies to it. https://stackoverflow.com/questions/51532101/django-static-file-internal-server-error-missing-staticfiles-manifest-entry-for

rare oar
#

Real dumb question. Given a m2mrelationship, is there anyway to preserve order when querying data back? Using Postgres. I know thats not really how dbs work, but man it'll suck to have to write another relationship to give order

#

relevent models:

#
class Team(models.Model):
    created = models.DateTimeField(auto_created=True, auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    players = models.ManyToManyField(Player)

    def __str__(self):

        if self.id:
            s = '/'.join(p.display_name for p in self.players.all())
            return s
        else:
            return "No Team"


class Match(models.Model):
    created = models.DateTimeField(auto_created=True, auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    tournament = models.ForeignKey(Tournament, null=True, blank=True,
                                   on_delete=models.SET_NULL)
    league = models.ForeignKey(League, null=True, blank=True, default=None,
                               on_delete=models.SET_NULL,
                               related_name='league_matches')
    event = models.ForeignKey(Event, null=True, blank=True, default=None,
                               on_delete=models.SET_NULL,
                               related_name='event_matches')

    status = models.TextField(max_length=300, choices=STATUS_CHOICES,
                                   default='in progress')
    teams = models.ManyToManyField(Team, related_name='team_matches')
    stream_url = models.URLField(null=True, blank=True)
    winning_team = models.ForeignKey(Team, null=True, blank=True,
                                     related_name='winning_team_matches',
                                     on_delete=models.CASCADE)
    ranked = models.BooleanField(default=True)

    def __str__(self):
        return f"{' VS. '.join(t.__str__() for t in self.teams.all())}"


    class Meta:
        ordering = ['created']

Looking to make Match.teams be queried back in same order it was appended

#

I guess a sensible would be to add some kind of slot to Team, but I was trying to make it easier to select in the django admin and I made all Teams check for duplicates and not add to the database. So each Team is truly unique. What other way can there be? Some kind of additional Table that gets slot numbers?

#

The purpose is to track team positions now on the game map. It wasn't part of the original requirement

candid basalt
#

The order in which teams were added to the match/

modern acorn
#

My datatable isn't case insensitive

#

ive tried to change the settings

#

The case insensitive setting didnt worrk but "search": {"regex": true}, did

modern acorn
#

is there any issues with displaying responsive websites when u run development server?

#

django

#

my site loads on my phone (hosted locally on my internet)

#

it just doesnt load a phone version and seems to request desktop version

modern acorn
#

Or is this a common problem if your static files arent handled by apache

coral ridge
#

If i'm fetching data from an API, does it make any sense to wrangle the data and print it out to the website with Flask+jinja, or should I just do it with js?

covert radish
#

@ripe pecan i guess i only just need to allow end-user to create their own table/model using django ORM in a very controlled way, like allowing them only to choose the type of field and the name, but im still trying to learn how to do that

rare oar
#

@candid basalt Yes

cold rampart
#

I need an async framework for building JSON REST APIs, I have taken a look at https://github.com/plone/guillotina , https://github.com/falconry/falcon and https://github.com/timothycrosley/hug , but I can't really decide due to a lack of experience. ^^'

#

the latter two don't seem to be async

#

I might also give Quart or Sanic a try, I'm not sure.

ripe pecan
#

I think sanic is the most mature, but I don't really know

#

I'm hoping Vibora isn't dead

#

I'm looking forward to that

kind steppe
#

I remember sanic being the most mature but there were some real security issues with it last time I checked

#

Personally I like hug because I like flask and hug is very similar to flask

#

Hug runs on top of Falcon anyway though

#

it's quite an old one though so they may have been fixed

ripe pecan
#

I think it's being actively developed

#

And things are being fixed

#

Though I'm not certain

ripe pecan
#

@covert radish You would need to makemigrations and then migrate after. do you have something set up for that?

agile ivy
#

Sorry for interrupting guys. I want to ask a quick question. So what library of javascript I should use for Django? Reactjs or Vue JS

ripe pecan
#

doesn't matter

woeful ledge
#

AttributeError: 'AnonymousUserMixin' object has no attribute 'username' has anybodt experienced this error before?

#

and what are common problems causing it?

ripe pecan
#

But, it seems like you're looking looking at a mixin instead of the object.

#

What's the code that causes this error?

woeful ledge
#
def validate_username(self, username=username):
        if username.data != current_user.username:
            username_auth = User.query.filter_by(username=username.data).first()
            if username_auth:
                 raise ValidationError("This username has already been taken. Please pick another username.")
#

ok that didn't paste well

#
@app.route("/register", methods=["GET", "POST"])
def register():
    if current_user.is_authenticated:
        return redirect(url_for("home"))
    form = RegisterForm()
    if form.validate_on_submit():
        hashed_password = bcrypt.generate_password_hash(form.password.data).decode("utf-8")
        user = User(username=form.username.data, email=form.email.data, password=hashed_password)
        db.session.add(user)
        db.session.commit()
       flash(f'Your account has now been created', "success")
#

jinja points to these two

#

statements

ripe pecan
#

Oh okay, you're not using Django

woeful ledge
#

only flask

ripe pecan
#

def validate_username(self, username=username)

#

username=username, what is the RHS username

woeful ledge
#

oh yes that was something I was wondering if it really was nescessary

#

username = StringField("Username", validators=[DataRequired(),Length(2,20)])

ripe pecan
#

is username a global var or a class variable?

woeful ledge
#

class

ripe pecan
#

do you not need to do self.username?

#

Sorry, I haven't ever used Flask, but I'm trying to help 😛

cold rampart
#

@kind steppe I personally don't trust Sanic 😅 hug isn't async though, is it? ^^'

kind steppe
#

I think it has async modes

#

but sadly falcon is not async

ripe pecan
#

What about this?

kind steppe
#

ah of course responder

#

I completely forgot about that

#

I've been meaning to make use of it

cold rampart
#

Is that async?

kind steppe
#

man i really want to know that font lol

ripe pecan
#

I'm not a fan of the font :/

kind steppe
#

i neeeeeed a name

#

oh found it, it's paid for lol

cold rampart
#

Inconsolata is great :) and it's free

#

@kind steppe

#

And wow

#

responder is great :o

#

almost too good to be true

kind steppe
#

oh that is a nice font, thank you for the recommendation!

ripe pecan
#

i like my ligatures

#

with fira code

covert radish
#

@ripe pecan i've posted this on stackoverflow with a more detailed context
https://stackoverflow.com/questions/53971797/how-to-allow-a-django-end-user-to-create-their-own-table-in-a-controlled-and-sec/53972801?noredirect=1#comment94791381_53972801

main objective is to allow users to create their own fields, i guess json is not a bad option for this type of functionality

Now i need to figure out how to turn a json string into a template field that can be edited by end users

glossy osprey
#

Not sure if this strictly applies to web development

#

But I'm trying to scrape some data at the moment and am having a bit of trouble

ripe pecan
#

@covert radish I don't think I can offer any help beyond what the stackoverflow post has given

#

:/

#

Sorry

glossy osprey
#

I looked into the url structure and split it apart to find out what's what, and one field was "security" which is some sort of session token I think?

#

Which is generated each time a new person makes a request

#

But I'm not sure how to generate that token via Python, the initial post request sent (looking at that via chrome dev tools) already includes the token

#

In the browser

covert radish
#

@ripe pecan it's cool fam thanks for trying :D imma keep punching this problem till i crack it :D

ripe pecan
#

@glossy osprey is it a hidden field in the form?

glossy osprey
#

The token?

#

I couldn't see any reference to it in the initial loading

#

Something to do with cookies maybe?

#

@ripe pecan

#

Oh shit, I think I just found it?

#

Woot woot

junior lintel
#

I'm having some trouble getting CSS to render with WSGI/Flask/Apache2 - has anyone had this problem before? (all forms etc work, but css won't render?)

ripe pecan
#

do you have to do collectstatic or something like that?

#

@junior lintel

junior lintel
#

I don't think so - I have my static folder specified and it worked within a venv. I can navigate to mydomain.ca/static but I get a 404 when I try to access /static/css where main.css is

#

I'm pretty new to flask. I read that it might be permissions-related, so I tried changing the owner of /static/ to root, then www-data,. then pi (it's a pi web server) and the CSS won't render

#

I'll put my code up on github

ripe pecan
#

Hmm I'm not sure, sorry :/

junior lintel
#

I think it might have something to do with not being able to access the subfolders of static

#

I can access my app paths and my static folder, but no subfolders of static

#

moved my main.css to /static/ and I can navigate to it now, but it still doesn't render...

junior lintel
#

If this were a permission error, it wouldn't be returning 404, right?

cold rampart
#

permission error is usually 403

#

404 means not found

#

So I decided to use https://github.com/kennethreitz/responder for the backend of my project. What are solutions that I can use for OAuth2? I want users to login via Discord. It has to be async because everything else is async and I can't have something block the loop. Any ideas?

native tide
#

Do you know how to press a button in HTML then activate a function in python with flask?

junior lintel
#

I can't for the life of me get flask to serve any files/subfolders in the static folder 😦

#

it finds /static, but nothing within it

ripe pecan
#

@native tide you cannot run Python in the browser. If you're talking about a function on the server, make a GET request to some endpoint using fetch

native tide
#

can I explain what I'm trying to do really quick

#

I'm trying to add a button that then runs a python function on the server that does something

ripe pecan
#

Yeah, do what I said

native tide
#

K

#

I'll look into that

#

later today cause it's almost 1 am

ripe pecan
#
  1. Add button using HTML
  2. Add an onclick event listener using JavaScript to that button
native tide
#

Okay

ripe pecan
#
  1. When that event is fired, make a GET request using fetch to some predefined endpoint
  2. $$$
#

If you don't want to do any JS, you could just place the button inside a form, change its type to submit, and add an action to the form with the url you want to hit.

junior lintel
#

Is there a trick to getting an alias in apache conf to include subdirectories? I think that's where I'm stumped here

native tide
#

does anyone have a quick guide for deploying admin static files with nginx?

#

the common tutorials that keep popping up are either for apache, or outdated versions of django

shrewd sand
#

@native tide are you doing it to learn?

#

Or just want it done?

native tide
#

@shrewd sand I need it done for an app I just pushed to production. The rest of the site works fine, but we are unable to get into the admin pages because the static file path for it is not set. After login it gives a 500 error.

#

I am very much willing to learn too.

shrewd sand
#

@native tide This is my design for a website.

#

This won't work perfectly for you, but hopefully you will be able to use the site.conf to figure stuff out

#

I'm on mobile, so I can't really go in depth, but maybe this is better than nothing :D

opal schooner
#
<div class="section-fullpage">
    <div id="particles-js">
        <div class="center-div">
              <h1>Placeholder</h1>
              <p>Text</p>
        </div>
    </div>
</div>```
```css
#particles-js {
    position: left;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    overflow: hidden;
    background:#333333;
    height: 100%;
    
}

html, body {
    height: 100%;
    margin: 0;
}

.section-fullpage {
    height: 100%;
}

.center-div
{
    position: relative;
    float: left;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);

    font-family: 'Open Sans Condensed', sans-serif;
    text-align: center;
    color: white;
}

.center-div h1, h2, h3, h4, h5, h6 {
    font-size: 5em;
}```

Using this to make a fullscreen page with centered text but for some reason my center-div tag causes the particles to not go to the top of the page
Here are some screenshots about it:
Without center-div tag:
https://cdn.discordapp.com/attachments/508329812625063937/529679050223124480/unknown.png
With center-div tag:
https://cdn.discordapp.com/attachments/508329812625063937/529679311461023744/unknown.png
#

As you can see, on the bottom photo it doesnt go to the top

#

for whatever reason

native tide
#

Sharpie, your site conf doesn't have anything I don't have in my nginx conf, but thanks for trying to help.

#

Did you set a specific route for admin static files in your settings.py ?

native tide
#

so here's the usual solution to my issue

location /static/admin {
        alias /usr/lib/python2.7/dist-packages/django/contrib/admin/static/admin/;
}

but this does not work on a production server (or even a development server) because python is installed through a virtual environment

cinder roost
#

Hey, I'm wondering what I would have to look up to find out how to output python data to my website

#

with live feed

#

does anyone know what that's called?

native tide
#

asynchronous javascript?

cinder roost
#

Aight

#

I'll look into that

native tide
#

here is another solution that comes up, but like the first one, this does not work with virtual environments

STATICFILES_DIRS = [
    '/project/src/static',
    '/usr/local/lib/python3.6/site-packages/django/contrib/admin/static',
]
amber stone
#

Hey guys, I'm trying to learn Django. Any good book reccomendations?

#

Maybe I should start with the docs

grand badge
#

the docs have a very good tutorial that you can start off with

#

im not sure about books tho

#

Theres this django book that i know of but its for more experienced django devs

#

Oh yes i almost forgot

#

Corey Schafer has a django tutorial

#

His channel is awesome

amber stone
#

thank you

native tide
#

how do you see errors in django when DEBUG = False ?

#

I fixed my admin static files problem by adjusting the permissions on the right folder

#

but now when I log in I'm getting a 500 error in the app itself

ripe pecan
#

@native tide You should have a log file

native tide
#

where is the log file?

ripe pecan
#

uh i think you have to set that up

modest bough
#

does anyone have any experience with donation websites? I'm looking to add a "buy me a beer" link for a project, but am unsure which platform I should go with

shrewd sand
#

@native tide Maybe using docker would help you?

#

Because then you could just stuff everything in a repo

#

and use docker to sort it all out

native tide
#

that would be counter-productive. The site is already live on a VPS, and I have everything set up with nginx and gunicorn after all these months that it finally works perfectly

#

except for this error

shrewd sand
#

ooo maybe it's gunicorn

#

Not nginx

native tide
#

hmm, gunicorn is showing no errors in its logs at all

#

the error does not show up in the browser console either, which means it is internal to the application

shrewd sand
#

@native tide So your problem is python is in a virtual environment basically?

native tide
#

no, it's when accessing the admin part of the app

#

the virtual environment is running fine

shrewd sand
#

What's different about the admin part of the app

native tide
#

I am loggin in successfully, so I suspect the error is with accessing the database. Or any of the logic of the app itself that happens between logging in the to admin and accessing the admin pages

#

the virtual environment has nothing to do with that

shrewd sand
#
here is another solution that comes up, but like the first one, this does not work with virtual environments
STATICFILES_DIRS = [
    '/project/src/static',
    '/usr/local/lib/python3.6/site-packages/django/contrib/admin/static',
]
#

I was reading that sorry

native tide
#

oh, yeah. I've already fixed that by adding that path to nginx and setting the chown permissions correctly

shrewd sand
#

Where are you getting the error then? in which log set

#

Could I just see what it says?

native tide
#

I am being redirected to my custom 500 error page as soon as I log in. That is the only information I have about the error.

#

thus my search for the logs

shrewd sand
#

So the error is nginx?

native tide
#

no

#

nginx is giving no errors

shrewd sand
#

is in nginx?

#

Wait

#

No errors?

native tide
#

nope

shrewd sand
#

ok

native tide
#

this must be purely in the app itself

#

in development, errors like this would be seen in the console, since the site is running with ./manage runserver

#

but without that, the need for error logs is important

shrewd sand
#

I'm assuming you access the database using python right?

native tide
#

yep

#

using django

shrewd sand
#

What I don't understand is nginx should still be giving a error.

#

To help you

native tide
#

nginx is not like apache. it does not touch the database at all. but thanks for trying to figure this out with me

shrewd sand
#

Anyways, does the Django config work normally?

#

nginx should still state somthing

#

it's documented

#

Like does Django work on your local testing site?

native tide
#

As far as nginx is concerned, it is serving the app and everything is working normally. It has no reason to see internal errors and workings

#

on the local side, everything is working fine. But I am using a different, nosql database there

shrewd sand
#

That's horrible.

#

(no offence, just feeling bad for you)

#

So you get no message anywhere, between python, gunicorn and nginx?

native tide
#

not that I know of. I am trying to have logs generated to fix that. I wonder why django doesn't do log files as a default. It would help so much

shrewd sand
#

I think that's your problem

#

Maybe

#

hopefully

native tide
#

nope, I already fixed earlier internal server errors. Those had to do with gunicorn and nginx.

shrewd sand
#

Wait what problem do we have now?

#

I'm confused

#
I am being redirected to my custom 500 error page as soon as I log in. That is the only information I have about the error.
#

You even said 500 error page

#

Python should output all its errors.

#

To sys.output

#

But since your not using docker.... I'm not sure

#

Use tmux?

native tide
#

That's what I'm trying to find out. Like I said, when I log in to the admin half, I get redirected to my custom 500 error page. This means something is going wrong within the app itself. I suspect it has to do with accessing the postgres database. Therefore, I am trying to have django output a log of it's errors so I can read them as if I were on a development machine.

shrewd sand
#

So you can keep the python thing open?

#

No

#

If you state in your site.conf a custom 500 page

#

Wait. You haven't done that?

native tide
#

It is not running with ./manage runserver. Therefore the error is not showing up in the terminal.

shrewd sand
#

A custom 500 page that isn't actually a 500 page?

#

why

#

Thanks for clarifying

native tide
#

the custom 500 page is stated through django. Nginx does not see any of that logic.

shrewd sand
#

How are you running python then?

native tide
#

gunicorn

shrewd sand
#

So gunicorn will hold the logs in theory?

native tide
#

In theory yes, however it is not reporting any errors.

shrewd sand
#

gunicorn does support logging

#

I think that's what you need to look into.

native tide
#

I'm looking at gunicorn with

 sudo journalctl -u gunicorn

which is showing me no abnormal behaviour. If there is a better way to see gunicorn errors I am all for finding that out.

shrewd sand
#

gunicorn and Django have their own logging support.

#

I think just checking their documentation is probably the best?

#

There ya go

native tide
#

I'll mess with that for a bit

native tide
#

Okay, so it turns out error logging in django is only for page views, but not for admin pages since those are default django

#

this is really frustrating

native tide
#

I still don't exactly know what the cause was, but resetting gunicorn fixed the unexpected behaviour

woeful swallow
#

Can anyone help me fix this error? my django app was working fine until I came back to it after a week and now im getting this weird error.. http://dpaste.com/0X0059M

wraith trench
#

Hi, anyone have idea with django how to optionally prepopulate text input field, like TimeField, has ability on button click to prepopulate field with time. http://prntscr.com/m27dhz

Lightshot

Captured with Lightshot

cinder roost
#

Hey, could someone help me? I'm trying to webscrape an image but the element in which the image url is , changes constantly

native tide
#

the class of the element is changing constantly? or is it the element itself?

cinder roost
#

There is a canvas on the html page and a button to get a url which contains a screenshot of the canvas at the given time

shell lichen
#

@wraith trench - that's implemented in JavaScript

cinder roost
#

class changes

wraith trench
#

@shell lichen so there's no nice way to do that in models, or in admin file?

cinder roost
#

well the class is different for every canvas

#

And there is alot

shell lichen
#

@wraith trench - no, if you want the user to be able to click something and that populates the field without a reload, you'll need to use js.

#

@cinder roost can you use an xpath to select the correct element?

native tide
#

if the element is the same, then you can build the path by that

wraith trench
#

Got it, thanks, just though, that maybe if TimeField has this ability without custom coding anything,, so do other fields, but looks like not 😃

cinder roost
#

This might be a bit out of my league

#

idk what an xpath is so I'll learn a bit more about html first before attempting this

#

ty for the help 😃

shell lichen
#

In the dev tools you can select an element and copy the xpath. Whatever scraping lib should allow you to find elements by xpath.

acoustic blaze
#

Question for y'all: what are you guys using for authentication with Flask? Flask-Security exists but it feels really inflexible, especially if you don't use Flask-Mail already

somber burrow
#

Hi everyone. This is my first time posting. I've read over the rule and hope my question does not violate them. I'm new to web development. I have created a small web app on flask as part of a volunteer thing for kids at a middle school and am now creating my second. I'm currently trying out django. My question is, how can I improve my work flow? I'm currently coding on my local machine on visual code and then scp to my server to see if it worked. It's time consuming doing this. Is there a faster way?

patent cobalt
#

This is my first time posting. I've read over the rule and hope my question does not violate them.
Don't worry, it doesn't. (Although I can't help you with your question; it's not something I do myself)

somber burrow
#

Okay. Thank you for your input ❤

native tide
#

You can use CD services

native tide
#

My workflow is to code on my local machine, and then rsync necessary changes to the remote server when needed.

ripe pecan
#

@somber burrow check out some CI/CD stuff life biogod mentioned

rare oar
#

oh man.... I have a use case where I think I need to use a through model, but everything looks so painful to integrate it with DRF and nested serializers

#

I also use drf-writable-nested which appears to break with m2m through models

#
class TeamLineup:
    team = models.ForeignKey(Team)
    some_attribute = None
    some_other_attribute = None
#

What if I was to just build a disposable container like that. Do you think it would make it easier on DRF?

#

and have the m2m be on TeamLineup instead of Team with a through model

scarlet elbow
#

i have a webserver i run off my phone for offline web dev

#

(progrmmed in python ofc)

woeful ledge
#

socket.gaierror: [Errno 11001] getaddrinfo failed

#

how can I fix this error?

scarlet elbow
#

that says "website ip not found"
its equivalent to the chrome message "this site cant be reached" if you type in a website that doesnt exist, or if you are not connected to the internet

#

@woeful ledge what are you using directly? sockets, requests?

woeful ledge
#

I’m using flask

#

and requests

#

modules

scenic barn
#

So, this channel Seems to be fitting for my problem, I wanted to start my discord bot and a flask server (for a web-panel) through the same main.py file, wich meant I "had" to switch to Quart to get it to be asyncio compatible (or so I was told) wich now starts, the problem is: the old Flask server used flask-assets to import things like scss files, wich now throws an error to wich I can find nothing on google/stackoverflow. maybe someone could look at the error-log and see what my mistake is?
the code that gets executed: py @app.route('/') async def index(): if await is_logged_in(): return redirect('/dashboard') else: return await render_template('index.html') (and yes I tried using flask_patch.render_template) and the part that seems to cause the problem is

{% assets "scss" %}

the full error log is: https://hastebin.com/arutugigan

#

Oh and my Python version is 3.7.2 and the Quart version is 0.7.2, if that helps

candid basalt
#

How do you start flask and bot from the same file?

scenic barn
#

like this ```py

Determining the event_loop

loop = asyncio.get_event_loop()

Running the bot

loop.create_task(client.start(common.config["token"]))

Running the web-server

web_server.run(loop=loop, debug=True)

#

don't know if its the best way, but it seems to work

#

(very timely response, I know)

candid basalt
#

Also it says in the docs that it patches asyncio event loop implementation. I'm not sure what exactly it does, but it may eventually get your bot into trouble if it happens to stumble upon such patch.

scenic barn
#

hm, alright... so, I should switch away from quart? or in other words, just use flask and start the server as its own instance?

meager anchor
#

the latter, yes

#

use something else than flask‘s builtin server as the production server though

scenic barn
#

okay then, thank you for the help!

upbeat forge
#

I am doing django. And I am wondering, how to i make, When I press a picture, it show that picture and comment about it. Should I use as_view?

#

Or is there better way

#

🤔

upbeat forge
#

Thats my plan