#web-development
2 messages · Page 196 of 1
arsenal is home, draw is draw, aston is away
if arsenal were to be clicked, that means draw and home are None type
Nevermind, Jinja got me. I usually never mix templating and js
leaving home
iv done exactly the same thing in python but ye idk why this is not working in JS
same logic
Hi I don't think tutorial for synchronous process queue in which process is processed one by one
I don't understand this statement. Are you saying you want it to be synchronous or you don't want a synchronous queue
I want synchronous queue
The main reason for a synchronous queue is to run one task at a time. The tutorial I sent you(although it asynchronous) shows how to prevent the user from running the same task until the task is completed. i.e the export task cannot be run twice by the user, only one export task can be run at once
I really need help with something
i want text to appern on image
i will send you the code
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
try z-index: -1;
where?
can you check the code once and tell then where to put?
on which image u want the text to appear on?
the showcase.jpg
did it work?
no
send a picture of ur page
wheres the image u want the text to be over, and which text
the drone image is the one i want the drone core paragraph
to be on
i increased the drone image size to make it cleare
r
try putting them inside the same div
whats wrong??
ur putting the photo in #showcase, but what is #showcase
ah ok i see
the reason for that is because <div class='showcase'> is above the nav bar
u need to put it under it
putting it above meaning it will push the navbar down
ok
@native tide i just had a look again on ur code seems i missed somethings. leave the showcase class where it is, but create another class at the end of that div and put ur image inside there
after line 44, create a new class and put the image in there instead
works?
ok
might wanna adjust margin-left too
yes i want to centre align
i did that
0k its finally coming together now
nice
does anyone know of a maintained css minifier? I see a lot of projects but they're all unmaintained for at least a couple of years. I know django-compressor has one but I don't want to install all of that just to minifiy a css file.
I generally use hugo (ssg) to minify css directly in html templates, but this doesn't look bad https://www.npmjs.com/package/clean-css-cli
mmm yeah I have a good choice if I don't want to limit myself to Python, but unfortunately I do... but I think I will probably end up installing yuglify or something
Hi. Im trying to load my css style but it doesnt work
like load
<link rel="stylesheet" href="css/styles.css">
In the
<head>
</head>
in flask?
from django.db import models
class Post(models.Model):
sno = models.AutoField(primary_key=True)
title = models.CharField(max_length=255)
content = models.TextField()
author = models.CharField(max_length=13)
slug = models.CharField(max_length=130)
timeStamp = models.TimeField(blank=False)
DateStamp = models.DateField(blank=False)
likes = models.IntegerField(default=0)
dislikes = models.IntegerField(default=0)
def __str__(self):
return self.title + ' by ' + self.author
but when i try to see the posts in admin panel
i get this error
OperationalError at /admin/blog/post/ no such column: blog_post.likes
no
Hi, I'm using Django and have a for loop which creates a new row and modifies other rows in few tables
I want a rollback for only that item currently of the loop to rollback if it fails
for x in abc:
with transaction.atomic():
something()
this would be the right way?
thank you, I think I will look into design patterns and architectures!
So I build a small Data Science Application, for which I use flask to provide it as a REST API. I'm currently doing this by simply starting the dev server of the app in a tmux console on Ubuntu Server. Now I'd like to profile it's memory consumption. Just to get an rough idea what kind of resources would be required should I put it in a dedicated cloud.
@app.route('/half',methods=['POST'])
def function():
return request.data``` how do i get the data posted ?
thats my attempt btw , a fail 😔
Has anyone ever developed with flask and scss? If so was it difficult to configure?
Looks like flask to me - guess you're looking for request.get_data() or request.get_json()?
perhaps , let me test it
Hello
does anyone know how to pull data from a form in fastapi
from fastapi import FastAPI, Request, Form
from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse
app = FastAPI()
templates = Jinja2Templates(directory="templates/")
@app.get("/")
async def root(request: Request):
return templates.TemplateResponse("index.html",
context={
"request": request,
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Crypto Watch Command Centre</title>
</head>
<body>
<form>
<label for="currency">Currency:</label><br>
<input type="text" maxlength="3" placeholder="ABC" name="currency" id="currency" autofocus><br>
<label for="amount">Amount:</label><br>
<input type="number" placeholder="123.456" name="amount" id="amount" min="0" step="0.00000001"><br>
<label for="status">Status:</label><br>
<input type="radio" name="on-off" value="on"><label for="on">On</label><br>
<input type="radio" name="on-off" value="off"><label for="off">Off</label><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
whats put into the form needs to be a variable
<form action = '/Sign-up' method='POST'>
you need to set Action"Which route will recieve this data" and a Method which always POST to the form tag
just a sec i will send you an example
oh okay thank you
ok and how would you recive ti
like in pyhton
I'm sorry this is my first time doing something like this
with python flask we recieved the data from the backend by request.form.get(name)
where do they pass the username tho
in the <input> tag
I'm using fastapi tho
oh i meant like in the query
i'm trying to do something like that
you mean the User.query.filtyby?
FastAPI framework, high performance, easy to learn, fast to code, ready for production
maybe , can i see those docs ?
https://www.youtube.com/watch?v=dam0GPOAvVI Very good tutorial and this is the code and files for the project https://github.com/techwithtim/Flask-Web-App-Tutorial
In this video, I'm going to be showing you how to make a website with Python, covering Flask, authentication, databases, and more. The goal of this video is to give you what you need to make a finished product that you can tweak, and turn into anything you like. We're going to also go over how you create a new user's account, how you store those...
oh no , i'm just trying to get the date from the query or url like make the user pass data like wise
https://cool_api/data/something/something2
ahh
I have a website here live on heroku http://symor-richaards.herokuapp.com/. You can successfully add a photo, and when you refresh the page it will appear. But when I make changes in the code and push to heroku, the image disappears and I see a 404 error in the console for all the photo's added. The code for the entire website is here https://github.com/Beefy-py/symor-richaards
I just found out that the images not only disappear when I push changes. But also when the herokuapp sleeps and that is every 30min or hour IIRC
Where exactly do the images go? When you upload them they are saved to a remote file? And when they disappear, those files are getting actually deleted?
I think so
they are being put in the build folder py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') if (DEBUG) else os.path.join(BASE_DIR, 'build', 'media')
I think heroku creates a new build folder everytime it goes to sleep and wakes up.
that's why the images disappear.
Am I wrong?
Possible, especially if you're on a free tier of service, did you check their documentation?
no
In Django Rest Framework, how do I deserialize a nested JSON?
Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name.
from django.urls import path
from . import views
from django.contrib.auth import views as auth_views
app_name='users'
urlpatterns = [
path('register/',views.register,name='register'),
path('login/',auth_views.LoginView.as_view(template_name='users/login.html'),name='login'),
path('profile/',views.profile,name='profile'),
path('profile-create',views.profile_create,name='profile-update'),
path('logout/',auth_views.LogoutView.as_view(template_name='users/logout.html'),name='logout'),
path('password-reset/',auth_views.PasswordResetView.as_view(),name='password_reset'),
path('password-reset-done/',auth_views.PasswordResetDoneView.as_view(),name='password_reset_confirm'),
path('password-reset-confirm/<uidb64>/<token>/',auth_views.PasswordResetConfirmView.as_view(),name='password_reset_confirm'),
path('password_reset_complete/',auth_views.PasswordResetCompleteView.as_view(),name='password_reset_complete')
]``` urls,py
why this error
Django rest framework question, how would I serialize a property of a model which will be returning a list of models?. Thanks
does anyone know how to deploy in a wsgi enviroment with gunnix or literally jus any environment that supports web-sockets
I'm getting error:
{
"detail": "JSON parse error - Expecting property name enclosed in double quotes: line 8 column 3 (char 184)"
}
from incoming JSON - how do I address this if this is the inbound data?
{
"session_id": "e2085be5-9137-4e4e-80b5-f1ffddc25423",
"category": "page interaction",
"name": "pageview",
"data": {
"host": "www.consumeraffairs.com",
"path": "/",
},
"timestamp": "2021-01-01 09:15:27.243860"
}
from API
It's not valid JSON. You can check online with a validator.
So, one thing you can do is edit the JSON inline if you can't get the change to happen on who sends it.
Here for instance the error is actually the trailing , after path I believe (the error is kind of incorrect or misleading because its saying that cause the comma means "there should be a property here enclosed in double quotes" but instead there is nothing.
However, a trick you can try (and I tested it with your data above) is to first put the response into a python dict, THEN dump it as json because that inbound data above IS a valid dict (cause python doesn't mind the trailing comma obv). And then you can turn the dict into json (if you really do need it as json).
Weird, huh?
But of course, you may just want to keep it as a dict and do stuff with it. All depends. 😉
((You may need to use ast.literal_eval to turn your initial string into a dict in the first place -- all of these steps simply because the json you're being sent is invalid. Consumer Affairs should be ashamed. :D))
Thank you!
I actually noticed a further issue, the JSON elements change, and likewise they are sometimes double nested
how do I handle this if I don't know the fields/content ahead of time?
hey guys, im using django and a create class based view, how am i able to still post despite one of the forms being empty?
Well, depends on what you're building and how much change do you mean?
Just that sometimes the data is "double nested" but still the same data? It could be that sometimes some properties have single values so the json is flat, but sometimes multiple values so they return an array instead.
You'll need to take care of that logic on your side. Check for array, if not, process as single value. Or any other rules like that. There is a pattern to it yeah or are you saying it seems random how they nest?
Can you share some code?
And are you asking how you CAN do that, or are you asking WHY it happens?
how the hell do meta tags work, I was stuck for a few hours making my website not look crap on mobile, and eventually adding a <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" /> fixed everything
well the default is to allow a form to submit regardless of data being in it unless you set them to required and have validation
should i be looking at the form then?
because when i attempt to submit only one field it says that the field from the view form is needed to be filled
Ha, yeah, they're just instructions to the browser on how to handle the view port. Lots of other meta tags are just informational for various reasons.
Be careful with user-scalable = 0 cause you're limiting expected functionality (pinch zoom)
i use the post method to update a previous object
Your view class that has the form in it might be setting up the fields to be required. I'm sorry, I don't use Django, but with Flask and WTForms you. build the form class and. can set things like "required"
I may be confused about what you're asking now.
pinch zoom not being available here is right :)
Actually, if you visit https://stash.martmists.com/audio_processing/introduction is there anything you see UI/UX-wise that I should change?
yeah my bad for the explanation, I essentially have a 2 fields, one for updating another object and one for creating a new object. Im using the POST method to update the already made object while the rest of the class view is used to make a new object
do somebody know how to use "flask-menu" package?
i need a simple example
..
done
thx
How to detect that device will able to screenshare though WEBRTC as mobile device cannot share screen in browser
Anyone know if paycopg2 works with 3.10? Isn’t listed as supported in on the website and am getting an import error. Not quite sure how to downgrade back to 3.9 to be on a supported version
i am working with django auth views the reset password feature so the thing is i have all email things setup then too it's showing error
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = os.environ.get('myemail@gmail.com')
EMAIL_HOST_PASSWORD = os.environ.get('mypass')```
I think to fix that you need to go into your google settings and allow less secure apps to have access @dusk portal
I ran into the same problem a while back
Ah
Got this error
Help please
Did you migrate your changes to the model?
yup
“makemigrations” too?
yes
Try deleting your database then applying migrations again
@civic crater your sqlite.db file
Nothing changed
Still getting the same error?
yes
Ok, try deleting the migrations you’ve made so far and the db.sqlite3 file again, then migrate/makemigrations one more time
sorry?
I might be getting ahead of myself, did you add the “likes” column after you first created your model?
yes i edited the model
Ah ok, and did you edit the view that uses your model too?
Trying to figure out why you’re getting that error
https://stackoverflow.com/questions/26312219/operationalerror-no-such-column-django
@civic crater this can help
I am very new to django and was able to finish the tutorial on djangoproject.com without any errors. I am now going through the Django REST framework tutorial found at http://www.django-rest-framew...
this one worked
https://stackoverflow.com/a/27286896
Thanx @split steeple
I am very new to django and was able to finish the tutorial on djangoproject.com without any errors. I am now going through the Django REST framework tutorial found at http://www.django-rest-framew...
hi
const game = {
elements: {
progressLabel: document.querySelector("#progresslabel"),
progress: document.querySelector("progress#file"),
levelBtn: document.querySelector("#btnLevel"),
cookieBtn: document.querySelector("btnCookie")
},
level: parseInt(localStorage.getItem("level") ?? 1),
cookies: parseInt(localStorage.getItem("cookies") ?? 0),
multiplier: parseInt(localStorage.getItem("multiplier") ?? 1),
clicks: parseInt(localStorage.getItem("clicked") ?? 0),
prestige: 0,
rebirth: 0,
requiredClicks() {
return game.level * 250 + game.multiplier * 50;
},
nextLevel() {
return parseInt(game.level + 1);
},
load(){
if (game.cookies > game.requiredClicks()){
game.elements.levelBtn.style.visibility = "visible";
}else{
game.elements.levelBtn.style.visibility = "hidden";
}
},
reset() {
game.level = 1
game.cookies = 0
game.clicks = 0
game.multiplier = 1
localStorage.removeItem("level");
localStorage.removeItem("cookies");
localStorage.removeItem("multiplier");
localStorage.removeItem("clicked");
},
updateProgress() {
game.elements.progress.value = game.cookies;
game.elements.progress.max = game.requiredClicks();
},
levelingEnabled() {
if (game.cookies > game.requiredClicks()){
game.elements.levelBtn.style.visibility = "visible";
}else{
game.elements.levelBtn.style.visibility = "hidden";
}
},
updateStorage() {
["level", "cookies", "multiplier"].forEach((key) => localStorage.setItem(key, game[key]));
},
how would i make it so when i click on cookieBtn
it does a function
click() {
game.cookies += game.multiplier;
console.log("h")
game.updateProgress();
game.updateStorage();
game.levelingEnabled();
},
that function
Events are actions or occurrences that happen in the system you are programming, which the system tells you about so you can respond to them in some way if desired. For example, if the user selects a button on a webpage, you might want to respond to that action by displaying an information box. In this article, we discuss some important concepts...
Ty
cookieBtn.addEventListener('click',function(){
})
np
after identifying cookiebtn
visit the page it will show you lots of cool stuff u can make with js eventlistners
const cookieBtn = document.querySelector("btnCookie");
cookieBtn.addEventListener('click',function(){
// your functions
})
yea
you can actualy make any eventlistener to any where in page
class Channel(Model):
""""A channel of a ChatGroup"""
chat_group = models.ForeignKey(ChatGroup, on_delete=models.CASCADE)
name = models.CharField(max_length=50)
position = models.IntegerField()
description = models.TextField(max_length=255, null=True, blank=True)
created_at = models.DateTimeField(validators=(validate_iso_timestamp,))
``` In this model, how do I make the `position` field unique per `ForeignKey`? So if there is already a ForeignKey to a `chat_group` with the same position it will raise an error?
I'm using flask, and I'd like to render a CSV into a table on the same directory as the server (with something like datatables?) is there an example? seems like something that should be simple, but I'm missing it. 😦
could anyone recommend some nice django community
mysql or postgresql or sqlite?
thanks I already solved it, I used a models.UniqueConstraint
okay
In template C:\Users\Raghava\Desktop\project_one\contact\templates\contact\contact.html, error at line 8
Invalid filter: 'as_crispy_field'
1 : {% extends 'profolio/base.html' %} {% block content %} {% load
2 : crispy_forms_filters %}
3 : <h1 class="ml-3">Contact</h1>
4 : <div class="content-section">
5 : <form action="" method="post">
6 : {% csrf_token %}
7 : <div class="col-lg-6">{{ form.email|as_crispy_field}</div>
8 : <div class="col-lg-6"> {{ form.subject |as_crispy_field}} </div>
9 : <div class="col-lg-6">{{ form.message|as_crispy_field }}</div>
10 : <input class="btn btn-dark col-md-2 ml-3" type="submit" value="Submit" />
11 : </form>
12 : </div>
13 : {% endblock content %}
14 : ```
I get this error but when I remove {% extends 'profolio/base.html' %} {% block content %}{% endblock content %} It works fine
I want to why its causing this error while using template inheritence
hii, i have to do a django project and i have no inspiration of what topic to choose, any ideas?😋
try to make a new freelancing platform
As a newbie in Django and struggling with projects vs. apps (and also the repetitive directory names https://github.com/paxcodes/book_WebDevWithDjango/blob/main/docs/notes.md#scaffolding-a-django-project-and-app-repetitive-folder-names), I find this resource (chapter 3 of the Django book) really helpful. In my first personal project with Django, I'm going to name my folders based on (but not exactly) his suggestion -- see screenshot.
I wonder what experienced Django devs think about this. Have you seen projects that follow a similar pattern? The few Django projects I know don't follow this but rather have repetitive directory names. I know I'll get used to the repeated directory structure but it will take some time.
If you can help with my inquiry, please @ me so I get to see your responses! 🙂
class Investor(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
views
investor = Investor.objects.get(user_id=request.user.id)
where is this user_id defined in Django? (i searched but only found id and pk but not user_id)
django.db.utils.OperationalError: could not connect to server: Connection timed out (0x0000274C/10060)
Is the server running on host "...redacted..." (123.456.789.11) and accepting
TCP/IP connections on port 1234?
``` I am trying to connect to the postgresql database hosted on heroku but I get this error, I checked and the server is available. Thanks
can someone help me implement this
into django
I did but cant link html with css
looks like this
ok got it working
damn this channel is so dead
what do you mean?
<link rel="stylesheet" type="text/css" href="{% static '/css/main.css' %}">
yes yes I fixed it already thank you
ah ok
Im struggling right now with implementation of login feature to this
{% load static %}
<link href="{% static "users/css/style.css" %}" rel="stylesheet">
<form autocomplete='off' class='form'>
<div class='control'>
<h1>
Sign In
</h1>
</div>
<div class='control block-cube block-input'>
<input name='username' placeholder='Username' type='text'>
<div class='bg-top'>
<div class='bg-inner'></div>
</div>
<div class='bg-right'>
<div class='bg-inner'></div>
</div>
<div class='bg'>
<div class='bg-inner'></div>
</div>
</div>
<div class='control block-cube block-input'>
<input name='password' placeholder='Password' type='password'>
<div class='bg-top'>
<div class='bg-inner'></div>
</div>
<div class='bg-right'>
<div class='bg-inner'></div>
</div>
<div class='bg'>
<div class='bg-inner'></div>
</div>
</div>
<button class='btn block-cube block-cube-hover' type='button'>
<div class='bg-top'>
<div class='bg-inner'></div>
</div>
<div class='bg-right'>
<div class='bg-inner'></div>
</div>
<div class='bg'>
<div class='bg-inner'></div>
</div>
<div class='text'>
Log In
</div>
</button>
<div class='credits'>
<a href='https://somelink.com/' target='_blank'>
Jak sie chcesz rozerwać
</a>
</div>
</form>```
hmm I dont even know what to look for
damn that looks sexy
the 3d
😍
damn
what is the issue?
I did whole project and now trying to make new one by myself
but without guidance Im lost after initial setup
.
well I dont know how to take this input and put it into username and password variable
do I need to make User model first?
django?
yes
damn
django has django.contrib.auth
but like
not very good at django lmao
oh rip
you have to create a form
let me find the html
he creates a form as a post method
def loginPage(request):
if request.user.is_authenticated:
return redirect('home')
else:
if request.method == 'POST':
username = request.POST.get('username')
password =request.POST.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('home')
else:
messages.info(request, 'Username OR password is incorrect')
context = {}
return render(request, 'accounts/login.html', context)```
He then sets this up in his views.py
find what you are missing.
I cant make the login button to perform post
{% load static %}
<link href="{% static "users/css/style.css" %}" rel="stylesheet">
{% csrf_token %}
<form method="POST" action="" autocomplete='off' class='form'>
<div class='control'>
<h1 id="form-title">
Sign In
</h1>
</div>
<div class='control block-cube block-input'>
<input name='username' placeholder='Username' type='text' class="form-control">
<div class='bg-top'>
<div class='bg-inner'></div>
</div>
<div class='bg-right'>
<div class='bg-inner'></div>
</div>
<div class='bg'>
<div class='bg-inner'></div>
</div>
</div>
<div class='control block-cube block-input'>
<input name='password' placeholder='Password' type='password' class="form-control">
<div class='bg-top'>
<div class='bg-inner'></div>
</div>
<div class='bg-right'>
<div class='bg-inner'></div>
</div>
<div class='bg'>
<div class='bg-inner'></div>
</div>
</div>
<button class='btn block-cube block-cube-hover' type='button'>
<div class='bg-top'>
<div class='bg-inner'></div>
</div>
<div class='bg-right'>
<div class='bg-inner'></div>
</div>
<div class='bg'>
<div class='bg-inner'></div>
</div>
<div class='text'>
Log In
</div>
</button>
<div class='credits'>
<a href='https://something.com/' target='_blank'>
xxx
</a>
</div>
</form>```
use the built in one in django.
im making one rn
I dont understand how to implement forms*
def register(request):
form = UserCreationForm()
if request.method == "POST":
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
context = {"form": form}
return render(request,"project/register.html", context)```
<!DOCTYPE html>
<h3>
<form method="POST" action="">
{{form.as_p}}
<input type= "submit" name = "Create User">
</form>
</h3>``` thats how far i have gotten
bruh I think this shit aint for me at this point
holy fuck
I dont even know what to look for
Im just gonna watch more tutorials
Checkout my new Django Course!
https://dennisivy.teachable.com/p/django-beginners-course
Adding User Registration/Signup and user login functionality along with restricted pages.
Follow me on Twitter: https://twitter.com/dennisivy11
Linkedin: https://www.linkedin.com/in/dennis-ivanov/
Source Code & Live Demo: https://dennis-sourcecode.herokua...
because documentation and everything else is just impossible to read for me at this stage of knowledge..
yes exactly what Im watching right now
same
lmfao
bloody hell
took me 10 mins as i didnt realise i spelt csrf_token as crsf_token...
well I just want to make website with login and then u can upload files there
so me and my friends can use it
I have no fucking idea
how to make html preset with django
i cant do html so save my life lmao
gl creating the upload area
lmao
ye...
fun project lmao
maybe flask would be better
well
noooooooo
dont use flask
trust me
it made me wanna die

django is so much better, as it is built better
flask is good for simple stuff
but django is more proffesional
the video is from a series, meaning you have to code all the way up to where this is used.
no I did what he does
but when I replace the <input> with form
it fucking removes the whole thing
holy fuck this makes me furious
c++ was more fun
bro
leave the <form>
and just add <input type="submit> at the bottom
and it will send a post request
then log this post request, add it to a db then say its successful
with flask, you have to create your own db in .json file and put it in there.
where at the bottom
before </form>
can I make drag and drop of files
without javascript
dictionary ={
"name0": "51",
"name1": "89",
"name3": "56"
}
json_object = json.dumps(dictionary, indent = 4)
class Data(Resource):
def get(self):
return json_object, 200 # return data and 200 OK
pass
api.add_resource(Data, '/users')
``` html ```html
<script>
$(document).ready(function(){
$("button").click(function(){
$.get("users", function(data, status){
alert("Data: " + data + "\nStatus:" + status);
});
});
});
</script>```
how do i display only for ex. name1?
hey im new can anyone please explain whats django
its web framework
thanks
someone help please
I would guess by replacing data with data['name1']... Does that throw an error or what?
What web framework are you using? I find it odd that you are serializing the dict into a string using dumps. Most web frameworks will let you return the dict directly.
Eitherway you may be able to manipulate the data how you want using https://www.w3schools.com/js/js_json_parse.asp
@native tide this makes some assumptions on how your framework is serializing the data though this may just work:
<script>
$(document).ready(function(){
$("button").click(function(){
$.get("users", function(data, status){
const obj = JSON.parse(data);
alert("Data: " + obj['name1'] + "\nStatus:" + status);
});
});
});
</script>
Why is it that almost every single python backend I've ever seen it seems as if it's excessively weighed down with a ton of stuff? It's hard for me to describe in detail, but coming from Node API development the difference is astounding. I started learning Flask, at first it seemed incredible, super basic and intuitive and easy to use. Then I went to github and started looking at some production ready projects and it's insane to me. There are all these extra files and there'll be like 20 config setting and all kinds of shit. A couple project I saw had a setting.py, a config.cfg, and a .env all in the same project. That's just one example that comes to mind right now, but it rings true for all Python backends I've seen. Can anyone explain this or help me understand why it's like this?
I moved to django for that reason among a few. To see if it would be a bit more easily structured
I couldn’t figure out how to separate flask code , I know it’s possible though .
I had some issues deploying my project - the Postgres database that heroku creates for the django orm existed but was completely blank . I took the opportunity to migrate my tables to MySQL and the authentication seems to be fine for now , I created a super user and can access the admin panel . I haven’t gotten into any serious crud yet , I at least wanted to make sure I could host the thing , so luckily I don’t have to rewrite anything
backend oriented python web framework ;b
performs great in backend, and quite poorly in frontend
I've looked into Django but my experience with it was less than stellar. About ~2 years ago I tried to build a "normal" Django project using the built in templating language and everything. It went well for the most part, but as soon as I want to deviate from something that wasn't within Django's paradigm it was a huge PITA, unlike with Flask or Express where it's much more extensible. Nowadays, I primarily do API dev with pure CSR apps on the frontend (react, etc) and Django seems like a poor choice for this. I know django-rest exist for this purpose but I've not heard much positive about it tbh
Hey, im trying to do a similar thing as the following link however i dont understand the JS. Can anyone sort of explain to me abit how it works. Much appreciated.
https://www.w3schools.com/howto/howto_js_filter_elements.asp
What i want to do is have 2 buttons, pending and resulted .
{% if pending == True %}
<!-- Display all pending bets once pending is clicked-->
{% else %}
<!-- Display all resulted bets once resulted is clicked -->
{% endif %}
need help with django db quering
im querrying the db with this command
images = Image.objects.all().filter(belonging_gallery=gallery)
but this is returning only 1 value
1 gallery has many images and different one
but im getting only 1 same image in all gallery
What's your image model look like?
trying to get my django app ready to deploy and setting the critical info to use system environement variables. When the terminal through VS Code tries to access them through os.environ.get('...') it doesn't work. When I do it in a normal cmd prompt it works. Any ideas?
this
class Gallery(models.Model):
group_heading = models.CharField(max_length=50)
group_desc = models.CharField(max_length=100)
def __str__(self) -> str:
return self.group_heading
class Image(models.Model):
image = models.ImageField(upload_to='uploads/%y/%m/%d')
belonging_gallery = models.ForeignKey(Gallery,on_delete=models.CASCADE)
multiple images are pointing to one 1 gallery
but getting only 1 image in filter
fixed
the backgroundproperty is a shorthand for various properties relating to background such as color, size, image, etc. you may be looking for background-image which would support the url function as value
the syntax highlighting on hastebin gives you a hint. notice how -6.j is highlighted green on the url line? do you know why? then take a look at how you've done font-family above: "PT Sans Narrow". you'd have to do something similar to that for the path passed into url(). in fact you're already doing that in the screenshot you sent earlier, perhaps you forgot to do it when changing background-image?
why driver.get() doesn't work in selenium?
I updated it and all
but it just opens the browser and doesn't open the url
nvm I fixed the problem, I had to install chrome driver
Just curious won't u add default field on image in class Image
N null blank field
class UserViewSet(viewsets.ModelViewSet):
serializer_class = serializers.UserSerializer
queryset = User.objects.all()
@action(detail=True, methods=("GET",))
def my_profile(self, request):
serializer = self.get_serializer(instance=request.user)
return Response(serializer.data)
``` I have this viewset, when I send a request to `http://127.0.0.1:8000/api/users/my-profile` (with authentication details) I get this response with a status 404 ```json
{
"detail": "Not found."
}```. I expected it to return json data. Thanks
Can someone here help me with my code? (HTML, CSS)
Don't ask whether someone could help you or not, simply post your question, if someone knows the answer to it, they'll answer it.
@umbral ledge
ok
No images are showing in my html
im using a flask server on linux while using chromium
im tryna do this for my project but i dont understand the JS
how can i make it were it doesnt show all but rather show certain things
hello
i am facing the same problem as yesterday
my image is not coming
send a picture
wheres the picture? and also show some code
add a / before images
no difference in output
background: url("/images/sky-view-6.jpg");
try that
add width: 100%; and height: 100%;
eh idk
maybe try renaming to skyview6 instead of sky-view-6
maybe remove the margin and padding u put or smt idk
@native tide are u tryna put the image in ur navbar? or body of ur page?
because currently it seems like u tryna put it in the navbar
body
then create another div at the end of #showcase div
and put the img in there
i told u this yesterday lol
after line 62 add a new div
then in css add the image to the div
where
oof
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Welcome to DroneCore</title>
<link rel="stylesheet" href="style.css" />
<link
rel="stylesheet"
href="path/to/font-awesome/css/font-awesome.min.css"
/>
</head>
<body>
<!-- Showcase and nav -->
<div id="Showcase">
<header>
<nav class="cf">
<ul class="cf">
<li>
<a href="#Showcase">DroneCore</a>
</li>
<li class="hide-on-small">
<a href="#Showcase">Overview</a>
</li>
<li>
<a href="#about drones?"> About </a>
</li>
<li>
<a href="#parts of a drone"> Components </a>
</li>
</li>
<a href="#uses of drones"> Usage </a>
</li>
</li>
<a href="#buy drones"> Buy drones </a>
</li>
</ul>
<a href="#" id="openup">DroneCore</a>
</nav>
</header>
</div>
<div>
<h1>DroneCore</h1>
<h2> Interested in drones?You came to the right place.</h2>
<p>
Learn about what are drones, what are they made of, their uses and where to buy them.
</p>
</div>
</header>
<!-- What are drones? -->
<!-- parts of a drone -->
<!-- Uses of drones-->
<!-- Buy drones-->
<script src="httpscode.jquery.com/jquery-3.6.0.min.js"></script>
<script src="main.js"></script>
</body>
</html>
:incoming_envelope: :ok_hand: applied mute to @native tide until <t:1634986687:f> (9 minutes and 59 seconds) (reason: newlines rule: sent 110 newlines in 10s).
!unmute 899531995191853106
:incoming_envelope: :ok_hand: pardoned infraction mute for @native tide.
!paste please use a paste-bin
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
@native tide just do what i told u yesterday.scroll to read the chat
its the same thing
thank you very much dude ❤️
I’ve some bugs in my code (HTML, CSS).
- There’s horizontal scroll which shouldn’t be there
- My code is not compatible with Mobile and Tablet
Can anyone help?
I can’t really comment on anything too high level man . But obviously you pick the tools that work for the job and you’ve found what works for you .
I have heard that flask is more custom, I’ve only been using django for a couple of days so haven’t run into any limitations yet really . Except my database not uploading properly to Postgres when deploying .
When you say template language , what are you referring to ?
im tryna do this for my project but i dont understand the JS https://www.w3schools.com/howto/howto_js_filter_elements.asp
how can i make it were it doesnt show options all but rather show certain things
youre deploying but dont know whats templating in django?
Is that a problem ?
just dont get why youre deploying already if you cant even make a template.
first things first
I can make a template . I was asking what he meant by templating language
I’m assuming he meant the syntax used with the html to work with the backend python code like jinja etc . But the terminology is all new to me so was just asking
Thanks
fixed it now
someone please help i keep getting this error => django.db.utils.ProgrammingError: column Occupier_occupier.dob does not exist
LINE 1: ..."."is_staff", "Occupier_occupier"."issuperuser", "Occupier...
my code => ```class Occupier(AbstractBaseUser):
email = models.EmailField(verbose_name='email',max_length=59, unique=True)
username = models.CharField(max_length=30,unique=True)
occupations = models.CharField(max_length=200,null=False) #amount of occupations user does
#cliques = models.ForeignKey(Clique,null=True,on_delete=models.CASCADE) #cliques user is in
date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True)
last_login = models.DateTimeField(verbose_name='last login', auto_now=True)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
dob = models.DateField(default=None)
password = models.CharField(max_length=14)
objects = OccupierManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username','occupations','password','dob']```
check your migration file and find the row for that column, delete it, remigrate @manic crane
already have deleted my migration file
and remigrating gives the same error
morning!, question:
how can i get the current web page?
lets say that i have a menu and i need to determine if the user have rights to use that webpage, how can i get the active webpage name?
so I want to make simple site like streamable on django
do I need to specify that the uploaded file can only be mp4 / mov / webm
cuz I know there is possibility to for example upload PHP code and execute it
is there already some kind of security for that in django
or do I need to implement it myself
wha ?
you want to build a youtube like site ?
and youre worried about uploads being malicious ?
well its only for me and few friends
so we can share like memes or whatnot
but still
I like to make stuff as its supposed to be made for actual real production etc
I got it set up so you get always redirected on login page, you cant register you gotta have an account
well real production would have a register page
then u have access to upload page and now im gonna work on main page with like view of latest uploaded videos
yes but I dont want other people registering
just saying, its an odd line of nitpicking then
I dont get you, maybe I didnt explain well enough
I want to use precautions and other methods most people use in actual projects
so best practice etc.
I can make register page
but I choose not to because I can make few accounts for my friends through /admin/ page
and I dont need page for registration for my use
youre just trying to clean uploads
do you understand things like SQL injection?
(basic starting place)
well Django has most of the SQL injection protected
i hope you dont think that means you dont need to understand lol
trying to build a concept here ...
looks like django checks the type and renders the type. I dont personally know of any tricks to hack through video upload but i dont know many tricks. at the end of the day people can still upload horrible things, even if they are just videos
if someone told you here, "its totally safe!!", would you then feel qualified to go on to production? lol
know your tools
which load balancer or reverse proxy would you recommend to put in front of a gunicorn server?? I could see that NginX and Traefik are popular options, but never really used any of them..
I could see that nginx is more of a web server than just a reverse proxy, so my gut feeling tells me to go with traefik- it does one thing and does it well maybe?

can anyone help me with this?:
Error: Could not locate a Flask application. You did not provide the "FLASK_APP" environment variable, and a "wsgi.py" or "app.py" module was not found in the current directory.
use have to export FLASK_APP first
you mean set FLASK_APP=*whatever*.py?
but isn't that for linux?
are u on windows
yeah
yeah i've tried that
but after that
when i use flask run
it gives an error
I set up upload page and then main page where I want my uploaded video files
I have no idea how to go about it though
I guess I need to make a model for uploaded video, store it in /media/ and then load it on main page
but I have no idea how to go about it code wise :(
come one
anyone?
Error: Could not locate a Flask application. You did not provide the "FLASK_APP" environment variable, and a "wsgi.py" or "app.py" module was not found in the current directory
you just said it. i suggest searching Creating models in django docs, then create form with ModelForm
did you try set FLASK_APP=whateveryourpyfileiscalled without the .py
Im real newbie in coding, reading documentation is sometimes just impossible for me :(
youre a real newbie and youre worried about malicious file content
from django.db import models
class upload(models.Model):
title = models.CharField(max_length=200)
caption = models.CharField(max_length = 200)
video = models.FileField()
def __str__(self):
return self.fname
okay
now you create forms.py and follow this https://docs.djangoproject.com/en/3.2/topics/forms/modelforms/
its in the beginning of the page. if youre including all fields just use
fields = "__all__"
from django import forms
from .models import upload
class Upload_Form(forms.ModelForm):
class Meta:
model = Upload
fields = [
'title',
'caption',
'video',
]
?
Hey guys, i wanna do an authentication system and generate a random code, but now i need to have the same auth code in another function to compare it in there:
@app.route("/sign-up")
def sign_up():
#some other code
auth_code = random.randint(100000, 999999)
mail.send
return redirect(url_for(app.authentication))
@app.route("/authentication")
def authentication():
auth_code =```
Does someone know how i can define auth_code so thats the exact same as in sign_up?
no
@spiral blaze i tried but same error
did u put it in a folder?
yes, fix the typos
now you instantiate the form in your views.py and render the template
Im working on it right now
from django.shortcuts import render
from .forms import Upload_Form
from .models import Upload
from django.contrib.auth.decorators import login_required
# Create your views here.
VIDEO_FILE_TYPES = ['mp4', 'mov', 'webm']
@login_required
def create_profile(request):
form = Upload_Form()
if request.method == 'POST':
form = Upload_Form(request.POST, request.FILES)
if form.is_valid():
the_upload = form.save(commit=False)
the_upload.video = request.FILES['video']
file_type = the_upload.video.url.split('.')[-1]
file_type = file_type.lower()
if file_type not in VIDEO_FILE_TYPES: return render(request, 'upload/error.html')
the_upload.save()
return render(request, 'profile_maker/details.html', {'the_upload': the_upload})
context = {"form": form,}
return render(request, 'upload/upload.html', context)
I m working with this https://data-flair.training/blogs/django-file-upload/
changed some stuff gonna see if it works
actually I need to make migrations first for the db right
wdym?
The view upload.views.upload didn't return an HttpResponse object. It returned None instead.
:((
ok changed some stuff seems to work
lets see if Im able to connect it with html now ;-;
yeah duh
im using a venv
i've tried without venv as well
doesn't work
like a folder inside of venv
@native tide hmm so it seems like migrate worked, stuff is in my database, but now when I upload everything works but there is no file in /media/ folder
from django.shortcuts import render
from .forms import Upload_Form
from .models import Upload
from django.contrib.auth.decorators import login_required
# Create your views here.
VIDEO_FILE_TYPES = ['mp4', 'mov', 'webm']
@login_required
def upload(request):
form = Upload_Form()
if request.method == 'POST':
form = Upload_Form(request.POST, request.FILES)
if form.is_valid():
the_upload = form.save(commit=False)
the_upload.video = request.FILES['video']
file_type = the_upload.video.url.split('.')[-1]
file_type = file_type.lower()
if file_type not in VIDEO_FILE_TYPES: return render(request, 'upload/error.html')
the_upload.save()
return render(request, 'videoplayer/videoplayer.html', {'the_upload': the_upload})
context = {"form": form,}
return render(request, 'upload/upload.html', context)
my project folder is called Loophole and i have the file named market.py in the project folder and not in any sub-folder
@quasi willow weird, never encountered that error before, sorry man
'tis okay thanks for trying 👍
you mean in your folder structure directory media, the file isnt saved there?
yes
thats because you dont have the upload_to
also I dont think views.py works as it should
in your model field args
if file_type not in VIDEO_FILE_TYPES: return render(request, 'upload/error.html')
this doesnt work
I upload file other than ```VIDEO_FILE_TYPES = ['mp4', 'mov', 'webm']
like that if didnt get checked
here is upload.html
{% load static %}
<video autoplay muted loop id="myVideo">
<source src="{% static "upload/vid/videoxd.mp4" %}" type="video/mp4">
</video>
<link href="{% static "upload/css/style.css" %}" rel="stylesheet">
<form action method="post" class="form" action="">
{% csrf_token %}
<h1><strong>File upload</strong> with mp4 / webm / mov</h1>
<div class="form-group">
<label for="title">Title <span>Use title case to get a better result</span></label>
<input type="text" name="title" id="title" class="form-controll" />
</div>
<div class="form-group">
<label for="caption">Caption <span>This caption should be descriptiv</span></label>
<input type="text" name="caption" id="caption" class="form-controll" />
</div>
<div class="form-group file-area">
<label for="images">Video <span>Here is where you upload your video</span></label>
<input type="file" name="video" id="video" required="required" multiple="multiple" />
<div class="file-dummy">
<div class="success">Great, your files are selected. Keep on.</div>
<div class="default">Please select some files</div>
</div>
</div>
<div class="form-group">
<button type="submit">Upload video</button>
</div>
</form>
<link href='https://fonts.googleapis.com/css?family=Lato:100,200,300,400,500,600,700' rel='stylesheet' type='text/css'>
<a href="http://something.com/" class="back-to-article" target="_blank">back to Article</a>
you should simply check in the template if there are errors
and if there are, just dont proceed with the POST
how to do that
I think the whole view is written wrong ```py
def upload(request):
form = Upload_Form()
if request.method == 'POST':
form = Upload_Form(request.POST, request.FILES)
if form.is_valid():
the_upload = form.save(commit=False)
the_upload.video = request.FILES['video']
file_type = the_upload.video.url.split('.')[-1]
file_type = file_type.lower()
if file_type not in VIDEO_FILE_TYPES: return render(request, 'upload/error.html')
the_upload.save()
return render(request, 'videoplayer/videoplayer.html', {'the_upload': the_upload})
context = {"form": form,}
return render(request, 'upload/upload.html', context)
Idk what might be wrong though
i suggest trying that
thats all from me, best of luck
Hey guys, i wanna do an authentication system and generate a random code, but now i need to have the same auth code in another function to compare it in there:
@app.route("/sign-up")
def sign_up():
#some other code
auth_code = random.randint(100000, 999999)
mail.send
return redirect(url_for(app.authentication))
@app.route("/authentication")
def authentication():
auth_code =```
Does someone know how i can define auth_code so thats the exact same as in sign_up?
can someone help? would be great
save the user in a session, the code in a file
And what kind of session?
session["user"]=user
k and how can i implement that in a a code?
so this line just before with open("file.txt")...
And then just repeat that in authentication?
https://docs.djangoproject.com/en/3.2/ref/forms/validation/#cleaning-a-specific-field-attribute
i suggest doing this in your form already there you can just check if video.endswith('.mp3') etc, if not, just raise error in the form. that'd be all now.
1 get the user
2 create the code
3 save the code
4 next time user login open the file and validate
or use databases
many programmers use databases
hey yall im trying to create a gaming forum for a gaming server anyone have a tutorial or resources you could send me?
ive been looking for the best way to do this with django but i am lost lol
i have website hosted on heroku https://symor-richaards.herokuapp.com/. When you post an image it disappears after the server sleeps, which is after 30min.
I want the images to stay even when I commit changes and push to heroku.
here my 1settings.py 1 settings for static files```py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'build', 'static')
STATICFILES_DIRS = []
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media') if (DEBUG) else os.path.join(BASE_DIR, 'build', 'media')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'```
And when I put something in STATICFILES_DIRS like py os.path.join(BASE_DIR, 'media') I get an error in the terminal.
full traceback:
!paste
{% for upload in uploads %}
<article>
<div class="media-body">
<div class="article-metadata">
</div>
<h2><a>{{ upload.title }}</a></h2>
<h3>{{ upload.caption }}</h3>
<video>{{ upload.video }}</p>
</div>
</article>
{% endfor %}
can someone help me with this, upload.video isnt showing up
you seem to have a typo at the video tag
I changed it
{% for upload in uploads %}
<article>
<div class="media-body" >
<div class="article-metadata">
</div>
<h2><a>{{ upload.title }}</a></h2>
<h3>{{ upload.caption }}</h3>
<video>{{ upload.video }}</video>
</div>
</article>
{% endfor %}
still doesnt work :c
Err, I think video tags have certain attributes they need
ok thanks gonna look into that!
set source on the video
I feel like you just copy pasted and didn't try your best to solve alone first.
Is {{ upload.video }} a url?
I tried setting types
size
and a lot of different things
okeh
try printing upload.video, it should be a url
Assuming {{ upload.video }} is a url/path, could you try this?
<video src="{{ upload.video }}" controls>
Video not supported
</video>
(this is just a shorter version with controls)
yes I did do that eventually it fixed all of my issues
thank you very much though
np
it looks bad
also need to make sorting from latest
and also need to make it look at least decent, with some default size
and probably page pagination
then I should be done
for sorting I would need to add time of creation to the model right
yeah you can put the attrs in the parameter of FileField and set the height and width and also add date_created with the autoaddnow option on and then in Meta just put ordered -date_created to sort for latest
thank you king
hello! i have a web dev question in help-burrito if anyone here could take a look 😄
no probs
someone please help when i try make a super user i keep getting this error => self.UserModel._default_manager.db_manager(database).create_superuser(**user_data)
TypeError: create_superuser() missing 1 required positional argument: 'dob'
user = self.create_user(
email = self.normalize_email(email),
username=username,
password = password,
occupations =occupations,
dob = dob
)```
self.normalize_email(email)<------ error,
username=username,
password = password,
occupations =occupations,
dob = dob
)
self.normalize_email(email, <-- fixed, try with this change
username=username,
password = password,
occupations =occupations,
dob = dob
)
Has anybody had any issues with modals in flask or django .
I had it with flask and I’d changed the cdn script .
I’m using django now and I can’t remember what I changed
hey all, currently going through Miguel's Flask mega tutorial chapter 7. He writes a piece of code to update the user_profile form, but the way he does it, every time the user clicks on "submit" the values are overwritten, even if they have not changed. is there a way to write this more efficiently and only do db.session.commit() if there are actual changes in the fields? this is the code: def edit_profile(): form = EditProfileForm(current_user.username) if form.validate_on_submit(): # Triggered by "form.submit" (POST) current_user.username = form.username.data current_user.about_me = form.about_me.data db.session.commit() flash("Your changes have been saved.")
I am using flask and i need js graph in my html, this is html code : https://paste.pythondiscord.com/usedizexij.xml but it doesnt return anything
whats wrong?
!pastebin
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
Put const config before const myChart = new Chart, then it will work. And another thing is make sure to add the css for chartjs as well.
If you really want to execute another script on a click, you can use celery for doing such thing, if this particular task is taking too much time.
@native tide try to use node media server along with pykafka for sending streams to this nms server
This will reduce the latency and increase video efficiency.
Hey, im making flask betting simulator app for premier league games. My current issue is that im not sure where to make the calculations in my code that determine whether a user has won or lost a bet, as well as updating their cash according to their bet placed.
Currently i have it in the same flask function that displays all the user's bets however ik its bad because that causes many problems and im not sure where else to make the calculations.
The problems are: the update query i have in my if statements always updates every time the page is refreshed. This causes the cash to keep on being added endlessly. Another problem is that only the last bet's value is added if a user wins. for example if the user wins their 4th bet, only their last bet's amount keeps adding to their current balance
I currently have 3 pages in my website. A "home" page which displays all upcoming games and their odds where a user can choose who to bet on. Once chosen, they are redirected to a checkout page in which they are able to place the bet with their amount.
And also a "pending" page which displays the user's placed bets.
should I use nginx in my development docker environment??
also should I make nginx a container in docker compose? I've seen a lot of people do flask + nginx in a single container itself, not a huge fan of that!
I'm trying to set it up here: https://github.com/aryaniyaps/todos
I think it is good idea to keep nginx separate.
Alright, that's what I was about to do,just wanted to check!! Thanks a lot!!
But still, should the nginx service be used in a development / ci environment?
That is going to depend on you frontend app I would think. Is it a separate SPA and flask as a backend only? Or are you using flask static folder / templates as intended.
right now I'm doing the backend, but there will also be a react frontend hopefully
so, its okay to have nginx right?
I also simplified my dockerfiles, docker-compose.yml is for production and docker-compose.override.yml is for dev. I will also use the production file for ci, with different ENV variables I think!
Hey folks. I was hoping for some input into hosting a frontend.
I build a simulation software, it runs thousands of different simulations (monte carlo analysis), so it is computationally intensive. On my newish gaming PC, the execution time is about four seconds, and the simulation seems to use up to about 3GB of ram, based on the task manager.
I was going to build a streamlit frontend for it. Question is, how to host? Seems like it would be quite expensive to put into the cloud as a service. I was hoping to make this tool available for free community use.
Its good to have in your CICD and some unit tests can use the rewrite via nginx giving you confidence when you have to make some changes to the nginx configuration.
hey folks can anyone help me with web scrapping here? I have a problem??
I don't think you particularly want separate files if you can help it and instead rely on environment variables to configure the difference. If you need extra services you can have another file and start both at once. My rational is that if you test in dev and its all good you still have the opportunity to have a discrepancy in production. See https://docs.docker.com/compose/production/
thanks a lot @raw compass
So, i am using flask and trying to make this graph https://www.chartjs.org/docs/latest/samples/line/line.html?fbclid=IwAR0qCITkkJeOCNyBRkkAo-_-4vxkCE9wSepWhFIpp37aeql3T_JP3EM3rDcHFc0NvBuUHMYrDEleLz3z2K_ADytMwZM2SWx9pjzhiPikGA , but my code doesnt return anything
This is my code https://paste.pythondiscord.com/efehediged.py
Open source HTML5 Charts for your website
Whats wrong with it?
I literally just copypasted it from the site
you don't seem to be using your <canvas id="myChart"></canvas> (like with getElementById anywhere in the javascript code so of course nothing would be displayed. perhaps you could try the example on the homepage first?
like this?
or?
looks good to me
does it work?
the usage page explains it well https://www.chartjs.org/docs/latest/getting-started/usage.html
Open source HTML5 Charts for your website
maybe try setting the width and height on the canvas tag? your code looks good though
nope... still nothing
ahhh
whatever, if you find something, lemme know in dms... I have to go rn
thanks anyways ❤️
alright np, I'll try it out locally too :)
@native tide hmm it looks like the script uses the Utils module which is a separate file that has to be imported
did you look at the event handling documentation someone linked last time? (forgot who) you can use cookieBtn's .addEventListener("click", handlerFunctionHere) to add an event listener to an element
hello,
i'm building an api for a web application, i'm facing a problem.
when i want to post a form, i have a field named : post_author
but once i submit the post_author with the user id it returns me an error,
how to do?
this is the error message returned :
non_field_errors [ "Invalid data. Expected a dictionary, but got str." ]
!paste can you paste your code please?
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
i've figured out what the issue was, i was asking to the serializer to only accept this fields :
class AuthorSerializer(serializers.ModelSerializer):
class Meta:
fields = ('id', 'username', 'full_name')
model = User
Aright, i will try it
is there anyone here who can help me create an e commerce project?
@fleet geyser Many of us could give advice at least. What do you need?
I'm not saying I'll code for ya, but I can point you in the right direction.
does anyone know how i fix the syntax ive tried alot of stuff and i cant fix this stupid error You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ') AND `type`='tool'' at line 1 php "SELECT * FROM `catalog_items` WHERE `id` IN (".implode(',',array_map('intval',$invItems)).") AND `type`='$type'";
can someone pls help go to #help-lollipop
$("#ip").html(data.ip); I have a client’s ip stored in a ”ip” id, how can i access it in <input type="text" readonly class="form-control-plaintext" id="ip" value ="{{ip}}" name="ip">? as the value of the input
Fixed it by setting detail to False
can i ask here web dev related questions or i need to use a channel?
Hi guys, I am developing a django web app but I am stuck on one particular thing.
I am taking user input in a form for reminding them about something , so via a dropdown user will select if they wanted to be reminded 'a month prior' or a 'week prior' to the due date..
I want to send them an email 1 week or 1 month prior depending on their choice. Now what I don't know is how to implement it? I was reading about Celery but how will celery schedule this task?
Is there a method or plugin that would help automate this task?
I myself am new so I can't be sure about this, but from the previous chat it looks like you can ask the question directly here..
Hello, i'm trying to learn how to make better looking programs, and as a first project i'd like to make a webapp or gui that is a list in which i can add/subtract and sort by parameters.
Where would you start? Can you recommend me something for this project?
where should i create the website itself? (looking for a builder)
Flask
I'll check it, thanks.
I've never done this, but I do use Celery Beat to schedule tasks. I bet you could create a CeleryBeat task to run at some point in the future.
Will Celery Beat also check for conditions periodically? Like check every 1 hour if the deadline for some user/users is approaching and if it is then send the email?
Not sure how the internals work, but it generates a Model and is stored in your database. It may even poll the schedule table every minute. So if the user form created a row in this table, it should then run at that time.
Thanks for the info, I will check celery beat out 👍
I think this would do what I want to do..
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-image: url('/Images/bitcoinbild.jpg');
}
</style>
</head>
<body>
<h2>Background Image</h2>
</body>
</html>
can anyone tell me why this does not set a background image?
i have checked the path, and it works as a link
Hey guys! I want to use a few variables from settings.py so I do from django.conf import settings and then settings.RAZOR_KEY_ID but that doesn't work. I get the error AttributeError: 'Settings' object has no attribute 'RAZOR_KEY_ID'
This is a Django project
So i imported it, but it still doesnt work...
your css code is correct so i think you need to check the path for the image
if the file images in same directory just add a ./images/image.png
the dot dont forget it
yeah but it worked in
<a href="https://www.youtube.com/watch?v=bBC-nXj3Ng4" ><img src="Images\bitcoinbild.jpg"></a>
yes
there is some thing annoying in coding
there is difference between
Images\bitcoinbild and Images/Bitcoinbuild
xD
the \ and /
lol
yea it is annoying i know..
Backslashes depend on your interpreter and your OS
Don't worry about it too much just use whatever works
i copied the relative path and still somehow messed it up 🤦♂️
huh it still does not work
is it Images\bitcoinbuild.png?
try adding .\ at the start
nope
other wise show me the directory
huh
tell me it works 😄
yeah I really appreciate your help here, but sometimes the code gods are against you :8
oh yeah it worked
haha this is just crazy
sec
The url() CSS function is used to include a file. The parameter is an absolute URL, a relative URL, or a data URI. The url() function can be passed as a parameter of another CSS functions, like the attr() function. Depending on the property for which it is a value, the resource sought can be an image, font, or a stylesheet. The url() functional ...
this will be your best buddy
ok thank you so much for your time. I hope this is my fifth and last encounter with path stuff 😁
np
try settings["RAZOR_KEY_ID"]?
you put another slash before the slash
TypeError: 'Settings' object is not subscriptable
my elasticsearch image pollutes the terminal with hundreds of lines of log. How do I turn it off? I think it's mostly java stuff I dont even understand
I'm confused about something silly, URL. A URL provides the location of the resource. but after learning full stack a URL in React can just be a thing you made up (in React Router) that moves you to another component. A URL should be the actual end point in the REST API that the component or page is behind the scenes sending requests to, which are unrelated to the paths you see in the top of your browser. So why is URL defined as "the location of the resource" ?
im trying to ask help in the right channels and getting no help. is everybody answering questions here?
Learning Django right now and really enjoying it a lot. Want to get learning a front end soon too. What do you all suggest goes better with Django? Vue or React?
VueJs
is there any way to decrease sorl-thumbnail's query count during Django test?
how did you import it? mind pasting the new code?
also, checking the console in the developer tools may be useful as it shows the errors if any
Can someone please tell me how I can update an existing Flask-WTF form using a server side session? Instead of using render_template I want to somehow say update this field in the session.
i make changes to my models but when i try and migrate i get no migrations to apply ?
tuf
i completed my site on html 😎
thats a flex
nice
I'm getting a headache of trying to create a reddit-like comment-threads system into django
there's alot of ways to do it, most of it is beyond inefficient that i doubt even 1000 comments would casue delays over 1 second per request
how good is js for mobile dev?
it can do the job but in a limited fashion probably
as long as all you need is interactive web site in form of app, you should be fine
if you will try to access internal mobile services for your application, you will probably encounter limitations
I never tried that, but that's just my lucky guess how it would be
for more information about the limits of the limits, check what can do particular mobile js framework, like React Native or Vue Native
I mentioned this a but agi and didn't get any decent responses so I'm trying again but this time with more context lol:
Anyone here do a significant amount of backend web dev with python? I do a lot of work with React and have, historically, used NodeJS to construct my API's when needed. However, my new job demands a lot more python use and I'd like to find a nice Python backend framework for API's but I have a few issues with the existing options:
-
Flask & FastAPI are great in theory, but every single production example I've found is needlessly complex and verbose when compared to Node applications that can handle the same amount of traffic.
-
Django, while great as a framework in and of itself, isn't great for pure API's and requires a ton of boilerplate. And Django REST isn't much better from what I've seen.
flask is simpler than django. from what you've seen? what have you seen? if youre new to python you might just wanna try flask.
I didn't say that Flask was mroe complex than Django, I said that production Flask applications are often very complex and require a lot of additional tooling relative to similar Node applications that can handle the same amount of traffic
We are comparing Flask vs Django - their pros and cons, use cases, and our experience with them.
▶ Contact Jelvix: hello@jelvix.com | jelvix.com
We are a technology consulting and software development company eager to share our knowledge and experience.
Subscribe for more tech tips and tutorials: https://www.youtube.com/channel/UCEDr9FfkfzsT-h...
?
im using react native for my front end its exce
excellent
Evening, I am using Flask to run a web app deployed to a Direct Admin server, I and sending POST requests to this flask app from a web based database which generates a PDF report.
Sporadically I get the No 'Access-Control-Allow-Origin' header error even after several successful requests, and using the FLask-Cors library.
Has anyone else works with this?
Yeah a 5 min youtube video doesn't address any of my production concerns and honestly I think you're missing the premise of my entire comment anyway
Hi... I learned html and css and i want to know if i can use django or flask in front end without any js. Is that possible?
Possible? Yeah absolutely. It depends all on what sort of interactivity you want in your web pages. You can 100000% make a simple, good looking, nice website without any JS
Ok tnx but do django or flask have a lot of features like js?
Thay arent comparable
Why
Django/Flask = Backend Logic (Database comms, routing, etc). Javascript = Frontend logic (cool effects interactivity, etc)
Well all i know about the web rn is html/css
And i think that js is used to write the functions and attach them to the buttons ...
I want to know if i can use python to write those functions...
No
Cz i don't need js for effects i xan do them with css
And how to make a page without js then
Interactive page
But if you want to do anything that requires JS then... well you have to use JS
JS isn't difficult
I know JS and Python very well
I prefer JS tbh
👍
My personal experience is with Django and while there is a fair amount of boiler plate this can be minimised with class based views (& viewsets in DRF). in terms of your question I would say it depends on the wider architecture our dealing with. ie do you have lots of smaller services (at which point I would lean towards flask), if it's going to be more of a monolith API then I would start with Django. For dealing with the boilerplate I typically reach for this in a new project which cuts through most of it: https://github.com/cookiecutter/cookiecutter-django
I'm pretty new to this stuff myself but that seems like a fair assessment. Flask and fastAPI are great for quickly developing simple APIs but if NodeJS is working for you, just use that.
why do i need a static file for style sheets?
What do you think the alternative is?
I'm not being a smart ass here lmao. I'm gonna ask you questions that will actually make you think and hopefully bring you to a deeper level of understanding.
im not sure, i thought i could just link it normally and it would work
kinda weird to me that when i open it in my folder, it works normally but i have to static it when i make a website
What is "linking it normally" to you? What other files have you "linked normally" that have worked? Additionally, what do you consider a static file to be?
from what ive heard a static file doesn't have to be generated
does this make it more efficient?
That is technically correct, but tell me what this means in your own words.
what do you mean
I mean exactly what I asked
like the name static file?
Defined a generated file for me real quick, short and concise.
In reference to this ^
oh, are generated files different for each user but static files are pretty much the same for every user?
Welllll kinda. A "generated" file (not the technically correct name) is basically a file that is dynamically updated based upon some information from the server. Users is a good way to look at it, or you could look at it as if there were a home page which stated how many times it had been visitied. E.g. it could have "1,245,343" total visits but then another person lands on the page it is updated or the file is re-"generated" to read "1,245,344"
A static file, on the other hand, is a file that will never, or very rarely, change
A great example is a CSS file. Your styles will not be updated per each user or per each visit
Your styles should remain constant throughout the lifetime of your application until you choose to update them
Another good example would be an image on your homepage. That image won't be updated with each visit or altered with each user session. It simply exists as it is
Does that make sense?
i think it does now, thanks!
No problem! Any futher questions? It's totally cool if so, these things aren't always easy to understand. I know when I was earlier in my dev journey there was so much that made zero sense to me lol. Feel free to fire away.
im learning super slow right now, so i have like little to no questions, just some jinja syntax thingy confuses me
from flask
Can't help ya there unfortunately. I mainly work with decoupled API's and Clients
hope ill be at your level one day, im just creating random websites for now, trying to add everything i learnt
My level isn't even that high haha. I still have much to learn, and no matter where you find yourself there will always be much to learn. It wasn't very long ago that I was exactly where you are now. Don't stress about it, just enjoy the journey and learn what you can 🙂
For Django, how can I change the default widget in models.CharField when using choices from the select to radio choices?
I haven't used much Django but how does this look https://stackoverflow.com/questions/9878475/django-modelform-override-widget
Np lol, I tried. Gl.
Is python well-suited for having lots of concurrent connections via websockets these days or am I better off with a full JS stack with Node or something?
I'm gonna be biased in respinding to you here, but I'd go with node. JS in fundamentally designed for asynchronous processes. Python absolutely can, I'm sure, handle lots of concurrent connections. But Node would be better.
If you're really willing to go with a lang specifically designed for many concurrent connections, then Elixir would be your best bet by far,
Yea that's the gut feeling I get from my research. I have a lot more python backend experience and love to work in it, but I feel like I'd be shoehorning what I want to do.
Honestly I have a lor more Node experience than I do Python. I've been really wanting to get into Python for web dev but it in general seems like a poor choice relative to Node lol
I wouldn't say poor. It all depends what you want to do. Python is very fast so it is still very well suited for web apps.
I use a Next/Django stack and it's just so fun to work in.
Python would be better for larger, monolithic apps.
you mean not using the choices parameter with the class?
The Django admin dynamically generates a modelform in the background (using a model formset if memory serves correct). The modeladmin class has a form attribute which you can use to override the default form and do whatever you like including customising the widget
I think tornado or pyramid might suit this kind of work better? Disclaimer not used either of them myself but from past reading they cover that area.
Or give Django channels a spin with an asgi server
i am using django-webpush. how can i recieve push notification only when the tab is outof focus?
guys whats
the best place to learn
django
and what route should i take to learn python web development
The official web tutorial is good. Django for Beginners book is good too.
After one or both of those, the best way is to try and build something small.
u got any links
to the web toturial
u talking about W3schools?
or something else
Hi everybody,
Could anyone explain to me why a python algorithm (complex) will take 15-20 times longer using with Flask and a web controllers? Can we improve performance?
Thanks, @calm plume
Do you mean vs running it directly in a script?
There is some overhead in processing the request and turning the output into a response object. Is the response particularly large or complex?
When you say 15-20 times longer are you talking like 2 seconds to 30 seconds or like 1 minute to 15 minutes?
I go from 4s to 4 minutes ...
And are you using flask's development server or a production quality server?
What do you mean ? I use flask on local ^^
app.run(debug=True)
Maybe debugging impacts performance?
And then flask run or something like that.
This is my main.py
from flask import Flask
from controllers.home import home_hdl
from controllers.dbscan import dbscan_hdl
from controllers.kmeans import kmeans_hdl
app = Flask(
__name__,
template_folder='views',
static_folder='static'
)
app.register_blueprint(home_hdl)
app.register_blueprint(dbscan_hdl)
app.register_blueprint(kmeans_hdl)
if __name__ == "__main__":
app.run(host="0.0.0.0", debug=True)
Debugging likely impacts it, but flask's built in server is slower, or at least it used to be than something like gunicorn.
So guinicorn seems to be better ?
gunicorn is pretty fast yeah, especially with uvicorn workers
I've never used it with flask though, only FastAPI
Definitely a better choice in a production environment and going to be faster. Are you just hitting a URL to kick this off, or uploading an image. Basically what you've added by being behind flask is all the stuff that goes with a web request. Request, deserialization, response serialization.
So it's likely that the code you're running isn't slower, but the translation from web request to your algo to response is what's adding the time.
Ok I will install and try it now ! 🙂
Ok I have an issue
Failed to find attribute 'main' in 'main'.
Ok I fixed the first now 🙂
TypeError: __call__() missing 1 required positional argument: 'start_response'
thx
If someone knows the solution
I take it 🙂
Are you getting this when you hit your url or during startup of gunicorn? Any more information would be helpful, but it looks like an argument isn't getting passed in somewhere.
So,
Command run :
❯ gunicorn -w 4 wsgi:app
Folders :
.
├── app
│ ├── controllers
│ │ └── XXX.py
│ ├── main.py
│ ├── models
│ │ └── XXX.py
│ ├── static
│ │ └── XXXX
│ ├── views
│ │ └── XXX.html
│ └── wsgi.py
├── Dockerfile
├── README.md
└── requirements.txt
File : wsgi.py
from main import create_app
app = create_app("production")
Error :
File "/Users/alexis/Documents/Cours/3iL/UQAC/Forage de données/TP2/8INF954-TP2/app/wsgi.py", line 2, in <module>
app = create_app("production")
TypeError: __call__() missing 1 required positional argument: 'start_response'
[2021-10-25 15:35:45 -0400] [14870] [INFO] Worker exiting (pid: 14870)
The error is present at startup
Honestly, not sure. it's been a while since I deployed flask. Could try starting like this gunicorn "myproject:create_app()"
I solved my problem by removing the ('production')
So the server is running but still slow
That doesn't work anymore. It won't call functions.
I have to find why it's still slow
I made a whole project without thinking about performance :x
It's probably slow because python
I am currently rendering a form using an UpdateView with a form_class that is created using crispy forms. Everything works as it should except the model is not updating
Maybe but I don't understand why it takes around 10 seconds without using flask
And with flask about 4-5 min
!e ```py
import timeit
timeit.timeit("import flask")
@frank shoal :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | File "/usr/local/lib/python3.10/timeit.py", line 234, in timeit
004 | return Timer(stmt, setup, timer, globals).timeit(number)
005 | File "/usr/local/lib/python3.10/timeit.py", line 178, in timeit
006 | timing = self.inner(it, self.timer)
007 | File "<timeit-src>", line 6, in inner
008 | ModuleNotFoundError: No module named 'flask'
where I put it ?
in a python prompt
Python 3.8.9 (default, Aug 21 2021, 15:53:23)
[Clang 13.0.0 (clang-1300.0.29.3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import timeit
>>> timeit.timeit("import flask")
0.5613005850000001
>>>
flask is kind of large (0.5s to load).
import is only 1 time, no ?
Are you set on flask or can you consider switching?
If you don't really need html templates, you can switch to fastapi (though it does support it if you install jinja2)
I can't change anymore ^^,
This is for a university project concerning img processing, I made a good interface to put the image and chose the options but the processing takes really too long while with a normal script it is fast
How is this difference explained? : /
i have the html code of a webpage and im planning on rendering it in a flask server. But, if i want to login or press buttons, will it redirect me to a new page or will it be static, if its static how can i make it redirect?
Hello anyone answer my ques
Directing a user from one static page to another with Flask at the press of a button is super easy. Each static page will have its own route/ URL?
I think it's request/response cycle. What is the request you send and what is the response?
when i try to run my website
oh
ill check
python manage.py runserver
this things pops up
no module named 'DEMOPROJECT.settings'
wat does this mean'
Should be able to do a post and then redirect
k
It means your settings file isn't where your import thinks it is. Are you importing your settings somewhere?
i dont know that how do i check?
I send a basic POST request from a web form with 2 inputs, 1 file and 1 number and after that I do my processing on my image and I make a render_template () of flask
So you are "uploading" a file. When you run it locally, are you just pointing to a file path?
yeah
would have to check your code to see if you're importing settings. If it ran before and suddenly stopped, always check what you've changed recently
In my controller I use pillow to recover all my pixels and numpy for my lists
can you time how long the "upload" takes?
the upload is fast it's really the processing behind ...
Did you measure it? How do you know it's fast? If your controller code runs fast outside of flask it's something about the web implementation that is slowing it down.
the server not work
when i remove this line it work
help ls
pls*
@native tide
help
Do you have patterns in the urls.py? What do your imports look like?
this the main urls
this is the pages urls
this the view
@native tide
setinges
so why the err
Try adding the project name in the path in the main urls include include('project.pages.urls'
with the name of your project
yp its project
too
shouldn't you have project.pages in your INSTALLED_APPS setting and it should be after the built in ones, not at the top
look, urlpattern != urlpatterns.
okay ill try
great catch
omg
thx
it works
congratulations, best of luck
thx
go ahead and ask, if I can help I'll try
Okay
Thx it's a weird question tho
So I have a lot of free time so I want to make a website in like 6 months but after 6 months or maybe a little more I want to have a decent website with also a decent amount of ppl going on it but idk if I can make it cause 6 months seems kinda short
And I also don't know how to code
I am a beginner noob
I would say in 6 months you should definitely be able to learn HTML and CSS to create a website
Nice
"Decent amount of people going on it" comes down to marketing. Are you a good marketer?
What kind of website should I make cause i want 1 that's useful for ppl
Uhh not really XD
Like I still need to learn everything
However, your question has a lot of issues, because you are not mentioning the purpose of the site, if it is gonna require memeberships? or is it just a blog? is it dynamic or static?
Ohh no just like a blog maybe or a internet testing site or just something simple
But not with memberships
And wdym with dynamic or static
Yeah sorry I still need to learn a lot
whether the state of the website changes due to user interaction
well i mean, if I go to your site and click something, will the site change what it is showing me?