for i in teacher_courses:
fetch = CourseWork().fetch_course_work_by_id(i.course)
course_name = str(i.linked_teacher.course_name)
for cw in fetch:
for x in grade_info:
for p in x:
if(course_name) in x:
course_exists = True
if(course_exists == True):
new_dict = {}
new_dict['student'] = f'{cw.submission.user_submissions.first_name} {cw.submission.user_submissions.last_name}'
new_dict['coursework'] = cw.name
new_dict['status'] = cw.submission.status
try:
new_dict['comment'] = cw.submission.submission_grade.comment
except:
new_dict['comment'] = ''
try:
new_dict['grade'] = cw.submission.submission_grade.score
except:
new_dict['grade'] = ''
grade_info[0].update(new_dict)
print(grade_info)
input()
else:
y = {}
y[course_name] = {}
y[course_name]['student'] = f'{cw.submission.user_submissions.first_name} {cw.submission.user_submissions.last_name}'
y[course_name]['coursework'] = cw.name
y[course_name]['status'] = cw.submission.status
try:
y[course_name]['comment'] = cw.submission.submission_grade.comment
except:
y[course_name]['comment'] = ''
try:
y[course_name]['grade'] = cw.submission.submission_grade.score
except:
y[course_name]['grade'] = ''
grade_info.append(y)
#web-development
2 messages ยท Page 191 of 1
I need to check if the course already exists in the dict. For example "English"
if it does, it should create a new nested dict, and attach it to "English"
grade_info[0].update(new_dict) causes the problem of incorrect Syntaxt. It doesn't add the new_dict as a nested dictionary
I feel like banging my head against the wall haha. Been stuck on this for several hours now
What is grade_info[0]
well grade_info is list containing all the dicts that it loops through
I have created a text form in HTML and now I want to export the text typed there to my Python code from where I will store them in a MySQL database. which framework is the best for this task.
?
I have heard name of Django, but in it's introductory video every thing they said was about managing multiple pages, urls classes parsing etc. which I dont need now
so can you guys tell me the specefic things I need to know from Django to acheive my goal?
use flask, its newbie friendly and will help u learn concepts and understandings https://www.youtube.com/watch?v=mqhxxeeTbu0&list=PLzMcBGfZo4-n4vJJybUVV3Un_NFS5EOgX&index=1
Welcome to the first flask tutorial! This series will show you how to create websites with python using the micro framework flask. Flask is designed for quick development of simple web applications and is much easier to learn and use than django. If you are less experienced with python and want to learn how to make websites flask is the right to...
thanks
django is just a heavy weight version
that can handle more traffic
yes I got an idea there
(how can I pronounce your name), according to you, learning what is necessary is a good practice or we should learn everything about a thing?
also I have already written the code for my page using HTML, so can I use it directly or I have to rewrite the entire code again in flask's code?
how many django projects can I deploy on heroku's hobby dyno ?
def put(self,request,pk):
serializer = StockModelSerializer(data = request.data,partial=True)
if serializer.is_valid(raise_exception=True):
stock = self.get_object(pk)
print("working")
print(request.data)
print(serializer.data)
print(serializer.validated_data['quantity'])
serializer.update(stock,serializer)
response={
"data": StockModelSerializer(stock).data
}
return Response(response,status=status.HTTP_200_OK)
output
{'quantity': 5000, 'rate': 45, 'manufacture_date': '2020-5-10', 'expire_date': '2022-5-10', 'company_id': 1, 'medicine_id': 1}
{'quantity': 1, 'rate': 45, 'manufacture_date': '2020-05-10', 'expire_date': '2022-05-10', 'company_id': 1, 'medicine_id': 1}
True
True
1
True
45
why my quantity is taking boolean value
it in intergerfield in django
class Stock(models.Model):
company_id = models.ForeignKey(Company,on_delete=models.PROTECT)
medicine_id = models.ForeignKey(Medicine,on_delete=models.PROTECT)
quantity = models.IntegerField()
rate = models.IntegerField()
manufacture_date = models.DateField()
expire_date = models.DateField()
can anyone help me
How would I open a single Django endpoint for an external service to point at if I am using a FE front end? Since I am not using URL routes generally in this situation, is there a best way to open an endpoint? Do I need to just open the port and point at the django route/path as usual?
I have the BE port blocked via firewall at the moment.
Should I route a specific url through nginx, or just open the port and access that directly?
@native tide can you tell me do I need to study whole documentation of flask or just some parts of it?
Study what you need to get going and then just read more as you need it.
yes I was thinking same, just wanted to be sure @dense slate . Thanks
anyone here using django
?
guys like i am sending image as response into base64 using django. image already are above the 100 mb. but when i see its response in thunder client. thunder client is hanging. though i am getting output
a week is enough to learn from basics to making a simple CRUD API
You can port the html over into the Flask project as a template. If you want to make the page dynamic then you'll need to use jinja templating language for dynamic behaviour (to present variables from the application/DB layers) on the page
I would start by getting clear about your goal. What is it?
what is dynamic?
related to CSS based animations?
CSS is about style (form). Dynamic is another word for...I have data that I want to render on the page that changes. In other words, if I have a copyright footer with the year, and I want to keep the year always up to date every time the page opens, then that data changes. In other words, dynamic text that changes depending on the user's context.
ohh. no my page is a simple form. which I will use to take some input from the user and store it in a sql database
my goal
That's simple enough. You can use html to present the form. Django provides the application layer that will grab the data entered into the form and then store it in the DB.
a chinese/japanese man advised me to use flask, was he right?
Either Flask or Django is an option. However, if you've got just the one main application, I'd recommend Flask.
in flask do we need to include sql commands in python code? or flask has some included things>
Flask is much easier to get setup with, and provides all the functionality (based on what you've shared) that you'd need.
Flask uses something called Object Relational Mapping (ORM). This creates files that do the SQL work for you.
"In Flask web applications, to manipulate databases, we can use SQL and Object Relational Mapping (ORM). An ORM makes writing SQL queries easier for a programmer, because it enables us to write queries in an object-oriented language, and then ORM automatically translates it to SQL and retrieves the result as an object."
so we wont need to type actual sql commans like :
something like create database school;```
Django also uses ORM. I've used ORM quite a bit. There is still a learning curve.
what if I wish to use sql exclusively
No. But there is still a learning curve for how you query. You will need to learn about how to work with the ORM manager. However, there is plenty of info out there on it.
In my experience, it's very powerful. I've been working with ORM since July. You can check the url in my profile to see the end result
like storing user's input in the HTML page into a variable and then work with it normally like a simple sql and python hybrid code. Actually I am a bit experienced in SQL,
yes I have seen the website. since july you have got 2 amazing customers. congratulations
is this possible?
Very much. LanesFlow has 20 tables with lots of relationships and fairly intense datasets.
And I have no SQL experience to speak of
so now you know my goal, I want to bring user's input myfrom html page into my code. my html page just act as a simple front end, it doesnt needs to be hosted on web. considering this what all topics of Flask should I study, so that my job is done?
Flask will be the simpler start. You'll be able to accomplish your goals.
webapp
/models
/user.py
/user_details.py
each .py has a table inside. User has a relationship to user_details.
I get this error Mapper mapped class UserDetail->user_details could not assemble any primary key columns for mapped table 'user_details'
how can I split up my models, and not have this issue?
LanesFlow is built on Django. But then LanesFlow already has some 10 applications with more planned
nvm thats not my issue ๐
I have planned to go till Tutorial section in the documentation, as i think that would teach me how to bring the data from html page to code
FLask is great if you want to develop very quickly and the web application is simple (1-3 apps)
That's why Flask is a good place to start. You'll learn about the basics, such as serving the web page, coding the front-end/application/DB layers, which will allow you to move data from page to DB and back again.
actually my project takes input of some data like name class roll and admission number and stores it in a database. in first version, I didn't used a html page or a gui and thus the input and output screen was messy, so this time I focused on including some html pages
now I have only one page designed, and m working on it's backend
when all the pages and their backend are ready i will transform the code to .exe and release it for everyone's use
There are some excellent reasons to shift to a web application. Challenges with building an application for an OS is UI. There are tools for web application UI that look good
for this I have Flutter in my learning list
So you want to deliver through an .exe file? That's a different beast.
and it is one of the reason I don't want to lewarn unnecessary things as I have already have too many things to study
You could use web app to deliver for use and be outside the constraints of OS
not now, as i said my work in only 5% complete now
A web app requires hosting it though. Challenges with each approach.
instead of .exe I may release a flutter app that uses my python code as backend
based on server-client architechture
well, the beauty of having a web application is you can build an API to connect the application to. The web app becomes your DB for your app.
yes, personally I am not a big fan of web apps
really
?
Irony is, I am a fan of web apps...for complex applications. They're OS agnostic. Plus, when it's online, an API means it is accessible by any internet connected app. And if I build offline caching functionality into the app, then users can upload/download information when their device comes online
only web apps have apis?
If you build an .exe application (for windows) you have to recognize that Python is an interpreted language, and building a windows client for Python comes with hurdles. Plus, you're locked to the OS, and have to manage how it ages
No. APIs are interfaces between programs. Glue.
A web application is OS agnostic. It doesn't care...Win/Mac/Linux? All good.
yup, so my modified plan now is to transform all my code on which I am working now to API which I will access from a flutter app
Also, an .exe is generally built on a client-server architecture. Are you building the DB into the app? So it is local? Or are you looking for data to be shared?
yes that is a benefit, but the flutter SDK allows to develop both android and iOS apps from one code base, so lines are equal
True. But apps are inherently limited to what they can do. Smartphone OS's (Android/iOS) have constraints.
i am not sure, if some biological institute or philanthrophist is intrested in my idea/project then database will be shared
If the requirement is ultimately to have shared data, then I would go straight there...from design up.
me too. but currently I have to accumulate all the data
Trade offs for all approaches. Depending on the complexity of data collection, presentation and manipulation, a smartphone app could quickly become a big constraint.
once I have considerable amout of data then I would work on how to share it
Plus, the UI formfactor of a smartphone could also be a constraint
that's why I am planning to make the app just a client that sends request and fetches data from server
flutter has nice tools for that
If it is raw data collection, then I would be curious about whether data is coming in 1 by 1, or you also want to batch input (100s/1000s/more) at a time
Sure. But smartphones are physically small.
one by one. Its tedious๐
Tedious == not encouraging.
Building a tedious data collection interface is not a strong start.
I have seen some UI designers designing great interfaces for small screens too
Sure. Data collection is only half the story though. You also need to present and allow the data to be manipulated too.
I"m not writing off an app. Just highlighting tradeoffs
i know,,,but as I said if some institute or philanthrophist is intrested in my project or understands it's need then i have some plans for that like hiring people to manually type as well as develop some AI to summarize the content
And the more complex the datasets, along with the great requirement for manipulating/presenting the data, the greater the challenge becomes.
However, I'm back to data collection and your use of the word "tedious"
there are quite a few tradeoffs here but as you know success has it's cost
every great idea has trade offs
Sorry...hit enter ๐
If you want to prototype an app, Flask offers rapid value to explore. When you have a DB then you can build an API. With an API you can connect to an app
Hello guys ive never used JWT with DRF, can someone simply explains my questions.
- Why there is refresh token + access token? does that mean if the access token expired the user is not authorized until he goes to the refresh token url? if yes how would a user using the website knows if the access token expired + how he will know how to refresh it or how to do it automatically in django if thats not the case.
2.Why logging out blacklists tokens? my main goal to use JWT is to not store tokens in db and take more storage.
yes that is the planned roadmap
JWT's come with security risks IIRC. I remember seeing a video by a hacker showing how easy it is to hack JWTs.
I use Django's auth model to manage login and serving up controlled resources.
Not a direct answer though.
Flask is simple enough that it could serve you very well as a way to prototype the application quickly
Wow, thats also an important thing
After watching that video...wouldn't touch JWTs with a 10 foot poll
had u ever tried Knox?
@ionic raft according to you which approach is correct:
- study everything about a library before reading it?
No. Not needed to so far. The Django auth model seems very robust. SALT + HASH password storage. Strong
Access token is used until it expires, which is generally a short amount of time, like 5-15 minutes.
Refresh tokens "refresh" them to be good for another period of time.
Not how I learned Django. I focus on the pieces I need combined with pre-research to determine fit....like you're doing now ๐
- studying only as much required at the moment and remaining when it is needed?
Sure. Except the video showed exploiting JWTs to hack paywalls.
Do u mean Basic token auth, if yes doesnt that take doubled storage by storing both users and tokens?
means I am on the right track
Like Twitter and Medium?
Specifically, on registration to reveal DB structure and send back info to inflate priviledge without paying
No. Like poor use of JWTs. Like anything...poor understanding == vulnerability
But seeing data related to the structure being sniffable...not strong IMHO
JWTs had the feel of a hybrid of front-end and application security. I'm for an application-only authentication model personally
You only store the refresh token, but why are you worried about storing them?
more storage
I don't want permissions being applied on the front end. I want to have the application do the logical work to build the template, and send the built template. Fundamentally, JWTs feel flawed.
@ionic raft thanks for the nice talk. good night everybody, its 15 minutes past midnighht here
I guess? It's one field extra. I can't imagine that is detrimental to an app.
You're not using a FE framework if I recall, right?
You don't need tokens in that case.
Okay then, using Basic Token Auth is the best way I think....
Right. And big caveat. I don't know much about JWTs at all. But the little I've seen raised many more questions than answered
But anyone knows what type of tokens is basic token in django?
I suspect my impression was influenced by the idea that, I don't want logic on the front end. That's what the application layer is for.
httpOnly JWT
What's your reason for that?
okay ty!
When I saw the hacker sniff/intercept the JWT (token), inject a different value into the subscription level, and then release the token back to the server to bypass paying for subscription...yeah...that
Like I said...limited knowledge, and more questions than answers
Is I can get job only with django and html css js with jQuery or shall l learn React and django rest freamework
That sounds like it was with a poorly implemented token auth.
Sure. But the fact it was possible because subscription level could be passed into the FE for interpretation client-side...that was the astonishing part to me. That's what the application layer is for.
And likely poorly implemented architecture too ๐
The irony is, one app will need a FE framework. That's the research dance I've begun....
httpOnly tokens specifically do not allow you to modify them on the client-side.
Good to know.
Still not decided on how to proceed with choosing the JS framework. However, being able to focus on just the one app....potentially helpful. And, may want to build the data model, and then look to experience/expertise to help with the front-end.
can anyone suggest me some good tutorials on django?
YouTube - Corey Schafer. 3 years old, but still solid.
that's a very small tutorial I guess
It's a 16 part series
Yes I have seen
That series led to the website on my profile
the website mentioned in your bio?
Yup. All started with Corey. July 2021
great
didnt you follow any other course?
I also did a UDemy bootcamp (for Python/html/css/Flask) and read a book....plus other tutorials...but Corey's series was where I started with Django
can you tell the course name and the book name?
Hi. So I'm working on a Django project.
In that let's say I have this endpoint, "/account/register/", which displays the form for register on the website.
Now, when the user is registered (successful POST request), I want to display user name for that user saying "Hey, username you are registered".
So I know I have to use HttpResponseRedirect when dealing with POST. Can anyone suggest how to do that?
How can I display this info on that same endpoint "/account/register/" and not creating a new view for that or new endpoint.
100 day bootcamp for Python (Dr Angela)
Two Scoops of Django
thanks
Good luck. Oh and I got bootcamp on sale. 15$
udemy provides sale twice a week :p
You can build out the view function (or Class) with an if statement to check for whether the request is POST or GET and render accordingly.
I already did that.
If POST.
CREATE user.
ELSE.
DISPLAY blank form.
Now, lets say user is successfully registered.
I use messages to pop a message up at the top of the page to show successful save/update actions for the user.
hey, which frontend technology did you use on your website?
Write a message into the context dictionary
Django
I can write message. That's a good idea.
But how to send CONTEXT with HttpResponseRedirect?
isnt django a backend technology?
For clarity...html/css for front end. Django builds the html page.
To render HTML page saying "Hey username, registered correctly".
Hmmm...you're redirecting to another page. A good question. I'd have to think on that.
Something like that.
I resolve by using render
But isn't using render with POST calls a bad practice?
If users refresh the page, the form gets resubmitted again right?
I've never heard that. And pentesting on my website hasn't yielded security issues
Really?
Really. At no point in any tutorial or even reading Two Scoops of Django have I seen render + POST being a bad practice. I can't see why it would be. But I've only been using Django for a few months
Okay. I'll try this once. Thank you for this!
It gets you context, which gets you messaging ๐
Messages can be sent via request right, or do I have to send it via context?
I send via context...
front end
{% if messages %}
<section>
<div>
<p class="alert-{{ message.tags }}">
{{ message }}
</p>
</div>
</section>
{% endif %}```
view ```py
message = form.instance.task_title
messages.add_message(
self.request,
messages.SUCCESS,
f'The Task "{message}" has been added'
)```
Bear in mind, I'm using bootstrap css to colour the p tag based on alert class
Okay! Thank you! ๐
def post_display(request, year, month, day, slug):
# Display all the details of the post
post = get_object_or_404(
Post,
slug=slug,
published__year=year,
published__month=month,
published__day=day,
status="published",
)
# A list of active commnets on a particular post
comments = post.comments.filter(active=True)
new_comment = None
if request.method == "POST":
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
new_comment = comment_form.save(commit=False)
new_comment.post = post
new_comment.save()
return render(request, "blog/post/display.html", context={
"post": post,
})
# return redirect(
# reverse(
# "blog:post_display",
# kwargs={
# "year": year,
# "month": month,
# "day": day,
# "slug": slug,
# },
# )
# )
else:
comment_form = CommentForm()
context = {
"post": post,
"comments": comments,
"new_comment": new_comment,
"comment_form": comment_form,
}
return render(request, "blog/post/display.html", context)
Hey @ionic raft this is one of my app. Can you just check if my POST render is okay?
Because if I do this, I'm able to post multiple same comments with refresh.
Please @ me, if you can tell me how to avoid this if I'm using render?
Please check this!
I'm having problem integrating Beaker for session management in flask. Can anyone share a snippet on how to integrate SessionMiddleware with flask?
edit: I was thinking you're using redirect. I think you can use redirect to add a parameter.
To use the person's name or username, the page view should be returning the user in the context so you get all your info to display from that.
Or maybe you can even grab it from the session cookie / request header if you want to get it that way.
(for po in pos:
browser.find_element_by_xpath('//*[text()[contains(.,{})]]'.format(po)).click())
sorry, i think i pasted it wrong.
GET must be idempotent, POST doesnโt; thatโs more or less it.
nothing to do with render
which just fills a template
Thanks for the clarity. The original question was based on an assumption that using render with POST was a bad practice. that didn't make sense to me.
yeah, which is why I mentioned it specifically
here
@uneven radish I'm using a similar comment approach but differently (screenshot helped). Specifically, I am using a class based view (CreateView) and calling the function form_valid to return the form itself. I'm not clear on how to prevent what you're experiencing with a functional view. However, that does inspire me to test what I do have to see if a refresh of the page will create the same problem.
def form_valid(self, form):
form.instance.article_id = self.kwargs['pk']
return super().form_valid(form)```
<!DOCTYPE html>
<style>
body {
background-image: url('bc.gif');
}
</style>
```Should this not render the gif as the background for the web page?
Hello, I'm new to Django. I learned the basics of the framework by watching YouTube videos. Now that I'm interested in learning more about Django, what would be the best place to start?
Django Docs
And self-practice.
https://docs.djangoproject.com/en/3.2/
Depends
Sorry, and that means?
Thanks @civic crater
Pretty awesome:
https://www.reddit.com/r/django/comments/ppxczs/django_40_will_include_a_builtin_redis_cache/
Gif will be stretched or repeated if u use it in this way
Wlcm
What's the issue @ashen crescent
it doesnt work as in transistion is ignored
transition: translate 2s ease-in-out;
-webkit-transition: translate 2s ease-in-out;````
so it translates just not as a transistion as shown
@civic crater
This image is showing a cracked discord logo.
^
look at this
POST is actually best practice for sensitive requests which change some database data. Because it is auto semi protected against CRSF attacks.
Tricks like
<img src="url/delete account at site X">
will be automatically more difficult and requiring for attacker to have attack hidden in javascript at least
Further protection with CSRF tokens or two auth is made to have better protection in this direction
what is the {% %} in html
this is jinja templating
@ionic raft
May be I'm overthinking this but Django Documentation Tutorial Part 4 says:
After incrementing the choice count, the code returns an HttpResponseRedirect rather than a normal HttpResponse. HttpResponseRedirect takes a single argument: the URL to which the user will be redirected (see the following point for how we construct the URL in this case).
As the Python comment above points out, you should always return an HttpResponseRedirect after successfully dealing with POST data. This tip isnโt specific to Django; itโs good Web development practice in general.
I can use redirect() because I think I read somewhere it is a wrapper around HttpResponseRedirect.
https://stackoverflow.com/questions/5823580/django-form-resubmitted-upon-refresh
Also according to the top answer, we should return HttpResponseRedirect after submitting a form.
can someone send me a tutorial on creating a Emailing service
dm me
like i am sending the over 100 mb of image in base64. but as response is containing bytes which freeze the browser itself
please tell me how to do it without freezing the browser
anyone got my question?```
welp im done with my site, where do i host
Heroku?
PythonAnywhere.
Heroku.
can anybody help me here. I am trying to install Flask according to the steps given in the documentation website of Flask
Remove $
before pip?
im not looking for the free services
Yes.
AWS..
but website says to write $
It doesn't.
$ is a notation used when any commands needs to be executed with sudo. In bash.
what does sudo mean
It's not related to Python Django Flask.
It's a program in UNIX with which we can elevate our privilege and run bash commands.
is it necessary to upgrade pip whenever a new version is available or I can manage with older version
can i create a website with react as front end and django and backend??
Never upgraded. If you encounter any errors. Maybe you should.
please help
Yes you can.
Check DRF.
no errors but only warning
what is drf?
You can skip upgrading then.
okay
Django Rest Framework.
got it
now i have created a folder so now I can open it in VS and start working as normal or not?
Build an API with Django RF and feed it to your Frontend.
is these any python framework for font end like react or angular ?
What exactly are you trying to do?
learning flask
So follow the tutorial. What does it say to do next?
directly it provides a code for a minimal app
I don't know anything about flask so can't really comment on that.
then i have to hit & trial
Or find a new tutorial? Just sayin'
good idea
I opened the flask folder I created before hand named flaskproject and installed flask within it. then I made a new file named project.py having following code inside flaskproject :
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello_world():
return "<p>Hello, World!</p>"
then I saved it and wrote the following commands
as you can see I have the following error
Import "flask" could not be resolved from source```
please help me here
you can see how I created my project file here
should i learn django or flask?
If I wanted to pass information from my react frontend app to my django backend, would I have to do a post request using something like axios, or could I use request.get(data=data) in a view in my backend?
For example if I had some articles on my site, and they were displayed from the db in django backend, and displayed on react frontend. And if I wanted to change the article on the site, I would have to pass the article id to my backend, so that it could be edited and saved in db. Therefore the article id, and the new text should be passed to django and the db, how could I do that
surely go for Django in 2021
I recommend to you to take CS50 Web this Course is Incredibly awesome ( especially Projects )
This course picks up where Harvard University's CS50 leaves off, diving more deeply into the design and implementation of web apps with Python, JavaScript, and SQL using frameworks like Django, React, and Bootstrap. Topics include database design, scalability, security, and user experience. Through hands-on projects, students learn to write and ...
thanks dude
i already know programming basics and i know programming languages like python javascript i dont think i need cs50
i wonder why people learn flask if everyone says that django is better
flask is kind of simple and ezz for api and more widely used for things like web automation making api's n all @native tide
hello guys, I'm new in django and I want to practice by some projects but I don't know where I should start, for example Is there any website that gives free project for practice?
see corey schafer's playlist btw u r lucky go to freecodecamp yt channel a django course 16 hrs , 2-3 days ago has been out
- django god CodingEnterpreneur
Mm thanks i will check
Hello guys, how would I go about automating fifa 22 transfer market trading?
aka just do stuff id spend hours on doing except get python to do it
I have not dealt with automation of websites before
How can I download a file from google drive in python like dropbox gives a access token and file Id, now how to get such access token for google drive .
I got to make a upload feature like upload from drive like google forms but can't figure it out.
Thanks
guys what should I learn for web development django or flask?
Hi, I need some guidance with django
I have a multiselect checkbox table in index.html tied to a submit button
Once i select rows and click on submit, it generates a query string like this
http://127.0.0.1:8000/?btSelectAll=on&id=0&id=1&id=2&id=3&id=4&id=5&id=6&id=7&id=8&id=9
I want that when the GET has id in query_dict, it should be redirected to another page and show the content of 'id' in that page
The redirection works fine as long as i dont attempt to pass the variables like this
def index(request):
x = request.GET.getlist('id')
if x:
context = {'data' : x}
return redirect('devicedetails')
else:
context = {}
return render(request, 'app/index.html', context)
def devicedetails(request):
return render(request, 'app/devicedetails.html')
However, the moment i want to do something like this, it doesn't
i dont know what is the correct way of achieving this
and i get error message like this
Reverse for 'devicedetails' with keyword arguments '{'context': {'data': ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']}}' not found. 1 pattern(s) tried: ['devicedetails$']
guys i receive a json file as a string, however it's show the code of the unicode
<class 'str'>
{
"Name": "turicas",
"Location": "Curitiba/PR - Brazil",
"Workfor": "Pythonic Caf\u00e9",
"Website": "http://dolaeor.py/",
"Twiter": "@oneoneo"
}
how can i treat this for every case of unicode that could appears to me
Anyone here who has integrated Metamask connect with a front-end?
Because you installed Flask in your virtual env. That "venv" thingy.
How can I get SSL going for an aiohttp server? I have an ssl cert from letsencrypt and have apache up and running, do I just need to plug and play?
@ me when responding please.
Hello, If I have a model which have a Foreign Key such as a user_id. When doing a Queryset to get all objects in the db in that table(model) but instead of only getting the user as an id, I want to include the user name in the response. Something like this:
#in Models
class Post(models.Model):
title = models.CharField(max_length=200)
creator = models.ForeignKey(User, on_delete=models.CASCADE) #This Will Get me the user id.
#In Views
Posts = Post.objects.all()
print(Posts)
#Printed Value of Posts:
#{
# 'id': 1 ,
# 'title': 'First',
# 'creator': 1 ,
# 'creator_name' : 'user' #What I Want to Include with the response
#}
#...etc
so what is the solution for this?
Guys anybody familiar with CKeditor
I'm Unable to uplaod images from templates usingit
anyone here ?
foreign key is always the id(primary key) of other table
so
post = Post.object.get(id=1)
post_create_id = post.creator
creator = User.object.get(id=post_create_id)
print(creator.name) //name can be access in this way.
Hi, Iโm building an app and here Iโve users, I read in few places itโs better to keep user profile information separate from the main user credentials table. Iโm using django and Postgres, is this followed practice?
u can customize the user model of django so that u can use inbuild django authentication and permission
Thank You!
how do i pass data from Django to a Vue spa inside a template
hey hello
needed some help urgently
i am trying to host a flask website suing sqlite database on pythonanywhere but it is showing errors taht tables dont exist while it was working perfectly fine on localhost
any suggestions
?
How did you create your database locally? You might have to repeat that process on pythonanywhere.
Hi, I want to create a search box, but it doesn't work.
This is my views.py:
โ`
from django.shortcuts import render
from .models import Products
def index(request):
product_objects = Products.objects.all()
item_name = request.GET.get('item_name')
if item_name != '' and item_name is not None:
product_objects = product_objects.filter(title__icontains=item_name)
return render(request, 'shop/index.html', {'product_objects':product_objects})โ`
This is my index.html:
โ<form class="card card-sm"> <div class="card-body row no-gutters align-items-center"> <div class="col"> <input type="search" name="item-name" placeholder="Search for products" class="form-control form-control-borderless"> </div> <div class="col-auto"> <button class="btn btn-success" type="submit">Search</button> </div> </div> </form>โ
For example I have a product called "Laptop", when I search Laptop nothing happens and it still shows me all products (just the URL changes to "http://127.0.0.1:8000/**?item-name=laptop**" )
any suggest?
The form is appending item-name as a URL arg, and your backend code is trying to get an arg named item_name. Notice the inconsistency?
ohhh thank u i'm stupid it was silly question ๐ .worked
Hi, anyone here successfully developer python web apps on Windows? With postgresql. I just want to know if you recommend buying a Mac instead?
Anyone use Next.js with a Django backend? I can't quite figure out how to use next.js api routes to send an incoming Stripe request to Django.
Hi Gurus!
I am getting data, but On Line response.json() is better?
how can i go forward? need this data dynamicly to front, it's Django.
If this will be on database i will do something like this
objects.all() and then for .
how can i do it on dicts?? on json?
Web apps on windows? you can buy any machine especially now that windows has WSL making it compatible with linux.
Macs are good since they come with apples M1 chip now and they are built strong, Asus is better because they have more advanced engineering in my opinion
hello can someone explain the difference between geodjango and django?
hello there, i really wanna create a custom user model in django, but using the django.auth it requires me to use the username field which i don't need in my project
done, just change username to None
well it was working.. but it doesn't work anymore...
okay i fixed it, just override it in the _create_user() method in the usermanager class
Well, think about the word, framework.
Imagine you want to build a house. Would you rather start on dirt, with just a pile of supplies? Or maybe at least the foundation, plumbing, wall studs and roof are on. You just gotta do the windows, doors, electricity.
That is what Flask and Django are. Frameworks for you to build your app on.
Ahh I see, well explained . Thank you, but I guess it's possible also to do web apps without these framworks am I right ?
Which I mean is full python
Yes, but you'll end up recreating a lot of what they do.
Flask is much lighter than Django for instance. Django is said to include everything and the kitchen sink as a joke.
I prefer Flask for most of my web work.
or FastAPI
Ahh I see, haha understood . May I ask what your web work is about ? I would like to understand more deeply . By that I mean what projects do you do as example ?
So basically Flask and Django are tools to help .
Oh yeah I also search up about these 2 framworks software and it is said that flask is lighter
framework*
Oh sure. Well, personally I build web apps for like dashboards or tools inside my homelab. I also have a blog that is statically output from the pelican static site generator (it's written in python but not me). I also wrote a short-lived website called warcache.com that was for one of my hobbies (wargaming).
Professsionally I use it to write and read APIs, glue systems together, do system admin work cause I hate writing bash scripts, have a few spiders running at any one time scraping data from websites. Hmm, oh, when we were testing out building apps for the Amazon Alexa devices, I did all that voice work in python. Originally in nodejs, but I found the python way better and rewrote it all.
I see, what's a homelab
Ah, sorry. I have professional grade networking switches, servers, a small kubernetes cluster built from raspberry pis, and such. Basically, I mess around with hardware, networking, and software as a hobby.
I see . Do you get paid for these hobbies if I may ask ?
No. Hobbies are for fun. ๐
Oh wow I see . Well that's interesting
I am an engineer though and do get paid for that. Or more now, my role is less making stuff and more overseeing growth, development, and careers of other engineers.
If I may ask, I would like to make educational websites, what would you recommend to me to start using to achieve my website ?
I'm currently learning HTML, CSS and JAVASCIRPT. Also Python .
Why is that ?
Great start. You don't need much more than that. One of the trickiest pieces you'll run into is setting up hosting but I'm sure you can figure it out. There are tutorials out there to help you.
Why is what?
That your role is less making stuff and continue on from that sentence
Can I make the website only using Python ? ( With Flask or Django of course )
Gotcha. I'm 20+ years in so I make less stuff for work because most of my time is as an engineering manager. I oversee teams. And currently my role is all about continuous learning, mentorship, and growing the company.
Wow I see, what tips do you have for a University student then ? Since I am one . I would like to know what you would love to see from a University student before going in the workforce life
Sort of. Remember though, all websites are in the browser are HTML, CSS, and JS. Python is on the server side. So you will write python but ultimately it is outputting HTML etc. You will still need to know HTML and CSS at least.
Ahh I see, than that's good ! I'm learning both at least so I can make the perfect website
I definitely have advice on that but my eyes are closing fast. I'm pretty tired. If I'm around tomorrow I'll try to answer. G'night. ๐
Ahh alright then thank you for your responses then . Good night !
what do you mean?
I mean does django load the pages faster
??
@wooden ruin
Guys can u suggest me a backend framework?
why would it? the loading time of a page depends on a variety of aspects that don't just depend on the backend framework. For python, flask or django are your main options
@wooden ruin is it possible to use async with django?
And what about falcon is it good
you can certainly use async with django, both through async views/middleware or even through websockets. and i've never head of falcon before
Ok
yeah why not!
share code and issue.
and what is issue?
you mean video is getting loaded tho?
also your src is right, right?
show me screenshot?
shows something in console?
also show me the directory view, I'd like to see, where exactly is your video. i think you're fucking up with the path.
I have installed flask on a virtual environment in a folder and I am coding in a file inside that folder but when I run it according to the way given by the documentation, it says that flask isn't installed. can you help me how to solve this
You need to activate the venv and don't put any of your python files inside the venv(they should be at the same level like siblings)
so i must create a new folder to write code instead of writing code inside Scripts subfolder of venv?
how is venv activated
can you give me an screenshot of a flask project to understand more clearly @jovial cloud
I'm not with my laptop rn but you can check out this link for a good project structure https://flask.palletsprojects.com/en/2.0.x/tutorial/layout/
You can either do that or put the file outside of venv in your base folder
how to activate venv?
On Windows, venv\Scripts\activate
While on Mac/Linux
source venv/bin/activate
I am getting same error which means the problem is that my venv isn't active
I should type it beforeset FLASK_APP=project?
and in ther terminal of VS code?
Yes, that is to activate the virtual env. Then you can pip install whatever you need (like flask and others) and also set environment variables (like FLASK_APP, FLASK_ENV)
Use command prompt, I don't know the command for powershell
How can I use flask's request.form.to_dict() in django?
is it just request.GET or request.POST
hi guys how I can create something like this using html and css?
a text box with 2 buttons, you must know html,css for the looks and JS is required to bring functionality
i get weird render differences in CSS between Linux and Windows. any ideas?
maybe different webbrowser / webbrowserversion?
Can some1 pls check #help-cupcake prblm related to flask api
AttributeError: module 'wsgi' has no attribute 'application'
I get this error while deployment can some1 help
that is expected.
?
you will see changes between OSs. you will see bit different in certain elements in MacOS too.
also define, weird, what exactly?
Layout of one of my divs doesnโt load correctly
Text appears much larger than my Linux system on Windows
oh just Text than right?
Yeah
have you given font-size?
Yes
also why don't you hover over the text to see how much does it take.
i mean in dev console view
How do I do that?
you know like this
yeah my assumption is that it may be because of changes of font.
Btw, Iโve heard a term called CSS reset. Can that help?
not sure, have not used personally yet.
Me too. Just wondering
but i mean to be very honest, some minor changes will be there when you switch OSs.
Yeah I see.
Also, margin of an <hr/> doesnโt change on windows too.
Windows sucks ๐ฆ
being a web dev you gotta see everything, especially the OS which gets used most.
I know
you can either complaint or just move on with divs lol.
Iโll just see what I can do with it. Itโs a problem when my pc is trash and canโt run VMs. If I could run VMs, I could test the site on Windows too.
For now, Iโll just ask my friend to run it on his machine for me.
Anyway, thanks for the help @native tide !
AttributeError: module 'wsgi' has no attribute 'application'
I get this error while deployment can some1 help
different available fonts in OSes
yeah, guess i got that.
as far as I remember from my CSS book...
you can set fonts in way like...
CSS book?
For thing one: use font1, font2, font3, and if nothing else use font_family_x
oh, yeah the fallbacks
lol
I like it
I read it only once
and never applied at practice
and still I remember it after many weeks/months
Head First books are cool
lmao, nice
i learnt my css from a youtube video. works fine imo
still needs some googling from the side tho.
their are some websites where form fields appear one at a time. Like first they say to fill Field A, then we click Next, and then Field B appears after reloading or something and so on. How can i create a such a system in flask ??
pls ping if u can suggest a approach
I think your frontend should be handling this, idk how this works in vanilla js but I did something like this in Blazor (frontend library for C#), basically you create a state with all the form fields and update the states data and pass it with the form's flow.
can u pls explain more about this?
Well I would need more info on your app? What it's using for the frontend?
well i use normal html and bootstrap for frontend
i guess thats not what u were hoping
Umm yep I will have to search for how it works in vanilla js and get back to you.
thanks for the doing
Idk if I'm allowed to share links here, you can search for multi step forms using javascript
okk
also i think i gotta learn about js front end with python back end (if its possible)
should i learn django after a few months of learning? i heard its pretty hard
learn flask
hey so I'm doing some basic contact form stuff with django's send_mail(subject, message, from_email, recipient_list)
I set it up and it works, but I can't figure out what's it supposed to do with the from_email parameter. Is it supposed to appear somewhere in the body/subject of the sent email?
I ended up just jamming message_email into the message parameter like this
path = request.path[:-1]
context = {'path':path}
if request.method == "POST":
message_name = request.POST['message-name']
message_email = request.POST['message-email']
message_text = request.POST['message-text']
context['message_name'] = message_name
send_mail(
f'prtfl - Message from {message_name}', #subject
f'{message_text}\n\nFrom: {message_email}', #message
message_email, #from_email (this thing here)
[str(os.getenv('email'))] #recipient_list
)
return render(request, 'main/contact.html', context)
else:
return render(request, 'main/contact.html', context)```
But is this the correct way to go about it?
2021-09-23T12:24:42.734186+00:00 app[web.1]: [2021-09-23 12:24:42 +0000] [17] [INFO] Starting gunicorn 20.1.0
2021-09-23T12:24:42.734469+00:00 app[web.1]: [2021-09-23 12:24:42 +0000] [17] [ERROR] Connection in use: ('0.0.0.0', 23194)
2021-09-23T12:24:42.734516+00:00 app[web.1]: [2021-09-23 12:24:42 +0000] [17] [ERROR] Retrying in 1 second.
2021-09-23T12:24:43.062713+00:00 app[web.1]: [2021-09-23 12:24:43 +0000] [7] [INFO] Worker exiting (pid: 7)
2021-09-23T12:24:43.662675+00:00 app[web.1]: [2021-09-23 12:24:43 +0000] [4] [INFO] Shutting down: Master
2021-09-23T12:24:43.662722+00:00 app[web.1]: [2021-09-23 12:24:43 +0000] [4] [INFO] Reason: Worker failed to boot.
2021-09-23T12:24:43.802630+00:00 heroku[web.1]: Process exited with status 3
2021-09-23T12:24:43.897718+00:00 heroku[web.1]: State changed from up to crashed
Hey i am getting this error while trying to deploy on heroku with gunicorn I am not sure what does it mean could someone help
@fallow meteor do i have to learn like css or html first or can i just dive in?
seems about right, just maybe save that same info in a database so if the email fails u have a backup
share your code?
thanks for the concern i figured it out ๐
:)
i ran the app twice ๐คฆ
i see, thanks!
also good idea
maybe a dumb question but do i need to let the user know i will be dumping their info into a db?
if your database is going to be without password and other protections, then yes
that's a legal question
depends on your jurisdiction
and what info it is
the user's email and whatever they put their "name" as, along with the message, but I'm already shying away from this idea
Is there any way to do dependency injection with HTTPEndpoint in Starlette without reinventing the wheel?
The easiest solution I can think of is a function that returns a class, but that's cursed and adds an indentation level
If I have an event hit an endpoint directly on my Django backend (Next/React frontend), how do I send a response to the front end to go to a certain page when it's finished, since in this case Django isn't controlling navigation on the frontend?
u need some basic knowledge about them, atleast about html
cuz u will be using bootstrap for the most part for styling, so u need some knowledge
but its easy, i guess it would take 30 mins to gather the knowledge of most of the html tags and all
iam following a tutorial just now, for django, i typed in everything the same and somehow an error occurs
is it wrong ??
@app.route("/")
async def home():
return await render_template("main.html")
@app.route('/handle_data', methods=['POST', 'GET'])
async def handle_data():
projectpath = await request.form['projectFilepath']
print(projectpath)
return projectpath
<!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>Document</title>
</head>
<body>
<form action="{{ url_for("handle_data")}}" method="post">
<label for="firstname">First Name:</label>
<input type="text" id="firstname" name="fname" placeholder="firstname">
<label for="lastname">Last Name:</label>
<input type="text" id="lastname" name="lname" placeholder="lastname">
<button type="submit">Login</button>
</body>
</html>
its not working when i am trying to get the post
"{{ url_for("handle_data")}}" use single quotes 'handle_data'
post error if there is some..
yes there is a error
@snow sierra
"{{ url_for("handle_data")}}" use single quotes 'handle_data'
tried that but still this error
from quart import Quart, jsonify, redirect, render_template, url_for, request
app = Quart(__name__)
@app.route("/")
async def home():
return await render_template("main.html")
@app.route('/handle_data', methods=['POST', 'GET'])
async def handle_data():
projectpath = await request.form['fname']
p2 = await request.form['lname']
print(projectpath)
return {projectpath: p2}
if __name__ == "__main__":
app.run(debug=True)
@snow sierra
<!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>Document</title>
</head>
<body>
<form action="{{ url_for('handle_data')}}" method="post">
<label for="firstname">First Name:</label>
<input type="text" id="firstname" name="fname" placeholder="firstname">
<label for="lastname">Last Name:</label>
<input type="text" id="lastname" name="lname" placeholder="lastname">
<button type="submit">Login</button>
</form>
</body>
</html>
"{{ url_for('handle_data') }}" method="POST"
i don;t know, just lets start by this changes :d
yes because there is some answer, https://stackoverflow.com/questions/57240608/typeerror-coroutine-object-is-not-callable
did you tried it?
and exactly your error https://stackoverflow.com/questions/51459793/python-typeerror-coroutine-object-is-not-subscriptable
@snow sierra can u show me a example of how to make a post request?
django is better right?
if yes so can u tell me how can i get started?
someone tell me how can i get started with django
???
either look up the docs or youtube search django tutorial
I can tell you how to get started with fastapi
the official django documentation has a really good tutorial that explains how django works and shows idiomatic django code, it's a really good resource to get started with django: https://docs.djangoproject.com/en/3.2/intro/tutorial01/
i am reading this rn
shell: ```sh
pip install fastapi
app.py: ```py
from fastapi import App
app = App()
@app.route('/')
def home():
return "Hello, world!"
main.py: ```py
import uvicorn
if name == 'main':
uvicorn.run('app')
Ok, I go now
fastapi and django are really for two different kinds of projects imo, django is absolutely brilliant for user-facing sites and fastapi is absolutely brilliant for well, APIs
fastapi pairs well with frontend frameworks, like react or vue
honestly django is just amazing
@meager anchor isint is possible to create chat room with django
ok so fast api is good for apis right?
yes, although you probably want to add a layer like https://channels.readthedocs.io for that
yes
i use it at work for a few things and it handles very very good volume
fastapi supports websockets fyi
if anyone is good with beautifulsoup and don't mind helping out #help-cupcake
can anyone suggest me some good tutorial on websocket?
Thank you, sorry for the late reply. I installed wsl2 and it works fine for me atm
Great! i'd highly suggest installing windows terminal from microsoft store
What to choose for creating an api + websockets. FastApi or django + DRF ??
I like the documentation of fastApi but I dont know if its going to be alive for very long
FastApi looks good but I dont know if I will be able to find any help with any edge cases that will occur in the project as it gets bigger
FastAPI is wonderful for API creation, I've used it multiple times
FastAPI is very popular and catching up to others. It is actively under development.
what are its weaknesses to django drf?
Not familiar enough with DRF. I never reach for Django as to me it's just TOO big.
Honestly, if it's just an API, I'd always go with FastAPI, it's much simpler
I'd only use DRF if it heavily ties into another Django project
hm ok that sounds good
I really like it I just want to be sure that I will not have any problems in the future
I want my api to communicate with a machine that sends and receices geolocation data with websockets
also to have user auth and roles
FastAPI is very actively maintained, it's pretty popular. I doubt you have to worry about it losing that.
You can definitely do that with FastAPI
ok nice
The FastAPI database guide could help you with that https://fastapi.tiangolo.com/tutorial/sql-databases/
FastAPI framework, high performance, easy to learn, fast to code, ready for production
thnx
I am also thinking of using this https://hub.docker.com/r/tiangolo/uvicorn-gunicorn docker image
my plan is to make a small stack that I can scale to multiple machines if needed
like use a load balancer in front and multiple API containers (fastApi) in the back
with 2 postgres databases one as main and one as the replica
@uneven radish another post mentioned the following:
POST is actually best practice for sensitive requests which change some database data. Because it is auto semi protected against CRSF attacks. Tricks like
<img src="url/delete account at site X">
will be automatically more difficult and requiring for attacker to have attack hidden in javascript at least
All I can say is that the documentation you cited is a bit general. Updating a DB is another layer complexity, and I'm curious about that recommendation when placed against what the CRSF token is supposed to protect against. While I get why you're posting what you've posted, the CRSF token is supposed to protect against the potential gap being listed. And in between various tutorials and the book, Two Scoops of Django, I've just not see anything that highlights POST (assuming a CRSF token is used - which has to be explicitly turned off to not use) and render as being a problem.
On the plus side, this is all good research. Deep research and finding out best ways to get the job done can only be a good thing. Good luck. ๐
Side note: And it's this sort of debate/conversation that is exactly why this Discord is amazing ๐
the correct way to protect against that is to implement CORS correctly
but it could still be an issue with images and such if you allow embedding your own images
...which is not a good idea because you can make IP grabbers that way.
Thank you for taking out time and replying.
I'm still not convinced how can I use render to return after I have successfully added a new comment under my blog (my application) or dealing with my POST call. I tested and tweaked my code but still couldn't remove that resubmission form error when using render().
However, if I use redirect and I don't have to deal with that problem.
I am just a beginner at this point following a book. Maybe in later chapters, they will introduce and differentiate or make things more clear. I'd still use redirect at this moment because of obvious reason.
If you test your code further, do let me know the findings and also post your code snippets.
And I completely agree about this being a good research. We will be learning something new and remove bugs one at a time.
Cheers! ๐ป
So many safety mechanisms already there, all we need just to turn them on
CSP technically protects too for same purposes
It will ensure that only your javascripts will run
It is more against XSS though
You've been following this conversation @inland oak ?
Just few last posts
The issue was when successfully dealing with POST call when I use redirect to return and refresh my form page my form isn't submitted again. But when returned with render, I can submit my form N times just by refreshing.
More precise phrasing would be:
Use POST to change state of smth
Use GET for things that change nothing :b
Well, and we can also
Use PUT to update or replace
Use DELETE to delete ;b
That is bothersome
def post_display(request, year, month, day, slug):
# Display all the details of the post
post = get_object_or_404(
Post,
slug=slug,
published__year=year,
published__month=month,
published__day=day,
status="published",
)
# A list of active commnets on a particular post
comments = post.comments.filter(active=True)
new_comment = None
if request.method == "POST":
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
new_comment = comment_form.save(commit=False)
new_comment.post = post
new_comment.save()
return render(request, "blog/post/display.html", context={
"post": post,
})
# return redirect(
# reverse(
# "blog:post_display",
# kwargs={
# "year": year,
# "month": month,
# "day": day,
# "slug": slug,
# },
# )
# )
else:
comment_form = CommentForm()
context = {
"post": post,
"comments": comments,
"new_comment": new_comment,
"comment_form": comment_form,
}
return render(request, "blog/post/display.html", context)โ
Not sure what to do with it.
I deal only with back and devops.
Front is still a mystery land for me
I can advice to try generating unique hash in your msg data
And validating that new recorded msg is not having the hash perhaps
It sounds as not perfect solution though ๐ค
Yeah!
Sounds like a workaround.
Also, the redirect commented works perfectly and do not add same comment again if user refreshes their webpage.
I am afraid that you will have hash collisions in this case
Perhaps to use hash with time expiration in it
If hash was generated longer than N time ago. To ignore it
The time can be inbuilt into the hash and encoded
Extracted on decoding back
Umm... Still an overkill solution.
Validating that new msg is not equal to previous one?
Why validate explicitly when Django can do that for me? And prevent resubmission.
If I use redirect, of course.
It can? ๐ค
Well, not exactly "validate" but prevent form resubmission upon refresh.
Oh, u mean... just wipe the field data after submission
Yup yup.
That actually sounds like easier solution
Just redirect is not sure if best option to deal with it
Perhaps a bit of javascript
To clean stuff after you
Yes. It can help. Currently I'm trying to explore vanilla Django options to achieve this.
I would try Svelte to do front part
It has jinja like language too that we got used in python
It should make smooth transition
Thanks. Will look into it. First time hearing it tho.
is it necessary to set up purge rules in order to use django-tailwind?
How to Django app as a client on laptop that is offline and push the data to your server when you get back online. plzz help
look up flexbox
ive already installed the flask-login module
this is my first day working with flask, any help would be much appreciated
can you share code where you're importing login_manager and defining it? they might be in 2 different files too
sure, gimme a sec
oh god im sorry for wasting your time
there was a spelling mistake
in the import statement
lmaoo im sryyyy
๐
(NOTE: USING REST FRAMEWORK)
Hello, so I have a model that has a Title, Description, User(Foreign).
Getting all with the queryset model.objects.all() returns me many objects, for the serializer we can easily put serializer(model.objects.all(), many=True) but how do I access some attributes for every object I also want to add some data with the response for every object.
Ive did that with only one object of the model:
GetObject = model.objects.get(id=id)
serializer = ModelSerializer(GetObject, many=False)
data = { }
data['response'] = 'Success!'
data['user'] = GetObject.user.username
data['title'] = serializer.data['title']
data['description'] = serializer.data['description']
#etc....
return Response(data)
Ive also tried another way for multiple objects but I dont think its a good way to do it + I didnt know how to return that as a Response
data = {
}
for objects in GetObject:
objects_id = GetObject.get(id=objects.id).id
objects_title = GetObject.get(id=objects.id).title
objects_description = GetObject.get(id=objects.id).description
data['id'] = objects_id
data['title'] = objects_title
data['description'] = objects_description
print(data)
def notes_delete(request,note_id):
if request.method =='DELETE':
qset3=Notes.objects.filter(id=note_id).delete()
messages.success(request,'DELETED')
return HttpResponseRedirect(reverse('home:index'))
return HttpResponseRedirect(reverse('home:index'))```
so what it is doing is it's directly rendering home page
not deleting
ohk done
Hello,
Please is there any way in flask (with celery, redis or any other tool) to stock the user requests in a queue and proceed in each time only max 5 requests in parallels and then proceed the others and so one (like amazon sqs principle) to avoid sever over process capacity issues
@lapis basalt I'd imagine you could do something like that with nginx
Override the .to_representation() method of your serializer (read the docs on this) - it allows you to modify the data in serializer.data
@rotund perch
Can u do an example if possible?
The docs probably do
Okay thank you!
@opaque rivet Thanks! I will see
Also I have a question, does each gunicorn worker spawn a django process?
Or do all the workers talk to a single django process
Hi, I have a http client (phone app) that does not tell me what it is doing. Does anyone know how I can set up some test server to see what its requests look like? headers and data? (Thinking about e.g. httpbin.org but this does not show the request easily on the server side)
wouldn't it get confused when it didn't get proper responses
Hi, so my friends and i are thinking of working on a django project together and currently the whole project is on my pc. My question is can i share the whole project using GIT and if I succeed, do they just have to download the project and runserver to make it work (assuming they have the requirements.txt files)?
I was confused because there are commands such as manage.py startapp etc, and was wondering how to go about this. Thanks for helping a noob
@vestal hound yes I just want to analyze the request details at first. Later I will write the server - the client is fixed, I just need to understand it so I can write the server side
At work we're using github to work on the same codebase. Doesn't matter which language or whatever. Would recommend getting to know the git/github workflow, it's fairly universal outside python, too. (And many more people should use it, I think)
Cool
So it's not like startapp etc is mandatory right? Let me be clear.. so they can just download the project and run it on their pc?
git is for collaborating on code with other developers - not for packagiung and distributing code as a runnable entity (although github, which uses git for many of its features, do have some packaging and distribution features)
use like FastAPI or Flask?
with one wildcard route
then just inspect the request objec
not a bad idea! I've begun working a bit on this approach since I did not find anythning ready made
this should be doable in like 15 min
so I have 10 min left to do it...
so they can just python manage.py runserver No?
then they make an app, upload it on github and I download it. does it work like that?
@vestal hound docker run httpbin is like 5 sec though!
That is one way to do it, if you prefer
What's the other??
There are many ways to work together. Keep people's competency and interests in mind, and if they're motivated you should be fine
@normal token there are 9 million. zipping code to sharepoint, deploying code to aws, docker-containers can deploy the app, ...
from fastapi import FastAPI
app = FastAPI()
@app.get("/{route:path}")
async def all_get(request: Request, route: str):
print(route)
print(request.headers)
return None
repeat for POST, I guess
and the others if you need them
@normal token maybe if you explain who the people are and what their tasks are, you'll get more concrete answers
@vestal hound brilliant, didn't think about the path trick there!
๐
Oh ok
Its just my friends and I are thinking of making an e-commerce website and I have already made a few apps.. but i don't know how can I share the code with them except Github, even then I was confused with problems such as maybe they have to startapp etc
will they also be writing code?
Your answers made it clear, tho I'm worried I may have to get Github pro for that
no, there's no need for any subscription
but
it sounds like you're not familiar with devops
so this would be a good time to start
ok, you might need github pro if your team uis larger than X, etc
there is this school of thought that "your app should be deployable with one command"
agree, someone needs to handle the opsy stuff, deploying to a website etc
Oh ok.. so how do I share the code with them first of all?
So I need to grab someone in my class who's interested in devops now.. haha
or is devops something that is manageable to do alone?
for working on code together, use git. Then put the git repo somewhere safe - github is one good option
@normal token someone needs to do it. Yes possible but it is some work if you want to automate everyting well
it's not super hard
and it's a good time to start
you can look at very basic things
like running your tests automatically
Cool I will look into it ๐
Devops- like aws etc?
not reaaaaally
AWS is one place you can deploy your project, yes
but devops, in general
is about turning your code into a working product
so integration, deployment, support, etc.
Oh ok! That's a good explanation, thanks!
np! it's not simple but it's always good to learn
you can check out #tools-and-devops too
๐ ๐
so im working on making a website to run off replit for now, mainly for testing, and running into an issue, here is my code ```py
#imports
def create_app():
@app.route("/")
async def home(self):
#doing stuff here
return app()
def setup():
create_app()``` so the issue im having is that i dont know where to tell it what host and port to run on
(lmk if this isnt the best place for this)
Hello i wanna ask a question can i make like a bot and integrate it with Django so when I add a post on my blog site it automatically add the same post and image on facebook and instagram , is that possible ?
Yes is it possible.
However, Iโd suggest you look at the Facebook API as opposed to making a bot.
I have a question, letโs say I am making a Django application to track user availability. What is the best way to store the available times on a given day for a user?
I can think of two options but not sure which is best or if there is another alternative.
- Create an Availability model and an AvailabilityDay model that have a one to many relationship. I can then set the day of the week for the AvailabilityDay and a string of times(11AM,12AM,etc.) for the available times that day. Then I make some setter and getters for those times to use datetime objects.
- Have the same two models as above but add an extra model like AvailbilityTime that will simply store those available times as datetime objects with a one to many relationship.
Thoughts?
anytip for django modal?
I actually handled this problem before
soโฆ
is that like regular availability?
i.e. it repeats every x period
or more like a calendar
so every day is unique
Regular availability yes. Say a user is available 11AM 1PM and 2PM on Sunday
and that will be true for all Sundays?
what are your predicted query patterns
like what kind of queries do you foresee yourself executing
See who would be available at any given day/time
And of course see all available dates/times for a given user
MySQL most likely. Maybe Postgres
Kinda torn between the two right now.
but these are concrete datetimes
whereas what you want to deal with is more abstract
i.e. โany given Sunday at 1 PMโ vs โthis particular Sundayโ
so
there are a few ways to do it
- use this and model all your dates from the epoch week
- come up with a custom encoding of your data
one thing I did before was
encode each period
as a bit
(30 min IIRC)
then matching availability = bitwise AND
in hindsight maybe that was a bit overengineered
this would be the other option I can think of
not modelling as concrete datetimes
but more likeโฆa table with id, day, hour, minute columns?
can anyone suggest something to make as a project using django and DRF?
then you have to perform the datetime logic manually
todo list is standard
done that already:)
card game
That was the idea with simply storing times as a string and encoding it/decoding it when needed.
you could
I personally donโt like it but there isnโt really a standard solution for this I believe
and itโs not horrible but
well
you canโt filter on database level
at least, not easily
if I understand you correctly
and this is Bad
anything other than a game?
dude I gave you two suggestions
how about a shop then
or a blog
I have my own question via flask. letโs say i have 2 users, user 1 and user 2. User 1 has info stored in a database and user 2 reads that info and removes it. Is there a way i can have user 2 tell user 1 info related to it. (like have them connect)
what?
or just interact in general
Yeah, thatโs the bad thing. The main problem I guess is I donโt just need a range I need individual times. Since it can be 11AM-1PM and 6PM-8PM for one given day.
I mean
those are discrete ranges, right
shop is a nice one ๐
actually
you know what
in the abstract sense
you can think of the problem this way
each user is associated with a set of tuples
where each tuple contains the start and end index of a datetime range
e.g. (28, 32) would be 2 AM to 4 AM on Tuesday
assuming your week starts on Monday
then two availabilities match for which the intersection of the inner intervals is nonempty
Well the day of the week thing Can simply be an int field in the day model so not worried about that.
this feels like the best idea though
at the moment
Ok cool, this might be what I do.
so you have 168 rows per user
assuming 1 row per hour
and 24 hours per day
not too bad I guess
Yeah, which is what I had thought of doing.
Because instead of doing it like that I could simply make a model that just stores a time and have it relate to a model that stores the day.
Well, this is only a small part of the entire application.
do you need to see intersections between users
Not necessarily, the data would really be used to schedule them to tasks that run at some given times/ranges of time.
And to optimize who goes to what task based on availability and some other factors.
this could be just User.objects.filter(availability__id=40, availability__status=True)
I think? havenโt done Django in a year ๐ฅด
Well. Iโd probably look for users where their available days and times are within a specified range. Not sure what that availability__status represents.
But I think making models for the times and days makes it much simpler to create the queries for it.
I appreciate the feedback. Might pick your brain for some other insight as I finish organizing my project.
yup
it becomes a question of efficiency
you could look into the bit type
feel like that would be best
atb!
Yeah, which is why I was scared of the amount of rows per user.
However, this might be premature optimization.
Doing it with bits I mean.
my concern is more the accuracy of the data model
bits are harder to work with in Django
but it just seems like a nicer representation to me
shrugs
What would lead to inaccuracies?
You are probably right, a bit outside my comfort zone right now. Probably should focus on getting this thing designed built and deployed first.
Another option is to have 24 Boolean flags in the AvailabilityDay model but that sounds like a nightmare lol
not really accuracy in that sense
more like
how appropriate the data model is?
ease of use
Yes, seems to be just a big table for no reason when you think about it I guess.
Since most of the rows would be similar since they only store one hour.
I like bits because itโs just one column per user
and no joins required
and you can do everything in the DB
hello there. do you have an experience with gzip on the heroku?
Yeah, Iโm thinking of something similar. But storing tuplesnof time objects.
For example letโs say you have a AvailabilityTimeRange model with two fields upper and lower. You would store a range the user selects (upper=11AM, lower=11AM) or (upper=11AM, lower=6PM).
So then you would basically save multiple ranges if the person decides to have an hour gap or more and if there is no gap it just extends the range.
This would make the query a slightly more complex than storing the individual times but would decrease the amount of rows per user significantly.
but how do you query efficiently?
Trying to work that out now as we speak of it. Because the way Iโd want to query it is give me a user that is available between this time range.
I don't think you can do it @ DB level without range support
and even then
not sure if Django would support that
think you'd need raw SQL
One way I can think of doing it which is not a great approach is to build a tuple or list for the required range so letโs say (11AM, 12PM, 1PM) for 11AM-1PM. Then do the same for all the ranges in the availabilities and see if the required tuple is in the other.
that would be in Python
Yes
it's not hard in Python
I mean, this is being built in Django after all.
but
Donโt have to do it at the database level right?
filtering in Python will not scale
don't HAVE to but
Ok
for any appreciable number of users it's unlikely to work
because you'd need to pull all that data over the wire
Scalability is key, which was the big concern with the 168 rows per user
168 is not a lot
that would be like...at most a KB per user? with 1 million users that's only 1 GB
in general I would say compute is harder to save on than memory
so
go for whatever lets you optimise on the DB side
but YMMV
Well, not just thinking of the space taken I meant the amount of time to query such a large table.
YMMV?
Because at 1M users you could have 168M records.
your mileage may vary
it should be indexed
so constant-ish time
remember that if you filter in Python
you'll need to pull every single record in the table
in general, you don't want anything you do frequently to be linear time and above
Yeah, makes sense. Iโll go with that approach for now and optimize later as needed.
hi,i need help in html actually i linked a webpage to submit button but when i try it it says HTML1423: Malformed start tag. Attributes should be separated by whitespace.
@west cove show your tag
anyone knows how do i get gradient text using CSS?
is it possible for 2 seperate sessions to interact with each other?
my only thought to make this possible is for every session to have a interaction endpoint so like '/user/interact/username' or something like that
am i wishfully thinking? or is something like that actually possible
and or is there any other way to have this work
Just trainning for my interview
Can you expand on what you mean by sessions, and what you're trying to achieve?
by session im refering to the user by browser. Like if im on my pc at www.google.com thats a 'session'
i have 1 session running at google.com
"session" has a specific technical meaning
do you mean that?
or do you want, in general, two users online at the same time to have the ability to interact
ye
exactly
then you should not say "session"
anyways
it depends on your needs
if realtime, like chat or a game
I would suggest websockets
but even vanilla HTTP requests will work
so would something like this not work?
it would
so via that could i establish a 'websocket' or is a websocket a whole diffrent thing
you could
websockets basically let you maintain a connection to a server
and transmit data bidirectionally
on the other hand, requests open new connections each time they are made
and only allow initiation by the client
could you point me to some sort of module that does sockets for flask or some tutorial?
just something to help me get started in this
donโt have one, sorry
Google could be a good friend of yours here.
Here's one for example, using Flask
https://flask-socketio.readthedocs.io/en/latest/
ight thanks
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="basic">
<div class="box">
</div>
</div>
</body>
</html>
{% extends "base.html" %} {% block title %}Register{% endblock %} {% block
content %}
<form method="POST">
<h3 align="center">Register</h3>
<div class="form-group">
<label for="email">Email Address</label>
<input
type="email"
class="form-control"
id="email"
name="email"
placeholder="Enter email"
/>
</div>
<div class="form-group">
<label for="firstName">First Name</label>
<input
type="text"
class="form-control"
id="firstName"
name="firstName"
placeholder="Enter first name"
/>
</div>
<div class="form-group">
<label for="password1">Password</label>
<input
type="password"
class="form-control"
id="password1"
name="password1"
placeholder="Enter password"
/>
</div>
<div class="form-group">
<label for="password2">Password (Confirm)</label>
<input
type="password"
class="form-control"
id="password2"
name="password2"
placeholder="Confirm password"
/>
</div>
<br />
<button type="submit" class="btn btn-primary">Submit</button>
</form>
{% endblock %}
*{
margin: 0;
padding: 0;
}
.basic{
height: 100%;
width: 100%;
background-image: linear-gradient(rgb(154,204,255), rgb(56,182,255)), url(images/md.jpg);
background-position: center;
background-size: cover;
position: absolute;
}
everything works, but the css modifications dont show up :(
you sure the html and css file are in the same folder?
does query.get and filter do the same thing in sql
Is this one html file or two different html files?
I can see that some semicolons are missing in the JS code
If you're extending base.html there shouldn't be any html tags before it or even anywhere at all. Extending copies the html from base.html and pastes it in your new html file with Jinja.
Also, can I see your base.html file
@native tide the click event listener has an undefined variable, clicks
!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 your custom css in the base.html file and check it out
@native tide I know, look in your "click" event listener. Where is the clicks variable?
@native tide aah I see, I didn't see it. So, what is the issue?
anyone with experience with discord bot dashboard?
{% extends "base.html" %} {% block title %}Register{% endblock %} {% block
content %}
<form method="POST">
<h3 align="center">Register</h3>
<div class="form-group">
<label for="email">Email Address</label>
<input
type="email"
class="form-control"
id="email"
name="email"
placeholder="Enter email"
/>
</div>
<div class="form-group">
<label for="firstName">First Name</label>
<input
type="text"
class="form-control"
id="firstName"
name="firstName"
placeholder="Enter first name"
/>
</div>
<div class="form-group">
<label for="password1">Password</label>
<input
type="password"
class="form-control"
id="password1"
name="password1"
placeholder="Enter password"
/>
</div>
<div class="form-group">
<label for="password2">Password (Confirm)</label>
<input
type="password"
class="form-control"
id="password2"
name="password2"
placeholder="Confirm password"
/>
</div>
<br />
<button type="submit" class="btn btn-primary">Submit</button>
</form>
{% endblock %}
This is how your 2nd html should look. And put your class(for styling) either in your base.html or the 2nd html file
my 2nd html file does look liek that
i also added the class in base.html
it didnt wor
work*
how to use "has_module_perms" in django to provide custom permissions to AbstractBaseUser?
How to do the text will change color after one second
how would i know if a user's session is over so that i can clean up the user's temporary files on the server? (Flask)
How to do button will look like this?
use transition ๐
anyone?
thx
๐
what are you working on?
dashboard
using tailwind and django?
Unless you're a security professional, hell no. Don't even touch making a VPN.
and performance levels?
No idea. But I would think it's pretty hard to make in Python