#web-development
2 messages · Page 17 of 1
RIP
Run Docker for Windows
Easy to setup
Then you can just put your code in a nginix container I think
shit's getting complicated just to deploy a damn app loll
Deploying apps the right way was never easy. =]
Fairly easy with just javascript and php
10 years ago this would require a team
It's easy to forget just how complicated this all is "under the hood"
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
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.
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
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...
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)
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
Did you check out the tutorial?
If you use the manage.py commands it will usually give a good structure
Yes
python manage.py startapp
https://www.djangoproject.com/start/ should get you started, it has everything you need to get a project up and running.
@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
Which IDE do you use?
pycharm
It might mean they are not staged for commit if you are using Git or some other VCS.
Well you can stage them for commit by selecting and pressing ctrl+alt+a, if I'm not mistaken.
yup used command line, pushing them made them normal again thx
👍
hey guys quick question
is there way to host a flask website for free?
i only want to host it for a school project
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.
@rough magnet try this: https://www.pythonanywhere.com/pricing/
Plans and pricing : PythonAnywhere
I used their services for a while - they are rather good.
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?
Did you allow it though windows firewall?
It blocks all inbound connections by default
yeah i figured it out thanks
i can access it locally within the same network now
but not publicly though
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
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.
how come this doesnt work <a class="btn btn-primary" href="{{count_url}}" alt="See details" role="button">Link</a>
"Not found: '/href='"
!t 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.
What framework is it, what templating engine is it?
Where is the error displayed, i.e. what outputs it?
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?
What's some of the best looking and simple CSS frameworks out there?
bootstrap
And it's numerous derivatives.
Any alternatives?
@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
can a django wizard tell me the difference between those two? thanks!
Seems like assertNotEqual is a method, and assertNotEquals is a function?
just warped there with my wheel click (goddamnt i love pycharm)
i think they're the same
they are the same, assertNotEquals is deprecated
not really django-related though, they're related to unittest
thank you
and by that I mean what do I put in
{% url '' %}
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?
Hi I fixed it. I decided to change to a model choice field
Nice, and you fixed (1) as well?
Awesome!
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
nvrmind think i got it
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?
Forbidden (CSRF cookie not set.) Is this a client issue?
It depends. Most probably you forgot to add {% csrf_token %} to your form template.
would i need a form template since im only using django as a server and not for browsing?
you will either have to disable csrf or something else that escapes me at this time
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
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
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
could be a circular import
there are only 2 reasons for import error:
- circular import
- thing is not in the python path
yea i got it. multiple copies inside and outside of the vert
its now running but can't hit it from web browser.
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.
@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
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.
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
Anyone have any thoughts on what I'm missing?
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
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
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
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;?
Yeah
def postRequest(request):
if request.method == 'POST':
print(request.POST)
return HttpResponse("Ok")``` fixed it typo...
You mean @csrf_exempt?
is sudo systemctl restart myproject the propery way to make updates to a website?
that is the proper way to restart a systemd service
and say i just want to change some html how what is the proepry way to get it to reload there?
that entirely depends on how you are running it
nginx,uwsgi,flask
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
@calm solar you copy the html files to where uwsgi reads them - that should be enough
@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
that only works if you have a init script or systemd service with the compat thing iirc
thanks @meager anchor i'll take a look at those docs this morning
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?
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
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 :/
you'd have to create it as a new field in your model, set it to be a Boolean (True or False)
(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
I don't really know what you mean by "signals" I'm afraid
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
Thank you so much Joseph, I really appreciate your help!
ok so
in your article model
you need a field with the type models.BooleanField(default=False)
call it visible or published or whatever
Understood, that's what I was thinking too...Go on. Thanks again
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
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?
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?
published_articles = Article.objects.filter(published=True)
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
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)
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
No worries, please take your time
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?
JFC...I think I just thought of something
Give the form two buttons. Save and Publish.
yep
And then do something like
if the user wrote this article but its not published, display to them anyways
Maybe?
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
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
Thank you so much!
No problem
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
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
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
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
Have you read the Django book?
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)
I haven't really read your question, so this might not help, but here it is anyway
Try taking a look through that?
@ripe pecan , this answers part of my question so thank you!
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?
How can l fix it to that?
I'm not sure what the context is... How are you getting that data
From my client
Oh oops didn't see that
Doesn’t make sense that it changes from “ to ‘ that tho pretty confused
Which version of python are you using
3.7
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
json.loads(request.body)
Ok
Also, I think part of the problem may have been you were doing print(str(body)) rather than print(body)
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 ""
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?
@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
@gritty halo huh.. I didn't know that, thanks for letting me know
@calm solar how does it change?
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
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
How to detect if its a mobile connection in django?
Mobile connection or mobile device?
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
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
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
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
Do you have an isPublished field in your model?
That is example. Are you familiar with django_extensions?
Would you like me to post my model code?
I am not familiar with django_extensions
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)
@kind steppe Are you free by chance? 😃
I am here, hello
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
Anyone?
Is the best option for web development using python Django?
Depends on the scale of your project
I would recommend Django...but, full disclosure, I use Django almost daily so I'm biased
There's quite a few depending on your needs
Django and Flask are the two big ones
Django is not going anywhere
I'm interested in this: https://vibora.io
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
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
Hi folks, just found this on github
https://github.com/tiangolo/fastapi
anyone tried it before
looks cool, especially swagger generation
but I'd prefer opposite way, when it generates some stubs using a swagger
How good is the udemy course on Django? I pirated all of it's videos recently
!warn @native tide I told you not to discuss piracy on this server.
:ok_hand: warned @native tide (I told you not to discuss piracy on this server.).
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
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 ?
@modern vale why poll? Is there no way to subscribe to changes? I feel polling could be expensive
@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
how are you thinking of doing the polling?
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
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.
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
Right, but if you're just serving up a template, you'll only be notified about the changes on page reloads. Is that okay?
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.
- Can I use python to create my own MVC model without Django and Flask?
- Will it be feasible and good option to create my own MVC and not using Django or Flask?
Yes, probably no.
@candid basalt Did you ans my question?
@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
If you want to build it yourself from the ground up - I'd start with https://uwsgi-docs.readthedocs.io/en/latest/WSGIquickstart.html
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.
You can also go for something like https://www.tornadoweb.org/en/stable/ if you like.
@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
How can I change the default template folder
I've been searching online but none of those links has helped me solve the problem
Default template folder of what? Framework? Lib?
People please be more descriptive
Flask sorry 😅
@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
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}")```
check if you're using python 3.6
Ohh. K that's why.. thanks 😄 👌
@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?
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
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
Is that not limited by the same origin policy?
I got a couple of issues with URLs
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.
you where told this before, please read the message and ask your question
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?
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?
@candid basalt No, I don't think so
I think server you are trying to post to has to cooperate via sending appropriate headers.
Yeah, maybe you're right. Even for GET requests?
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. 👍
@ripe pecan How do? :/
So you have a VPS hosting your app and you'd like to connect a domain to it?
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?
@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
@modern vale yup, if you need any more help, lemme know
Git is a distributed version control system. Every dev has a working copy of the code and full change history on their local machine, by Linus Torvalds
@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.
Yes it does 😐
I've hosted my apps on Heroku with custom domain for free
Don't you have to input your bank details though?
@modern vale
Also, doesn't Heroku have a limit of 500hours or something.
Anybody have a good tutorial to dynamically updating pages with Django channels?
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"
I think using web sockets might be overkill, but maybe not idk
Can u use jquery to update the page?
I have no idea where to start 😐
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
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
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?
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
Thank you, ill check it out
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.
Im sure there might be someone to answer your question, just ask @abstract orbit
!t 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.
how can you get an error message when the login details in django is wrong
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
can you show the error trackback?
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
@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'
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
Gimme a sec, I'll upload the full thing
Here you go: https://paste.pythondiscord.com/jakohuvuha.py
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
what your darwinChecker should do?
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
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
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.
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
needed json response got it
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)
Flask/uwsgi. The only way I can get my templates/py/mysql to show updates is to ```sudo systemctl restart myproject
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
I bought datatables it seems interestinig
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?
Try this?
@last forge
@ripe pecan that looks like it's only dealing with the date, unfortunately, not a date and time on that date.
I mean if you have a datetime object you should still be able to use that approach
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.
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
.
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
@wary mantle these are both solid.
https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world
https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-uswgi-and-nginx-on-ubuntu-18-04 and
@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!

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
when paypal tells you your json is malformed but jsonvalidator says its valid D:
does anyone have experience with datatables and django?
!t 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.
I'd recommend using gunicorn behind nginx as described here http://docs.gunicorn.org/en/stable/deploy.html#nginx-configuration
can someone explain to me what ElasticSearch really is ?
@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.
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
Oh ok. I'll check it out. Thanks!
So does that mean I can take app.run out of the code?
Willing to pay somebody with django and datatables knowledge 
@modern acorn Elaborate on the problem and maybe someone can help you without paying.
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
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
Django default admin is decent for editing table-like data.
Also I believe there are libs for Django datatables integration.
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
It's about the same as any other python uwsgi application - nginx+gunicorn works fine most of the time.
@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
@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)
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.
@gritty halo I haven't got any good tutorials handy, so google would be your best bet here.
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)
@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.
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
PythonAnywhere or Heroku for Flask?
Which is better for the price?
Why not AWS Lambda?
Quite complicated to setup from what I've heard. @coral ridge
I'm running into this exact problem with my django app and nginx, but I don't understand the solution here.
https://stackoverflow.com/questions/48594306/nginx-default-page-showing-cannot-get-app-to-display
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
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 !
Hey.
https://github.com/discordapp/discord-oauth2-example/blob/master/app.py
So I was testing that out ^ , although, when I login, it just gives me an error. Does anybody know why this is happening?
should that go in #303906096458891264 ?
Eh, I don't think so. #303906096458891264 is for bots, right?
@wary mantle did you add your redirect url to your application?
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)
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
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.
Can you show the server code?
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
Yeah I know that will happen. But I am not getting a single message
https://i.imgur.com/JflMToG.png it's just this, my program has not even exited yet
Hmm I've never used ws with aiohttp
https://stackoverflow.com/questions/47701854/aiohttp-websocket-client-and-http-server I found this as well, when I was trying this with aiohttp websocket client, but that did not help either.
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.
Just to be clear, you're sending a message right?
yes
Cause your client code is only receiving
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.
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
hm, I can try to look into that, good point.
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
It does have receive, and it works fine
Ok, so not only does the server print but client also receives it
I think my suspicion is correct upon further research
Hm yeah, when I tried sending from the python client it did not pop up on the extension
Oo thank you, that'll maybe be it. I'll give it a try, thank you kindly. 
You're welcome. Definitely follow hubo's advice in the comments there
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
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?
And here are two questions like what I am trying to do, if that helps.
https://stackoverflow.com/questions/8153875/how-to-deploy-an-https-only-site-with-django-nginx
https://security.stackexchange.com/questions/8964/trying-to-make-a-django-based-site-use-https-only-not-sure-if-its-secure
My original question was how to enable HTTPS for a Django login page, and the only response, recommended that I - make the entire site as HTTPS-only.
Given that I'm using Django 1.3 and nginx, wha...
In Django i want to pass a javascript variable inside of formURL: "{% url 'URL' javascriptvariablehere%}"
how can i do that
@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
Oh, nvm. I forgot add in /callback to the redirect URL. Thanks!
There is something I don't get.
Intended behavior: https://docs.djangoproject.com/en/2.1/ref/models/instances/#get-absolute-url
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?
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
altho there is files in the dir http://prntscr.com/m08t7z
nvm fixed forgot to add staticfile dirs into cfg my bad
[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?
I put a config file for sites-enabled like this https://stackoverflow.com/questions/11693135/multiple-websites-on-nginx-sites-available but how do I systemlink it so that nginx can restart correctly?
You should put config files into sites-available directory instead.
then
cd sites-enabled
ln -s ../sites-available/your-config-name.conf ./
@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.
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.
@candid basalt so I do not need a config file in both sites-enabled and sites-available?
@coral ridge thank you.
@native tide config file in available and symbolic link to it in enabled.
ah, I see.
I reinstalled the server to start over, should I just delete the /etc/nginx/sites-available/default ?
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
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.
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?
yes
<div style="display: flex;"> Item1 Item2 Item3 </div>
<div style="display: flex;"> Item4 Item5 </div>```
I was able to get it working with another way 😄
sounds good
I gave up on trying to get datatables editor to work in Django
went with crud instead, works just as good
@modern acorn what exactly did you use?
I mean what libs for frontend and backend.
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
pass is a keyword, you can't use that there
Ohh, yeah. Thanks!
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
So basically the schema will be altered dynamically?
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
You want a dynamically updating schema?
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.
It seems like my error is this exactly
https://stackoverflow.com/questions/39119337/django-with-gunicorn-and-nginx-http-500-not-appearing-in-log-files
but their solution is not a solution for me at all
This question also seems accurate to my problem https://stackoverflow.com/questions/38028099/500-internal-server-error-when-deploy-django-with-gunicorn-and-nginx?rq=1
but my app does not have user authentication, or users logging in at all
so my problem is not there
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
i have django and static angular project when i turn debug to off in setting.py i get error 500 (Server Error (500) and when i check my email it say:
Internal Server Error: /
ValueError at /
Miss...
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
The order in which teams were added to the match/
My datatable isn't case insensitive
ive tried to change the settings
The case insensitive setting didnt worrk but "search": {"regex": true}, did
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
Or is this a common problem if your static files arent handled by apache
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?
@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
@candid basalt Yes
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.
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
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
some of the issues about sanic are in this thread https://www.reddit.com/r/Python/comments/876msl/sanic_python_web_server_thats_written_to_die_fast/
229 votes and 40 comments so far on Reddit
it's quite an old one though so they may have been fixed
I think it's being actively developed
And things are being fixed
Though I'm not certain
@covert radish You would need to makemigrations and then migrate after. do you have something set up for that?
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
doesn't matter
AttributeError: 'AnonymousUserMixin' object has no attribute 'username' has anybodt experienced this error before?
and what are common problems causing it?
But, it seems like you're looking looking at a mixin instead of the object.
What's the code that causes this error?
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
Oh okay, you're not using Django
only flask
def validate_username(self, username=username)
username=username, what is the RHS username
oh yes that was something I was wondering if it really was nescessary
username = StringField("Username", validators=[DataRequired(),Length(2,20)])
is username a global var or a class variable?
class
do you not need to do self.username?
Sorry, I haven't ever used Flask, but I'm trying to help 😛
@kind steppe I personally don't trust Sanic 😅 hug isn't async though, is it? ^^'
What about this?
ah of course responder
I completely forgot about that
I've been meaning to make use of it
Is that async?
I'm not a fan of the font :/
Inconsolata is great :) and it's free
@kind steppe
And wow
responder is great :o
almost too good to be true
oh that is a nice font, thank you for the recommendation!
@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
basically in an HTML user friendly form
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
@covert radish I don't think I can offer any help beyond what the stackoverflow post has given
:/
Sorry
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
@ripe pecan it's cool fam thanks for trying :D imma keep punching this problem till i crack it :D
@glossy osprey is it a hidden field in the form?
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
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?)
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
Hmm I'm not sure, sorry :/
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...
If this were a permission error, it wouldn't be returning 404, right?
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?
Do you know how to press a button in HTML then activate a function in python with flask?
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
@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
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
Yeah, do what I said
- Add button using HTML
- Add an onclick event listener using JavaScript to that button
Okay
- When that event is fired, make a GET request using fetch to some predefined endpoint
- $$$
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.
Is there a trick to getting an alias in apache conf to include subdirectories? I think that's where I'm stumped here
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 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.
@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
<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
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 ?
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
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?
asynchronous javascript?
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',
]
Hey guys, I'm trying to learn Django. Any good book reccomendations?
Maybe I should start with the docs
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
In this Python Django Tutorial, we will be learning how to get started using the Django framework. We will install the necessary packages and get a basic app...
thank you
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
@native tide You should have a log file
where is the log file?
uh i think you have to set that up
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
@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
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
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
@native tide So your problem is python is in a virtual environment basically?
no, it's when accessing the admin part of the app
the virtual environment is running fine
What's different about the admin part of the app
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
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
oh, yeah. I've already fixed that by adding that path to nginx and setting the chown permissions correctly
Where are you getting the error then? in which log set
Could I just see what it says?
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
So the error is nginx?
nope
ok
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
I'm assuming you access the database using python right?
nginx is not like apache. it does not touch the database at all. but thanks for trying to figure this out with me
Anyways, does the Django config work normally?
nginx should still state somthing
it's documented
Like does Django work on your local testing site?
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
That's horrible.
(no offence, just feeling bad for you)
So you get no message anywhere, between python, gunicorn and nginx?
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
nope, I already fixed earlier internal server errors. Those had to do with gunicorn and nginx.
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?
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.
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?
It is not running with ./manage runserver. Therefore the error is not showing up in the terminal.
the custom 500 page is stated through django. Nginx does not see any of that logic.
How are you running python then?
gunicorn
So gunicorn will hold the logs in theory?
In theory yes, however it is not reporting any errors.
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.
gunicorn and Django have their own logging support.
I think just checking their documentation is probably the best?
There ya go
I'll mess with that for a bit
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
I still don't exactly know what the cause was, but resetting gunicorn fixed the unexpected behaviour
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
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
Hey, could someone help me? I'm trying to webscrape an image but the element in which the image url is , changes constantly
the class of the element is changing constantly? or is it the element itself?
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
@wraith trench - that's implemented in JavaScript
class changes
@shell lichen so there's no nice way to do that in models, or in admin file?
@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?
if the element is the same, then you can build the path by that
Got it, thanks, just though, that maybe if TimeField has this ability without custom coding anything,, so do other fields, but looks like not 😃
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 😃
In the dev tools you can select an element and copy the xpath. Whatever scraping lib should allow you to find elements by xpath.
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
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?
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)
Okay. Thank you for your input ❤
You can use CD services
My workflow is to code on my local machine, and then rsync necessary changes to the remote server when needed.
@somber burrow check out some CI/CD stuff life biogod mentioned
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
i have a webserver i run off my phone for offline web dev
(progrmmed in python ofc)
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?
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
How do you start flask and bot from the same file?
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)
The flask extension must be limited to creating routes, using the request and rendering templates. Any other more advanced functionality may not work.
https://pgjones.gitlab.io/quart/flask_extensions.html#flask-extensions
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.
hm, alright... so, I should switch away from quart? or in other words, just use flask and start the server as its own instance?
the latter, yes
use something else than flask‘s builtin server as the production server though
okay then, thank you for the help!