#web-development
2 messages · Page 170 of 1
here's the html jinja I used to receive
{% with messages = get_flashed_messages() %}
{% if messages %}
{% for message in messages %}
{{ message }}
{% endfor %}
{% endif %}
{% endwith %}```
I hope that helps. I've only a couple of months with Flask so not an expert. But I did get those flashes working for me in Flask
Okey, I understand the code here and in the documentation but I wonder how get_flashed_messages() can be read?
I didn't need any include statement at the top of the html file. So maybe it's a part of Jinja2?
The reading is happening in the for loop....give me a sec...
I'm also passing in an a form object within the return render_template()
So can we say that some functions is avaliable as a default in Jinja2? But this functions is a function of flask.
So maybe it counts flashed messages as a part of the Form object? Pure guess though
I don't have the definitive answer. But in my experience, frameworks do have some heavy-lifting coded in.
Definitely a question you could research. I bet Stack Overflow will have someone explaining that with a related question
Okay but there should be a logic behind it
Thanks for your help
I agree. But without knowing the object model for how Flask treats forms I declare...
Glad to help. I've had plenty of help here. 🙂
You're right @languid raptor what do you recommend?
Oops sorry I didn't know this rule existed before now
I wish I had an answer for you. I don’t make commercial products or do consulting. For me if my Django project does what I intend, That’s satisfactory.
Alright I'm sure I'll think of smth eventually. I'm kinda busy with another project.
I’m certainly not pushing any rules on you. Just FYI.
Don't worry I appreciate your input tbh
Thanks for the review too
oh crap, i'm not sure if i should have posted this in a #help-chili channel or not... but mine's related to web dev
do i post it here instead and close out chili?
Can anyone recommend a great book for really learning Django? I need to delve deep into this framework. Tutorials are nice an all...but methinks this is going to warrant some deep learning.
Two scoops of django 3.x will follow me forever. You can check it out
Thanks 🙂
Just purchased...looks really solid already. Thanks for the recc
Im using matpltlib on my dev enviroment, but when I try to push to heroku this error comes up.... 😦 any ideas.
ok... so i'm still battling this silly thing and the more i'm doing this the more i realize maybe i have the entire way i'm doing it wrong...
i'm creating a customer and ticket tracking system (that i'm planning on giving away, at least for a little while) as a learning project, but i'm stuck....
i can't seem to fill in the customer ID (i'll figure out note type after that, hopefully)...
class NoteType(models.Model):
name = models.CharField(max_length=40)
color = models.CharField(max_length=7)
icon = models.CharField(max_length=50)
class Note(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.DO_NOTHING) # <--- HOW DO I GET THIS?
note = models.TextField()
time = models.DateTimeField(editable=False, auto_now_add=True, auto_created=True)
created_by = models.ForeignKey(User, on_delete=models.DO_NOTHING, auto_created=True, editable=False, related_name='notecreatedby')
type = models.ForeignKey(NoteType, on_delete=models.DO_NOTHING)```
I know that customer ID is defined in the URL as follows:
**urls.py**
```py
path('update/<int:pk>', views.CustomerUpdateView.as_view(), name='update_customer'),
path('update/<int:customer_id>/savenote', views.CustomerCreateNote.as_view(), name='add_customer_note'), # <-- HERE SHOULD BE WHERE I CAN GET THE CUSTOMER ID```
How do I get that ID?
I guess I'll include my views.py as well:
class CustomerCreateNote(CreateView):
model = Note
fields = ['note']
customer_id = 0
def post(self, request, *args, **kwargs):
pass
def get_success_url(self):
return reverse_lazy('view_customer', kwargs={'id': 1})
def form_valid(self, form, *args, **kwargs):
obj = form.save(commit=False)
obj.created_by = self.request.user
obj.customer = Customer.objects.get(pk=form.cleaned_data['customer'])
obj.type = NoteType.objects.get(pk=1)
# obj.save()
return super().form_valid(form)
It's under major reconstruction
I thought it was originally going to be request['customer_id'] but that didn't work...
well, I usually include the id as an attribute..... try
class CustomerCreateNote(CreateView, customer_id):
@opal canyon i tried to do that but was dissuaded by pycharm... NameError: name 'customer_id' is not defined
Ohhh yeah you're right I didn't noticed you were using class based views...
Try to read a bit of this documentation:
https://docs.djangoproject.com/en/3.2/topics/class-based-views/generic-display/
Specially the Dynamic filtering section
it's all explained there with examples
awesome @opal canyon - thank you!
For example
No Worries
Hey guys, question, best way to store a list of floats on the database using models?
Honestly I've got no clue of what would be the best practice in this case
what is expected amount of elements in your list
if unknown... then better just creating table with float element for row
it will be auto ordered by primary key
you would have some problems with inserting new elements in the middle of the list though
depending on what you exactly need perhaps integer element with your own element counter is in order
Though forget about it. It does not sound good to use SQL db for that
tbh. May be better using mongoDB for that
you will be able to store your list of floats exactly as list of floats
without any extra trouble
hey i need a very small help i am doing pagination and my home page is working perfectly but when im opening the detailed (paginated ) new post added page it's showing some error
or may be just storing in filesystem as file 😉
and if it would grow too big, handling it with python generators.
my views
def detail(request,question_id):
n1=Posts.objects.get(pk=question_id)
return render(request,'app1/detail.html',{"n1":n1})```
plz help
i just forgot how to paginate lol
im too dumb
ok done
thanks alot
Hey guys
Anyone familiar with apscheduler in django?
whenever i do open with liver server google hangs , i have tried 100 times still not working
[Help] flask html/css divs:
I have 2 divs next to each other in div container. But on mobile I want them to be moved to below each other. I cannot do it, I tried different displays: flex/ grid. Did not help:
# main container which will have 2 divs inside next to each other:
.main{
display: flex;
}
.div_1{
text-align: left;
font-size: 14px;
padding: 15px;
margin: 15px;
}
.div_2{
/* empty */
}
so html looks like:
<div class="main">
<div class="div_1">
Some Left Menu Data
</div>
<div class="div_2">
Main article Content
</div>
</div>
How to break them on mobile? (div under div)
You can put both divs in another div. Then, use media queries and style the container div with
{
display : flex;
flex-direction : column;
}
I have a flask application and i want to create routes that can only be visited when a button on the current route is clicked and not on the adress bar
thx
ig u must use media query
{}
the only way to achieve this, without affecting the address bar, is to replace the content of the current view
else what you are looking for is impossible
hello
i want to know i have create django project and i have written mysql localhost server password in it and added that project folder to github in public repo ! ! Do u think that good to share you local host mysql server username password with project
anyone??
if not how to add folder of django to the github repo?? only app?
My css changes wont get applied no matter what i do
try using cryptographer
in what framework ?
@jovial cloud @merry kelp Thank you very much guys, appreciate the info
is it possible to make django ORM request with closing db connection right after that
creating threads in django exhausts database limit connection, how to fix that? I don't even need active db in my child
im using the datetime module to display the current day
but i don't get it why sql is bothered
from flask import render_template,redirect,url_for
from Flaskiproject import app
from Flaskiproject.forms import Login_formcall
from datetime import datetime
@app.route('/')
def login():
form=Login_formcall()
ademail="@direwa"
useremail="@ecolewa"
if form.validate_on_submit:
if ademail in form.email_user.data:
return redirect(url_for('admin'))
elif useremail in form.email_user.data:
return redirect(url_for('user'))
return render_template("Layout_log.html",form=form)
@app.route('/admin')
def admin():
date=datetime.now()
elegante_date=date.strftime("%A %d %B %Y")
"""
for temporary use only we will give some dumbass data
"""
return render_template('Admin/Layout_Admin.html',date=elegante_date)
from enum import unique
from Flaskiproject import db
# from sqlalchemy import Column,Integer,String
class Students(db.Model):
id=db.Column(db.Integer(),primary_key=True)
fullname=db.Column(db.String(50),unique=True,nullable=False)
dialling_num=db.Column(db.String(int,15),unique=True)
from flask import Flask
from secrets import token_hex
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
app=Flask(__name__)
xa=token_hex(16)
app.config['SECRET_KEY']='abcdef5fe2659e'
app.config['SQLALCHEMY_DATABASE_URI']='sqlite:///PFA_DB.db'
db=SQLAlchemy(app)
import Flaskiproject.routes
here's the error
https://pastecord.com/agukirafeg
@desert estuary try only date=datetime.now
without parenthesis
@desert estuary try only date = datetime.now
Yh
thank you
actually i solved the problem before hand it gave me a weird error and i restarted the computer and now it worked
would such a problem would happen if i hosted it if yes how should i deal with it
Hello... I am unable to validate a php contact form on my website.
<div class="container">
<div class="form">
<form action="forms/contact.php" method="post" role="form" class="php-email-form">
<div class="form-row">
<div class="form-group col-md-6">
<input type="text" name="name" class="form-control" id="name" placeholder="Your Name" data-rule="minlen:4" data-msg="Please enter at least 4 chars" />
<div class="validate"></div>
</div>
<div class="form-group col-md-6">
<input type="email" class="form-control" name="email" id="email" placeholder="Your Email" data-rule="email" data-msg="Please enter a valid email" />
<div class="validate"></div>
</div>
</div>
<div class="form-group">
<input type="text" class="form-control" name="subject" id="subject" placeholder="Subject" data-rule="minlen:4" data-msg="Please enter at least 8 chars of subject" />
<div class="validate"></div>
</div>
<div class="form-group">
<textarea class="form-control" name="message" rows="5" data-rule="required" data-msg="Please write something for us" placeholder="Message"></textarea>
<div class="validate"></div>
</div>
<div class="mb-3">
<div class="loading">Loading</div>
<div class="error-message"></div>
<div class="sent-message">Your message has been sent. Thank you!</div>
</div>
<div class="text-center"><button type="submit">Send Message</button></div>
</form>
</div>
Above is the index.html code
above is the first half of the php code
this is the second half of the code
Hello, I'm using Django and right now I'm creating web. Tell me it is better to use django admin web or create my own to CRUD?
Anybody can suggest or Any article for doing messaging system in django with Javascript and jQuery
i am using flask and sqlalchemy how can i delete the table which i have created
i mean the model i created
db.drop_all() and try again 🙂
if i want in particular ?
i mean a single model
what type of database are you using?
depends on your use but the django admin panel is a complete package
mysql
oh it's my first job so I have a lot of question how to do it. But I was thinking the same. Thanks
so login to your xampp or whatever server its on and go to phpmyadmin, then remove it from GUI @merry kelp
Honestly, yeah, that might be better
I've got no clue how to use mongoDb on Django tho
ok
its in http://localhost/phpmyadmin/ @merry kelp
download DBeaver and connect your database there, you will easily be able to drop tables etc
thx
mongoDB is hard to learn? @thorn igloo
I don't know, never learnt it
the first time is always hard ;b
but need makes us learning
<html>
</html>
MongoDB is a must skill anyway for python backend
so it is good oportunity to get a hang of it ;b
a must?
you think so, my must is mysql / postgres / sqlite
i think it's an optional thing to learn
Yeah, I need to check that out
Any hints on how to set it up?
let me hear your opinion?
I know that MongoDB company has free online interactive course regarding it
tried its beginning at least
opinion on what exactly?
or may be actually not fully free
and better to skip them
at least I did not like them
abandoned at the begining 😉
anything... come on I'm just a beginner..... anything will do as long as it's not too harsh
bro, html+css is one of those combos where the code doesn't really matter but rather what it looks like
also you're using the label tag wrong
well, there is always an option to hire web designer to make design in figma
oh
and actually code a bit matters there too
well back to work.
it is possible to make spaghetti out of html+css as well
I'm checking out a guide on how to set it up with PyMongo and I guess I'll just read the docs until I get it lol
sounds like a good plan
guys
any way we can create child views in Django
like the login required mixin is repeated so many times
can i do this in a non repeating way?
what is happening?
um actually i am making user to login .... and trying to validate him
ok, but what is happening? what are you actually seeing when you do your tests etc?
i am seeing again admin page instead of database page
i configured the problem thx for concern
i was not inserting csrf tag into page
oh ok
@inland oak why is this so complicated damn
how much diversity in data you plan to have 😉
perhaps you could just store it in binary file
window.addEventListener("load", () => {
const canvas = document.querySelector("#canvas");
const ctx = canvas.getContext("2d");
//Resize Canvas
canvas.height = window.innerHeight;
canvas.width = window.innerWidth;
});```
Why is the canvas bigger than chrome? Those scroll bars come and its annoying
someone please
why are you setting the canvas to be the window height and width? that's literally the viewport size meaning your entire screen
it doesnt matter now. i just disabled scroll bars
ok
Guys any tips for CSS. Why is it this way
I haven't worked on any real world project so am adking just outa curiosity. Will there be some kinda blueprint for the design of the webpage or the web dev is put in a room and tortured to give the webpage👀 @thorn igloo
depends on the size of team.
Technically design of web page is a separated totally skill consisting two professions: web designer + ui/ux designer (which is often made in figma)
but frontend web devs learn this skill as addition too more or less
to be fair, @sterile swan it's this way to allow flexibility while trying to convey context at the same time... it used to be that if you wanted elements inside of elements you had to put it inside of a table
thesedays, however, you have 150 different screen sizes and types... aka DPI's... so the code has to do more
i guess the datetime wasn't the problem bcz i just commented it but the thing didn't wanna work out again
the same error popped up
dialling_num=db.Column(db.String(int,15),unique=True), what is int there?
what's it supposed to do
the dialling number of the student
so i kinda know how the problem is caused so basically in powershell i called python and did this
Hey @desert estuary!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
i'm reffering to this specifically:
db.String(int,15)
what is int supposed to represent here?
uhh integers like int ?? idk
to just accept ints i guess
so if someone types
bro, where did you get that you can do that? cause there's no such thing on the sqlalchemy docs
db.String represents a string, a string can be entirely made of digits etc. my guess is that this is the cause of your error
for example
i corrected it
from Flaskiproject import db
class Students(db.Model):
id=db.Column(db.Integer(),primary_key=True)
fullname=db.Column(db.String(50),unique=True,nullable=False)
dialling_num=db.Column(db.Integer(),unique=True)
branch=db.Column(db.String())
occupation=db.Column(db.String)
def __repr__(self):
return f'Student:{Students.id} {Students.fullname} {Students.dialling_num} {Students.branch}'
this sounds like something you need to validate when the user tries to submit
here
you're still getting the error after that?
.
also you forgot closing brackets for occupation, should be :
occupation = db.Column(db.String())
i should also ask, is this your only table?
it must be Integer not Integer()
this is the new model you want to use?
delete the .db file so it creates a new one
class Students(db.Model):
id=db.Column(db.Integer(),primary_key=True)
fullname=db.Column(db.String(50),unique=True,nullable=False)
dialling_num=db.Column(db.Integer(),unique=True)
branch=db.Column(db.String())
occupation=db.Column(db.String())
def __repr__(self):
return f'Student:{Students.id} {Students.fullname} {Students.dialling_num} {Students.branch}'
i used this and it works
ig error could be from another part of code
why what exactly?
why yours worked while mine didn't
was it bcz the import
bcz i was importing db and models in the same time
and if so what's the difference between importing the module and from module import *
that's what i thought in the beginning but i've been told to not to do so
why btw what's your reasoning
cmon man, store it in string so you will save memory, you can always cast to int later when processing data, please @desert estuary
no, you can use string, db.String(int,15) this is just wrong syntax
you wanna store 9 digits number in int? lol
int should not be there
even more than 9 sometimes
should be db.String(15) rather
US number has 10, and plus direct number? its even over 12 digits sometimes
ofc it should be string
and well, to answer your question, i am using the flask shell context, so i am not sure how you are running your thing, and if you want to create a table or tables with db.create_all(), the class for the table should be visible in the shell you are using, which is why i used from models import *, it imports db along with my classes as they are
right, where you start your main project, there should be a shell, tell him @thorn igloo
I use git bash for example
there where servers runnin you mean
he can always run jsut shell, go to his main project and then run python from shell, it will be the sdame
he can manipulate DB from there
just importing 2 lines of db and depends where his models are
it's better to use the flask shell when creating the db because of the app context thing
its ok to use as I wrote too
you were programming in Java FX? so your nickname come from there? @thorn igloo System.out.println("Hello world");
no, just a name i came up with, for gaming purposes
Is it possible to save a non serializable object on the session?
what does
#search-result .listvideo li a
select
<div id="search-result">
<div class="listvideo">
<li>
<a href=""></a>
</li>
</div>
</div>
the anchor tag
thanks!
how to store session as foreign key in database?
do you know what a foreign key is and what it's purpose is?
how to select foreign key by session in django
@pine torrent I feel like you're asking a question but I don't understand what you're trying to do?
how to connect variable with selection tag to be selected in django
I need help passing a return value from a webpage to javascript to create an alert output
hey fellows
👀
couldn't you just output the script results directly into the template?
It requires an input to run from a drop down.
So I have to get the value, attach it to the end of the url since the app path is game/<move> and it’ll run the python script.
oh, you're facing a quandry that i've always had a hard time explaining well... it SOUNDS like it's related to when the javascript is being loaded into the DOM - if you were to change JS to an "on" event handler instead, you could trigger that based on a DIV or object that is stable (and not inserted by JS after DOM prep) - i have more on this if this sounds right to you?
wait, forgive my ignorance, you said python script, not JS script
Yeah I edit to make it clear. Not use to using multiple scripting languages at once 😅
Honestly I’m only using flask to showcase python skills for potential employment eventually.
Okay I’ll look into Ajax. I have to use document.GetElementById on the select box to concentrate the url right?
ah, i'm the reverse... well established, well qualified PHP/HTML/CSS/JS/SQL programmer breaking into Django because i want something easier :p
Oooh full stack lol.
yeah - it's a difficult place to be :\
you're either "great but not exactly qualified" or "we want only this"
Omit the extra from resume. Seen that not listing anything that would over qualify you such as degrees or skills actually help for the “we only want this” situations
haha yeah, i broke out and went freelance for now - i'll hit the churn later
The dream. Freelance development and small quantity electronics component store. Radio shack but cheaper.
And it services.
I have a ways to go. Gotta get my CompTIA a+. Anyway, I’ll try Ajax. If I need further help mind if I ping you?
nah, feel free - AJAX should serve you well, if you have JQuery installed it could be as simple as one line 😄
careful - it can become gnarly if you begin loading content in via AJAX and not keeping track of the "global namespace" for javascript... if you get heavy into it, i can recommend reading for ya
I’m only using it because I didn’t enjoy the idea of loading a new page from my portfolio. Espeically since it’s a small sample of my Rock paper Scissor discord bot.
so it turned from that super complex code to something so simple... i hate how django mocks me sometimes...
Hi, from the DRF documentation, 'serializer_class' attribute is only for GenericAPIView class, but why does it also work with APIView class? I cannot find anything on it
I know that GenericAPIView is a descendant of APIView, so shouldn't it not work? Maybe im missing something related to OOP?
for example, extending APIView using some attributes from 'GenericAPIView' works...why?
Bro best free resources to learning django anyone
Docs are pretty good if you can get into it xD
Thanks space
np, i tried doing tutorials and skippin docs, but that was a huge mistake
Can someone recommend a resource or help with creating a basic Django API that just returns a string for example? I'm following the Django REST tutorial but it's so overcomplicated it makes no sense. Does it take 50 times more code to just return something with Django REST than with FastAPI?
bro just use viewset/router and model serializer
That's what the tutorial showed also but it's super overcomplicated for such a simple task
And I've yet to figure out how to return something specific
since the tutorial's code doesn't even have a return
just keep the return and request.method
and the api_view decorator
and return anything
thats it
But why are the serializers needed
its not
its only if you have a model
if you're returning a string just return a string
yeah
Django, API, REST, 2 - Requests and responses
it took like 2 hours to go through all the parts
Well I'm at part 1 and don't understand anything
Nor see why is 90% of that code even there in the first place
FastAPI took me literally 2 minutes to set up
yeah its called fastapi
its also not a complete framework
if you're just trying to return strings then go ahead use fastapi
maybe look at django docs
I would but it doesn't make much sense to run the web app on django and run a single API function on fastapi
which is the best frontend framework to work with django?
it sounds like you don't really understand the point of serializers to begin with
You're right I don't, I have no idea what's the point of them nor why do I need them
ok, so you might be getting ahead of yourself trying to jump too far ahead
maybe take a beginner tutorial on backend development or django
I'm almost 100% sure I don't need them
I just want to return a function
Without having to write 50 lines of code in 5 different files
lol you sure as hell need them if you dont understand the basic underlying principles
such as serializers
best? what's defined as best? Bootstrap is universal
So everything in Django is 50x the code length of FastAPI?
I haven't had to use serializers once with FastAPI
you're going in circles bro
instead of blaming the framwork
it seems like you really have no idea of the basic underlying principles
you're ganna go far as a developer
i showed you the code already
just get rid of the serializer part
if you just want to return a string
So perhaps could you show a code that doesn't have any of the useless stuff in them just what I need?
I want to return this is a string
dude you're asking the question, you show the code
Show what code
whatever you have so far
Martin - i've never used FastAPI but I guess based on what i'm seeing now, why are you coding in Django? it sounds like you have something else you like more...?
If you have a very big project with authentication and stuff I'd say use django for it, but if you just want to make a simple API which returns a string use fast api
Because the entire web app is in Django and I don't want to run FastAPI too just to host a single function
The string example is obviously not the end goal it's just for testing
Well, the more abstract you go (more stuff you can do with a language) the more code it's going to take to do it
I want authentication & rate limiting etc. which is tough in FastAPI
FastAPI is focused on API calls, Django is focused on displaying a website
But all I want is to return a fucking function lol how hard could it be
Oh, but it's gonna take a good amount of code just to return a single string
But why
I'm probably like... stupid here... but i don't consider 8 lines of code a lot of code
In Django views can't return strings, it needs to return a Response object
Can you send me those 8 lines?
in PHP to return a function through an API call you have 5 documents spread out with 38 lines each
Yeah I did it with HttpResponse
That's, Django...
said here from space
But I figured I shouldn't use that
I'm looking for the bare minimum I need for what I want
just remove the unneeded stuff
surely you can tell which of the things aren't necessary?
But I don't know what's unneeded that's my whole point
Just have a view which returns a JsonResponse
.<
That's what I'm doing now but then what's the point of this entire API framework?
I thought the point was to make it even more simpler
also it does make things simpler, but there is more setup required, not everything comes without a cost
That's for making advanced apis, for your case just a simple view which returns JsonResponse will be enough
from django.http import JsonResponse
# In your view function
return JsonResponse({"message":"test"})```
!d django.http.JsonResponse the docs for it
class JsonResponse(data, encoder=DjangoJSONEncoder, safe=True, json_dumps_params=None, **kwargs)```
An [`HttpResponse`](https://docs.djangoproject.com/en/stable/ref/request-response/#django.http.HttpResponse "django.http.HttpResponse") subclass that helps to create a JSON-encoded response. It inherits most behavior from its superclass with a couple differences:
Its default `Content-Type` header is set to *application/json*.
The first parameter, `data`, should be a `dict` instance. If the `safe` parameter is set to `False` (see below) it can be any JSON-serializable object.
The `encoder`, which defaults to [`django.core.serializers.json.DjangoJSONEncoder`](https://docs.djangoproject.com/en/stable/topics/serialization/#django.core.serializers.json.DjangoJSONEncoder "django.core.serializers.json.DjangoJSONEncoder"), will be used to serialize the data. See [JSON serialization](https://docs.djangoproject.com/en/stable/topics/serialization/#serialization-formats-json) for more details about this serializer.
Python discords api uses the Django rest framework
How can I take in args?
For example if I wanted to do
def api_test(request, x, y):
result = x * y
return JsonResponse({"result": result})
And then make the request like url.com?x=1&y=5
The Django docs are so shit
Great argument thanks for the input
@velvet yew not quite true.
https://www.django-rest-framework.org/
Django flares as API good too
Django, API, REST, Home
I would say Django is universal all around tool
the only thing it lacks...
having a bit better async support. It is only halfly ready, but it is already there.
the last part is remaining, Django ORM to be converted
Does anyone know about this?
Can you help with my example?
as far as I understand serializer_class is multi purpose thing, I thought its main usage is needed for mixins
https://www.django-rest-framework.org/api-guide/generic-views/#mixins
creating either CRUD for all operations at once or
for particular operations with mixins like:
CreateModelMixin
RetrieveModelMixin
UpdateModelMixin
DestroyModelMixin
Django, API, REST, Generic views
which one
?
@api_view(["GET"])
def api_test(request, x, y):
result = x + y
return Response(result)
Yeah same thing
@api_view(["GET"])
def api_test(request):
result = int(request.query_params["x"]) + int(request.query_params["y"])
return Response({"answer":result})
@api_view(["POST"])
def api_test(request):
result = request.data["x"] + request.data["y"]
return Response({"answer":result})
Well that just gave me a headache
well, you can directly extract values from query_params, but you know, converting in advance them a bit better
there is another solution though
which involves probably less converting.
JSON supports transfering ints I think
btw, not sure if Response can transfer result like this. better giving away as dictionary
as proper JSON
it would be better
fixed example
two ways to input data for you
;b
they are different in how you should insert data though
first choice requires transfering input data as query_params
and second way asks you to input json
The query_params one worked the way I wanted it
@api_view(["GET"])
def api_test(request):
x = int(request.query_params["x"])
y = int(request.query_params["y"])
result = x + y
return Response({"result": result})
If anyone else searching for this
xD. the only thing it is missing...
@api_view(["GET"])
def api_test(request):
x = request.query_params["x"]
y = request.query_params["y"]
result = f"{x}, {y}!"
return Response({"result": result})
query
f"{url}?x=Hello&y=world"
output:
{
"result": "Hello, world!"
}
ah thanks, i think the problem is the example was setting 'serializer_class' as a custom attribute and i was confused by it
since it calls self.serializer_class and uses it
Getting a Django error. Question in #help-grapes
in the github oauth docs, one of their URLs is completely wrong and returns a 404 error, does anyone know why or what the correct url is? (https://github.com/login/oauth/access_token with a POST request)
Im having troubles with jinja. When i load /rps everything works perfectly fine. When i go to /rps/<move> or /rps/paper it decides not to load any css
probably because you aren't having properly relative static urls
try to use {{ static load }} or something like that, supplied for jinja
it will make static addresses attached to your web framework particular things
as easy dumb solution...
you can just try to replace your current static file address
you had like blaablabla
replace with ../blablabla
it will make it seeking static file in folder by one level higher
I have no idea what happened but i changed it from static/css/styles.css to url_for and now its worse. nothing works instead of just the one page lmao
<link href="static/css/styles.css" rel="stylesheet"> is how i currently have it
oh. idea.
<link href="/static/css/styles.css" rel="stylesheet">
what if to try this? 😉
Well my thing is that works. For every other template and app route i have. Except my new one
the problem is probably because you have relative address
while your new one expects having relative address ../static/css/styles.css
perhaps absolute one address will work
/static/css/styles.css for all pages
I apologize. That worked. Its too late to be coding lmao. I should turn in, its 4 am
the spirit is willing but the flesh is weak
Got it working. gotta space out the project block and on to sampling my next project
https://feedback.harperdb.io/suggestions/195304/flask-plugin-for-harperdb
If you're a flask developer/enthusiast and you use HarperDB or are a fan of Serverless solutions.. Kindly upvote this, so it gets better priority as a necessary tool in the space. Thank you
path('password-reset-confirm/<uidb64>/<token>/',views.PasswordResetConfirmView.as_view(template_name='users/password_reset_confirm.html'),name='password_reset_confirm'),```
why errror now
@mystic vortex yes
I need help with flask
My code is giving me 502 http error
show code
ohh internal server error
import winsound
from time import sleep
driver = webdriver.Chrome(r"C:\users\ARMcPro\Desktop\chromedriver.exe")
driver.get("https://www.google.com")
while True:
sleep(1)
if driver.page_source.find("test") > -1:
driver.refresh()
else:
winsound.Beep(500, 1000)```
I am trying to make a program which detects a specific change in a website (google is a placeholder here)
The program works for a while then it raises a `RecursionError: Maximum recursion depth exceeded while calling a Python object`
its a simple keep alive commands
Does anyone can give me idea on Open Source Contribution in web?
I can not know how to choice or find a project to contribute as beginner
Hey my template in django seems to not find css files I'm linking to
basically when I run local developement server of template I want styled, nothing changes. I followed file structure in tutorial, but I found in different sources, different structures. However nothing I tried worked
did you set your static file directory?
your STATICFILES_DIR i mean
you should also set a STAT_ROOT as well
ehm
STATIC_ROOT **
yeah I didn't do that. My static folder is inside my app though, and I thought it's when you have some kind of static folder for whole project
could be missunderstanding
ok here is what you do
do you have your static folder ?
put the static files in your static folder
and then go to your console and type "manage.py collectstatic"
ok but should my static folder in my project dir or app dir.
yeah I used app dir all the time, this is why I included ss above, but yeh
nah I copied in both dirs, still nothing.
did you collectstatic?
It really seems like I missed some very simple step or made some typo, because right now I'm super lost
Is there a way to have a view send several "responses" after time goes on?
Like, say I have something like:
class FizzView(APIView):
def post(self, request, format=None):
data = request.data
for value in data.get("values"):
result = doSomething(value)
report = reportOnThatSomething(result) # This can take up to a minute
# I should send the report information here to the frontend, any clues how?
return Response({"Ok":"Execution completed"}, status=status.HTTP_200_OK)
Any ideas?
now I'm super confused. I added JS folder with simple document.write('hello') and it works, however damn thing still won't style my html
💩
i am working in flask with sqlalchemy i want to get all names of tables which are in database
bruh, your classes are essentially equivalent to the tables in the database, i believe there is a property you can use to set how a table name should appear, you can use that to retrieve the table name
if I want to expose ports of my docker container to other docker containers, I don't need to specify this in the dockerfile correct?
thx
Hey folks, does anybody know alternatives to Aloha-Editor that're more current/supported?
In essence, I'm looking for a rich text editor that allows client users to make changes directly on a div, which can then be pushed back to a server.
https://rawgit.com/alohaeditor/Aloha-Editor/hotfix/src/demo/boilerplate/
https://alohaeditor.org
The Aloha Editor Boilerplate - Just another demo page
https://ckeditor.com/ maybe this is what you are looking for?
In one of my microservices:
# settings.py
ALLOWED_HOSTS = ["*"]
I'm getting the error:
Invalid HTTP_HOST header: 'data_scraper:8000'. The domain name provided is not valid according to RFC 1034/1035.
but that should be valid?
oh - it's an RFC 1034/1035 thing. the host can't contain underscores
just a guess but it may want you to have a tld too?
my microservice doesn't have a tld atm (tbh I know nothing about them so I may be wrong), it's just running on 0.0.0.0:8000
but regardless, it's fixed, finally getting 200 status code
my microservice was called data_scraper, changed it to data-scraper and it works
feels much more bulky having django apps all over the place instead of having one monolithic web app
there's a balance to strike for sure
monoliths themselves aren't bad and you can over-microservice yourself
its important to design thinking about the domains and scopes of what is happening and where a monolith is good with satellite microservices in "orbit" more or less around it
whereas I'm currently trying to help our team disassemble a anti-pattern called "Big Ball o' Mud" where we have a monolith of monoliths. And slowly breaking it apart. Likely the final version will end up being 5 monoliths that are individual "apps" but communicate to each other and to the outside world via microservices.
Do you know any good guides to creating tests for django projects?
path('password-reset-confirm/<uidb64>/<token>/',views.PasswordResetConfirmView.as_view(template_name='users/password_reset_confirm.html'),name='password_reset_confirm'),
django docs
I mean any general guides, like how to make tests that will expose things like bugs or holes in your code.
@barren moth u know this error?
how the heck did you choose me
The chosen one
Hello Guys, I need help with this piece of HTML and CSS ```html
<div class="srv-grid">
{% for guild in guilds %}
<div class="card-wrapper">
{% if guild.joined %}
<a class="card-link" href="{{ url_for('dashboard_server', guild_id=guild.id) }}">
{% else %}
<a class="card-link" href="{{ guild.invite_link }}">
{% endif %}
<div class="card-server">
{% if guild.icon_url %}
<div class="card-image-icon" style="background-image: url('{{ guild.icon_url }}');"></div>
{% else %}
<div class="card-image">
<div class="card-image-placeholder">{{ guild.short }}</div>
</div>
{% endif %}
<div class="card-label">{{ guild.name }}</div>
</div>
</a>
</div>
{% endfor %}
</div>
So, the whole grid and cards show perfectly except: the images don't show. This is because the height is 0 in the computed CSS ```css
width: 100%;
height: auto;
``` This is my real CSS but the `height: auto;` seems to somehow just not work. Is it because the cards get added dynamically?
Btw, when I used the exact same HTML just with one hard coded card, the image did show, and it shows too when I set `height: 100px;` for example. So the problem is the `auto`
But I can't hard code the height, because it would be messed up on all other screen sizes than mine
Height auto will set the image size to the height of it's contents. The content height is 0px so it will set the image size to 0px.
But why is it 0
I don't want to hard code any heights because the cards' height will be different for each screen size
Maybe you have put it inside of a div or element what height is 0px. Or haven't set the height
.
How can I fix this? Also, I am trying to make it look like this page: https://discord.com/developers/applications
Theirs also uses height auto
And theirs does not compute to 0
I don't know because you have provided very little css
I once even copied the discord page's CSS and still didn't work
So did you code the css yourself or just copied?
I tried myself and tried with the copied CSS
Even this copied CSS didn't work:
https://mystb.in/MonicaAtlanticSuitable.css
This is how it looks right now
https://hypixeI.net/
It's not that easy
What looks wrong,
Do you have images?
The image is gone
The image is there when I inspect it but just with height 0
And when I hard code height it works:
https://hypixeI.net/
That is just changing height auto to height 100px
Looks good
today I got a partner to connect to a jupyter lab with ngrok, but they couldn't make changes. does anyone know how I can do this?
please ping with any useful feedback.
If you want it to be square, you should set the height and the width to same value
But then when the grid is adjusting and making cards smaller, the image is still giant
Just not fitting
Hardcode the card width as well
Set the card to fit the images then
Any other ideas how I can get the height auto to just calculate correctly?
You should code it from the start by yourself so you understand what it is doing
Well I thought I did.
But the auto thingy just refuses
Is the hypixel link what you are working on?
I mean are you building the site or can you share the code. Maybe I can help you with it
What more code is there to share?
The quart backend
But
That can't possibly matter
No I want only the css and html. Is it running on the hypixel domain?
I sent it
Alright
Or is there more
That you need
oh btw the whole HTML block is in a container
If that matters
wdym
Well
imported bootstrap and daisyui
The whole HTML block I sent is inside a container (bootstrap) inside a flexbot (daisyui)
image
Didn't do anything
https://hypixeI.net/
I am afraid I can't help you without knowing what css goes in to the parent divs
Yeah, if you can build it with just bootstrap that'll be great. Otherwise it's hard to make while you mix bootstrap and own css
That's just the HTML I sent
And the CSS I sent
The weirdest part is that when I copied the CSS from discord's card image, the auto still gave 0
There might be some css you missed, but I am sure you'll find a solution for it
I gotta go
I have tried for 3 hours
Also looking at discord's for a while
So confused
But thanks
Is question regarding selenium applicable here or under #unit-testing ?
If your question is about testing and you're using selenium for testing, you can ask there
If it's about "how to select x element in my website" then maybe this channel is better
Okay so now I figured out that just using bootstrap img-fluid works perfectly, except: when the icon is not found I am trying to add a blank background and centered text. I can't just use the same img-fluid, because it's not an image
https://hypixeI.net/
How can I make that responsive too
Hi please I need help
...
am using gunicorn for multiprocessing of parallels clients requests and I want to improve the performance of my app. Does celery works well if applied directly on an api route it is more useful for backgrounds tasks. And check with me if my call to celery is correct:
`from celery import Celery
def make_celery(app):
celery = Celery(
app.import_name,
backend=app.config["CELERY_BACKEND_URL"],
broker=app.config["CELERY_BROKER_URL"],
)
celery.conf.update(app.config)
class ContextTask(celery.Task):
def __call__(self, *args, **kwargs):
with app.app_context():
return self.run(*args, **kwargs)
celery.Task = ContextTask
return celery
We use the Flask framework to create an instance of the flask app
We then update our broker and backend URLs with the env variables
app = Flask(name)
app.config.update(
CELERY_BROKER_URL=os.environ.get("CELERY_BROKER_URL"),
CELERY_BACKEND_URL=os.environ.get("CELERY_BACKEND_URL"),
)
create an instance of celery using the function created earlier
`
cel_app = make_celery(app)
Thxx
You should probably be using bootstrap's grid system
How does that help me
The grid works and is responsive
Isn't responsiveness what you were asking about?
Can you clarify what kind of behaviour you want for those black avatars?
You just need each card to take up the same height in each row
yea
But the size of the images in managed by the img-fluid. But that does not apply to the black thingys
Img fluid just gives max-width: 100% and height: auto
So you should give your cards explicit height and width
I tried adding that to the black thing
But then it isn't responsive?
You can set a max height, for example
Any ideas how I can make it as big as the img's
The images use img-fluid, right?
yea
So I think with those settings, it tries to preserve aspect ratio, and fill up the width of the boxes. And the height is whatever is needed to keep the aspect ratio.
The width is sort of fixed - it's determine by the grid system
yea
But your black box has no notion of an aspect ratio or whatever. It doesn't have anything is can relate to in order to set its height
CSS doesn't support relating that to siblings afaik
Is it .img-fluid actually making it responsive? Or is it the grid?
img-fluid
So I think you need either to set a fixed height or fixed max-height.
Or is it better to compromise and just set a static image when there is no server icon
Well, you could use flexbox (pretty much a responsive grid) and have the cards have explicit sizes
Maybe. I think the current reason the image containers have the same height is cause you happen to be providing images with the same aspect ratio. I imagine that if you used images with different dimensions, they would also have the same problem as the placeholders you currently have
Are there anyone who know about this topic plz I posted my question many times in many groups without results, where are the python masters 😩
Any suggestions any groups...
Sorry I have no idea - never used celery
even in stack overflow anyone replied maybe my question isin't good enough?
Please best group to ask about flask
or about job queue topics
This might be more a Database error question, I am having trouble with this SQLalchemy error:
File "C:\Users\LuMi\crossfit\routes.py", line 123, in signup
role = 'admin'
confirmed = True
created_on = datetime.now()
password = form.password.data
newuser = User(username, email, role, confirmed, created_on, password)
db.session.add(newuser)
db.session.commit()
elif request.method == 'GET':
return render_template('register.html', form=form)
File "<string>", line 2, in add
File "C:\Users\LuMi\crossfit\venv\Lib\site-packages\sqlalchemy\orm\scoping.py", line 23, in _proxied
return self.registry()
File "C:\Users\LuMi\crossfit\venv\Lib\site-packages\sqlalchemy\util\_collections.py", line 1010, in __call__
return self.registry.setdefault(key, self.createfunc())
File "C:\Users\LuMi\crossfit\venv\Lib\site-packages\sqlalchemy\orm\session.py", line 4101, in __call__
return self.class_(**local_kw)
File "C:\Users\LuMi\crossfit\venv\Lib\site-packages\flask_sqlalchemy\__init__.py", line 175, in __init__
track_modifications = app.config['SQLALCHEMY_TRACK_MODIFICATIONS']
KeyError: 'SQLALCHEMY_TRACK_MODIFICATIONS'
in Stackoverflow they say this happens when you have two instances of flask app(). But I have just one instance
does anyone know what triggers this error?
Hi. I have the following problem, I want to create an api in django. I will describe the different steps:
- I want to retrieve data from a certain address using requests.get(url).
2.Then I am going to parse this data and extract what I am interested in. (The data is about cars e.g. Name, year of manufacture, color)
- then this data is to be returned using the GET method I created with the ability to filter by name.
My question is this, should I create a model in django from the retrieved data and then use DRF and django-filter for filtering or is there an easier way?
I will add that without filtering I would be able to do it just by returning the json but I don't know how to go about filtering
it depends
if your data lives on another server, you don't need drf
if it is your own database, then models and drf is for you
since, in your situation, you are getting data from somewhere else
you don't need django rest frameworjk
or at least the serializer part
it still is good if you are building any rest api
how do I check the "SECRET_KEY" in app.route
(flask)
I'm learning Django REST right now, but I can't find anything in the documentation about how to POST foreign keys. I can see the foreign keys when using the API Browser but I have no clue how to do it in Postman with raw json...
nvm... I didn't read hard enough, i got it now.
@app.route('/',methods=["GET","POST"])
def login():
form=Login_formcall()
if form.validate_on_submit():
if form.email_user.data.split('@')[1]=="direwa.com":
if Admin.query.filter_by(email=form.email_user.data)==form.email_user.data:
redirect(url_for('admin'))
else:
flash("you don't exist")
elif form.email_user.data.split('@')[1]=="ecolewa.com":
if Students.query.filter_by(email=form.email_user.data):
redirect(url_for('user'))
else:
flash("the User doesn't exist")
else:
pass
return render_template("Layout_log.html",form=form)
i wrote this and finding difficulty to understand it
if Admin.query.filter_by(email=form.email_user.data)==form.email_user.data:
redirect(url_for('admin'))
```im telling it if the filter == form.email.data
do the redirection to the admin page else he's not existing
(sidenote :please give me a nicer way to tell the admin he doesn't exist)
and yeah idk if that's the right way to do it or no
so, I have a couple questions
I'm making a website with quite a few features, and one I have in mind is a top banner message that I or a different admin can set from the Django admin dashboard
perhaps I'm missing something in my learning... but how do I just make a single text entry field for something like this?
a model seems a bit much for something like that, maybe
Any good/tried and tested books to learn Django from?
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
go to books section and see two scoopes of django
@native tideI guess for the sake of keeping the main one clear, making it easier to read.
As well as making it easier to remove/add apps.
You can use if Admin.query.filter_by(email=form.email_user.data):
There's no need for the '==form. email_user data' because the above query will return an Admin object if found in the db but will return None if not found
Use app.config["SECRET_KEY"]
hi, im just leaning basics . so here my qn is how to remove the space between the boarder that i marked?
Do you have any margins set in your css?
i set all margin{0 px 5px}
The margin is what causes the space. If you want to remove the space, remove the margin on that specific container
this is what happened when i set the container margin:0px;
the green boarder represent the container of the image and text.
*border
the whole boxes are also in a one big container😆 .. its kinda crazy , i dont know how those big websites are made using flex
Can I see your html code for the page?
You'll learn it some time
Hey @restive whale!
It looks like you tried to attach file type(s) that we do not allow (.html). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a.
Feel free to ask in #community-meta if you think this is a mistake.
Hey @restive whale!
It looks like you tried to attach file type(s) that we do not allow (.scss). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a.
Feel free to ask in #community-meta if you think this is a mistake.
The image and text should have margin set to 0 px
ohh..ok..shey..that was simple...haha.. thanks man..
so even if we already set margin to 0px with * there will be margin for those boxes? it wont apply to all elements ?
I'm not sure about that. Personally, I prefer not to set margins and similar stuff for all elements. Setting margins on individual elements makes it easier to keep track of each element's margin
so the way you have set the margin with two values .... margin : 0px 5px ....sets the value 0 value to top and bottom and 5px for left right
@jovial cloud thanks for help
@bright lodge yes, that was tutorial in freecodecamp abt media query
is that a light theme?
definitely a designer xP
My eyes hurt lol
hey y'all, i've been trying to resolve this issue since yesterday in various channels, but no avail. so i opened a stackoverflow thread. Please feel free to take a look at it 🙂 https://stackoverflow.com/questions/68284089/what-triggers-the-keyerror-sqlalchemy-track-modifications
You're welcome
Hi
Please help
I want to render multiple dicts json to fornt
all in the same interface
but each one in a specific tab
and the tabs have to be created dynamically based on the number of dicts
a basic example
[{"name" = a, "age" = 29},{"name" = b, "age" = 19}, {"name" = c, "age" = 28}]
the first tab with be a table containing the first dict {"name" = a, "age" = 29}, the second tab a table containing {"name" = b, "age" = 19} and so one
knowing that I don't now the length of json in advance
hello ,what should i give the client when his site is ready?how can i receive him all access to his site?
Make an API call to your endpoint, which returns an array of objects (JSON encoded). On your frontend, decode the data, and iterate through the array making a new table for each object.
@lapis basalt
Easily done with JS or jinja templates
@rustic sky If you want different admins being able to change it, a model is the way to go. Other than that, you can have an API that sets env variables, but anyone could query that unless you have auth
How does sending an image work using api work?
Like when you Request an image from this api https://thecatapi.com/ how does it send back an image?
I mean it only sends a link with an image but how does that link show the image? When posted like
^
The link is embedded in some platforms
It's not something the api does
They just return a link to say, a png file, which the platform, in this case Discord, embeds
It could be the link to a png file
Wdym link
But then on server side how did they linked that file.png?

The image is stored in the server's filesystems
yo there
are you using flask?
not really
Nothing yet I'm still thinking how things work so I know what to do
do you are the slave of java script
But how does the url relate to the system file 
and then when you request for the file, it uploads it as a file response (you can have json, html, xml, file responses, etc)
at a high level

no 
well as Addike said, you normally save them on the server system and then you can create a url that serves this images, as long as the image name is dynamic and exists on the server, the server or your backend will send it back
Server system is like your storage file.png ?
yes, you can save them locally or use something like aws really,
yeap
What about Firebase 
Say an api can send files, when you request to mydomain.com/get-file/<the file name>
and you make a request to mydomain.com/get-file/image_of_cat.png
So it looks in its files for image-of-cat.png, and then uploads that as a file response
💯
Oh I somewhat get it
so the url that you make the request to would normally give the api information about what file you want
This is more or less what cdn's do
I somewhat get it thanks

But what about options on where you store them
I don't want people seeing some of those images in my github repo

it would just be a different "route". Maybe this api says that to upload a file, and store it, you need to provide the file, and filename (as request data) in a request to mydomain.com/upload-file/
So you would make a request, with the filename in the request data, and upload the file along with it. Most requests libraries have a simple class/function to allow you to upload files along with a request
That would be a bad way of storing your assets 
What's a recommend way
You could write a cdn (basically the api I'm talking about) to handle serving your files
Alright 
a cdn = fast api to serve files
https://thecatapi.com/
But do you have any idea where this guy store his images?
normally a cdn would use many servers around the world to decrease serve time 
but thats not required
Either he gets it from another api 😂 or somewhere on his vps/hosting service
:thinkie:
Will the cdn and your api be in different places? 
wdym?
Not necessarily. You could host it on the same vps, and domain as well 
Like your cdn could be on cdn.mydomain.com or mydomain.com/cdn
and the api could be on api.mydomain.com or mydomain.com/api
good choice, but make sure you know asynchronous programming before trying it out 
It would work
But I don't have domain and such
If you're a student, you can a couple free with github education pack
It takes months to get one 
no 
It takes at most, 1 month to get it 
but if you have a verified school + email id, it would only take a few hours at most
if not, it could take upto a month
Verified school is doubt
might take a few weeks then 
But wait a minute ....
Cdn is for file handling and Api is for request handling?
if your api only handles files, then it would be a cdn, of sorts
I'm am confusing myself too much 
😂
yes yes yes
price=models.DecimalField(decimal_places=2 ,max_digits=1000)
TypeError at /admin/products/product/
argument must be int or float```ig error is in ^^ price instance
@lapis basalt Specify what you want more details on
@opaque rivet sir help 
btw done corey's playlist and i have 2-3 doubts to ask , others things are done made todo app , blog app with all features sign up sign in profile and all , now doing CodingforEntrepreneur video then will do a e-commerce website development on own then django react rest framework

@dusk portal i cant help with that, you're passing a arg to your Product model which isn't a float or int
but that youtuber done that only
how can i fix bruhh!!!
You get the error after saving the object in the admin dashboard?
yes
after saving yes @opaque rivet
can u tell what should i change here
and what is a boleean field it founds tricky
@dusk portal so what are you inputting into the fields once you save the object?
nothing when im click it's throwing error
So you're just saving an empty object?
when i click on products not even any objects on whole Product app model in admin
yes
Okay... so is this what you're doing?
- In django admin, you select product model
- Create a new object
- Save that object without inputting anything into the fields
?
Please how to post a list of str in a flask rest api
I'd nuke the db, delete all of the migrations, and start the db afresh
if request.method == "GET":
word = request.args.get("word")
nb_links = request.args.get("nb_links")
select_filter = request.args.get('filter')
else:
word = request.json["word"]
nb_links = request.json["nb_links"]
select_filter = request.json('filter')
like this but words instead of word
with words a list
how
Yes @opaque rivet
Please how to post a list of str in a flask rest api
example:
if request.method == "GET": word = request.args.get("word") nb_links = request.args.get("nb_links") select_filter = request.args.get('filter') else: word = request.json["word"] nb_links = request.json["nb_links"] select_filter = request.json('filter')
like this but words instead of word
with words a list
@lapis basalt not sure what you're trying to do, what do you mean by "post"?
Can you rephrase
Hi, I have a question on Django admin page. I'm trying to register a form (not model) into the admin page, but my form consists of variables like user_id / =kwargs['initial']..., and as a result there's error when i try to add/edit the admin form because i have not passed this variables in... How do i do it ? :/
in flask how to send an input as a list to get or post request of a rest api as the previous example shows
Thxx
You can convert a list of strings into a JSON string, then send this in the body of a POST request. I assume you're using JS so use axios.
@opaque rivet thxx a lot . I am working on a full api
with flask
I want to send a bulk request based on a list of words sent by the client
after that how to recover please the input sent by the client as a usual list
I found a solution or that
json_obj = json.loads(json_string)
anyone can help me?
def register(request):
form = RegisterForm(request.POST or None)
if form.is_valid():
username = form.cleaned_data.get("username")
password = form.cleaned_data.get("password")
newUser = User(username=username)
newUser.set_password(password)
newUser.save()
login(request, newUser)
return redirect("index")
context = {
"form": form
}
return render(request, "register.html", context)```
I don't really know much about Django - is form.cleaned_data supposed to by a dict?
Can you send the RegisterForm class?
I don't know, I just started django
class RegisterForm(forms.Form):
username = forms.CharField(max_length=50,min_length=8,label="Kullanıcı adı")
password = forms.CharField(max_length=24,label="Password",widget=forms.PasswordInput)
confirm = forms.CharField(max_length = 24,label="Confirm Password",widget=forms.PasswordInput)
def clean(self):
username = self.cleaned_data['username']
password = self.cleaned_data['password']
confirm = self.cleaned_data['confirm']
if password and confirm and password != confirm:
raise forms.ValidationError("Parolalar eşleşmiyor.")
values = {
"username",username,
"password",password
}
return values
Can someone help me setup pm2 on my vps so i can start my website with pm2 start ... im using Ngix Gunicorn and flask
Honestly I'm not sure what the problem is - try looking into the value of form.cleaned_data
By the looks of the error, it is returning a 'set', which you cannot perform the method 'get' on
Ah I think I figured it out - potentially
form.cleaned_data = ```python
values = {
"username",username,
"password",password
}
because that is returned from your clean method
However, values's data type is a set. Did you perhaps mean to put colons instead of commas in your values variable?
So perhaps you meant ```python
values = {
"username": username,
"password": password
}
exactly
thanks for helping
np
Django 3.2, Python 3.8, any idea why random.randint(0,255) isn't working? i'm so confused.
Running into an issues with an app route I have for my website.
The Try-Except-Else block isn't doing what I want it too.
It's supposed to see if di or dn is equal to None then handle the TypeError and return user.html as the rendered template if there is an error, otherwise render thx.html
It currently is catching the error, then running the else statement, then crashes a minute later even though I added an exception handler for the TypeError, so it shouldn't be crashing, and should run the except statement instead of the else.
I'm not sure what I'm doing wrong.
Here's the route:
def addrec():
if request.method == 'POST':
try:
dn = request.form['dn']
di = request.form['di']
with sqlite3.connect("tinker.db") as con:
cur = con.cursor()
cur.execute("INSERT INTO users (user, user_id) VALUES (?,?)",(dn, di) )
con.commit()
msg = "Record successfully added"
print(msg)
except:
con.rollback()
msg = "error in insert operation"
finally:
if di == '425477636333240331':
return render_template("result.html", msg = msg)
con.close()
try:
if ((dn == None) or (di == None)):
msg = "Please fill the required fields"
except TypeError:
return render_template("user.html", msg = msg)
else:
return render_template("thx.html", msg = msg)
con.close()```
look here
it evaluates the comparison regardless of whether what i'm comparing is none or not
basically,
try:
if ((dn == None) or (di == None)):
msg = "Please fill the required fields"
this will never cause an exception unless dn and di are not defined
so im playing with fastapi, and im trying to spread some routes across files,
code:
from endpoints.contributors import contributor_router
api = FastAPI()
api.include_router(contributor_router)
only problem here is that its not including the routes from the router
From the random module you are importing the random function, that function has no attribute randint
import random
random.randint(0, 255)``` This should work
Hey guys so idk whats gotten into it, it was working just fine but after pasting some html code it happened like this, it does not render/display at it should
its django
it should display something like this
nvm I juts fixed it
Do you use docstrings in a Django project?
[HELP] Anyway to covert Django app to an exe? I want to serve my Django app as a desktop app and I can't figure out a way to do that, anyone with any experience?
django is a for web apps
should I make shadows in darkmode ?
I mean white shadows, or is it too much?
it looks ok or?
That looks pretty good
I think its too glowy you know what I mean
I now have it black, its inspirated by a guy from github, he said its more realistic 👍
because that’s random.random.randint
you want import random to use it that way
so here's what I'm trying to do:
i want to embed a python console BUT I want my python code to automatically start (without the user pasting in the code) and I want this to be embedded into a html website
I found this code online:
<iframe
style="width: 640; height: 480; border: none"
name="embedded_python_anywhere"
src="https://www.pythonanywhere.com/embedded3/"
></iframe>
but all this is doing is creating an iframe with the console website. Is there any way to achieve what I'm trying to do?
also not sure where to post this
how can i make a online ide ?
Hey, is anybody familiar with flask? I am trying to route to a custom login page, but I'm having no luck
It just goes to the default login page
AH HA, thank you - that makes sense now
wrong person, but whatever, thanks @vestal hound
Did u use redirect
Or @app.route("/login")?
wait
redirect
what redirect are you referring to
@real rapids
I used @app.route('/login')
it's flask security that is giving me the problem
i know how to override the html page now, but i'd like to be able to actually have it use my routing method
@dusk portal dms
Django project tree and runserver question in #help-honey
I don't know if thats even possible, but if it is, that would be extremely cool and useful. What you're saying is what ElectronJS does (with javascript) somewhat, its basically a minimal browser that runs html/css/js as expected
in fact, I believe Discord runs on electronjs. so everything you see in your GUI is just css and js on an html page
what should i do to make the background img fit to enitre screen
is the django rest framework needed to connect the backend and front end when using something like react or can i do it without
for eg i wanna loop through one of my tables with react, is the rest framework needed ?
it depends on where you have your table
if you extract table from some database
you need either 1) django rest framework... 2) or some alternative, Node.js for example
node.js is the most closest javascriptish thing for react devs
I am too much familiar with python to choose anything else though
in theory you can even use direct access from frontend to database
but... it would need having public login/password to database
probably
well, nothing prevents to use it, if there is frontend library for direct sql connections
except for how much big code complexity and security issues will be with this solution.
how much database would be have to tuned to setup correct permissions%
it is probably all possible, but you would have to be probably a monster of databases
and considering that it will remove from you architecture as code... (since I don't think there are advanced enough libraries for that) it is going to be messy
better creating normal backend (Node.js, or Django rest framework or whatever else backend offers) and pulling data from it
Is this a right channel to ask about django?
I've having a problem in displaying the profile image.
@ember eagle I forgot to update you. I say screw it and just made a new webpage for my small scripts lmao. Looks nice though.
prefectly right
so i wanna do a thing when the user visit the site his first visit should render a certain template to modify some data (to change his email or password and other stuff )after it's submitted in the database it should render the homepage idk how to express it here
@app.route('/user',methods=["GET","POST"])
def user():
formi=Userform()
return render_template("User/info_gathering.html")
oh
what is booleanfield
what is manytomany relation
now i have completed corey schafer's playlist and made some apps like contact form simple app todo app blog app with user sign up login and forgot password
how can i get to more advanced to make own projects
guys i need some help and suggestions regarding django and stuff if anyone there please tell
so firstly how did you finished that tutorial it's soo confusing i started with him and he start to make some weird stuff instead of making stuff clear from the beginning and also i guess you should go and check the documentation with some forums on the internet
are u seeing the web dev playlist of django
flask
cz i am also seeing it and ik its confusing but he is really good with explaining
oh ok idk about flask
i started with flask and he confused my fucking ass
F
flask has jinja right so its confusing ig
i mean django has it too but flask too
i have first done docs then his video

https://docs.djangoproject.com/en/3.2/intro/ done 8 docs
all 8
then 2-3 simple proj
then corey vid

1 month
oh nice
he is doing flask tho
if any food django dev online i need some suggestions so please ping me up if someone willing to help
why not linux
I am using windows 10
best solution is to move to linux
indeed.
