#web-development
2 messages · Page 232 of 1
In that case I would focus on getting a degree after high school, but you're in good shape... I definitely didn't know how to do that at 16
yeah but its still pretty not good
i barely know how to put these stuff
its really unorganised
looks fine to me, but it's all about practice, just keep at it and you'll keep getting more comfortable doing more challenging things
yeah, thanks
im rlly paranoid about my future haha
since i dont really see anything i do as good, i feel like the only good project ive done is my pico8 player thats virutally useless
as you have to go to the original website to get the games haha
...and it didnt even use flask
As a fellow neko lover I'd like to see this website grows
yeah im playing with names rn
i didnt know how to make the app start from /catboys so i did it like that
lol
If you want to redirect users from / to /catboys when they visit / then create another view function that redirects the user to /catboys, see this answer:
https://stackoverflow.com/a/14343978/14169295
Ohh just I noticed you did something similar to handling HTTP 404 status code lol, btw 404 stands for "Not found", I guess you should rename that function to "not_found"
yeah ik
but i couldnt make it so / redirects to catboys
so i made it when it cant find anything it just sends you there
oooh tysm!
np!
ive been working so hard on this website and its finally looking up owo
your problem solved?
bro, if you need any help in Flask, you can message me personally. I'll try to help.
So this site I'm working on will have groups, I want to have an option to create groups based off your school. Any ideas on how to do this while keeping some form of security in the sense of stopping anyone from joining any schools group?
I'm considering doing it off of school email but some schools limit emails from being sent/received from outside, untrusted domains. I'm thinking of possibly doing it through oauth but want more opinions first.
yknow ive been working on this site for so damn long
but
i dont think i can add this to my resume-
All depends on where you wanna work 🤣
Hey guys I have a quetion about web scraping. Id like to get all the facebook posts my friend makes, but dont have a facebook account. Can I still do it?
You can be their follower and see their posts
Is async sqlalchemy worth it in fastapi?
Or should you do everything sync?
can someone help me
where do i fit python flask
in html css js
is python flask replaceing any of it
or is it a addition to any of it
i dont see the point of it really?
or is it to avoid JS
and under hood it deos translate to it still?
Hi, how do I pass JS data to Flask?
How do I set Flask Environment to Development? set FLASK_ENV=development ain't working
Also try FLASK_DEBUG=1
How can I write a program to make it interact with webpages on chrome, like I want it to react with the Discord reactions, every 10 min.
I want the script to be able to run even if chrome is minimised.
I don't have much experience in coding, but please tell me the libraries and other things I will require
Please tag me while answering
Thank you
no, python is a backend, html is the structure, css is the style, javascript is the interactivity and dynamics, python is the algorithms and databases
Hi
using a fetch
in javascript to call to the flask api
People often like Axios library
I would say yes, it's not that different, all you have to do is use AsyncSession class instead of standard Session
mhmm do someone know how to post into a django website?
im troubling with csrf tokens
need some help with flask
I'n my first route i'm sending a request to the second route
is there a way to share the client with them?
@app.route("/course/<int:course_id>")
async def course_route(course_id: int):
async with httpx.AsyncClient(headers=headers) as client:
responses: list[httpx.Response] = await asyncio.gather(
client.get(course_url),
client.get(f"{course_url}/public-curriculum-items"),
client.get(f"/api/get-course-reviews/{course_id}")
)
return render_template("course.html", course=data)
@app.route("/api/get-course-reviews/<int:course_id>")
async def get_course_reviews_api_route(course_id: int):
"""
Api route for getting course reviews also takes JSON 2 parameters page and page_size
"""
return jsonify(data)
how can I add a date field in django user authentication for storing user's date of birth?
You can create a custom user model that inherits from AbstarctUser or AbstractBaseUser (Depending on if you want to change the authentication process or not) and add a DateField if you're just starting a project. Or you can extend the User model using one-to-one relation with another model.
See this article:
https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html
What are you using to send POST requests? Django forms or AJAX?
is that @spare ridge.route stuff what is used on apis?
im just beginner is it still part of django?
oh i see it thanks
Why not? You can add stuff to it and make it a big project. Add user registration and authentication stuff, let users bookmark images, let the app send an email to users about popular entries every week, and many many other things you can do.
What you can do in this project you can definitely to it in another one.
@native tide Even if the topic isn't very serious, that project still shows your skills pretty well. As others have said, you can always expand it or transfer a lot of what you've learned to a different project. I'm working with Flask as well and never had any 'serious' projects, but I learned a lot from experimenting and ended up transferring much of that code to a 'proper' project - in my case that was an project/issue tracker.
hello guys
i need some help in css
is there anyone here???
so this is a <div> element, in which I am trying to add the "<_" text. But it seems no matter how I try to align it, it doesn't. So can someone pls tell how to center the text, vertically and horizontally in the box
it is horizontally centred, by doing text-align: center;, but how to do it horizontally??
what’s the code of the child and parent
for css
.logo {
border-radius: 25px;
background: #2fc4ab;
opacity: 0.5;
padding: 20px;
width: 370px;
height: 320px;
margin-left: 180px;
font-family: Product Sans;
font-size: 200px;
text-align: center;
}
its just a text yes
then make this logos position relative
and the text divs position absolute
<div class="logo">
<p><_</p>
</div>
look ive wrote this in the html file
oh okay, then just put a class for the p
ohh...
okay..
and so when you put the p tag as absolute, also put this in
top: 50%;
left: 50%;
translate: transform(-50%, -50%);
okay i'll
the reason you put translate transform -50% is because the left and top 50% translation starts from the top left meaning you need to balance it and bring it to the center
oh lol its even more separated now... it has gone more far
hmm..
did you put the logo class as relative?
yes
oh yeah 😭
here... because now i've created another class for the text... thats why maybe it didnt work
i'll just copy and paste that part
let me pull this up on my laptop real quick lmfao
lol
i've worked in css before too... but that was 2 years ago lmao... i've now forgotten almost all of it
i see
what should i do now
<style>
.logo {
border-radius: 25px;
background: #2fc4ab;
opacity: 0.5;
padding: 20px;
width: 370px;
height: 320px;
margin-left: 180px;
font-family: Product Sans;
font-size: 200px;
text-align: center;
position: relative;
}
.logo_text{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -150%);
}
</style>
<body>
<div class="logo">
<p class="logo_text"><_</p>
</div>
</body>
oh wow
for some reason putting the translate to -150% works
its just a bit buggy for some reason
-150% ??
yea
yeah that can happen sometimes
meaning its going upwards by 150%
yes
send the code
thats fine
should i send them both?
yea
okay gr8
.header {
padding: 30px;
text-align: center;
font-family: 'Product Sans';
font-size: 40px;
background-color: white;
}
.header p {
font-size: 40px;
}
.logo {
border-radius: 25px;
background: #2fc4ab;
opacity: 0.5;
padding: 20px;
width: 370px;
height: 320px;
margin-left: 180px;
font-family: Product Sans;
font-size: 200px;
text-align: center;
position: relative;
}
.logo_text{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -150%);
}
``` thats the css
and
<!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>Bash Commands</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="header">
<h1>Bash Commands</h1>
<p>Scripts made with Python!</p>
</div>
<div class="logo">
<p class="logoText"><_</p>
</div>
</body>
</html>
``` thats the html
is the logo inside header?
no
there we go
i was working on that for more than 3 hours now... it finally worked
when you want to create interesting looking things
yes it is
because positioning is very easy with it
yeah
same with flexbox but you can be more creative with absolute positioning
hmm... i'd prefer absolute positioning
thanks again mate
now say if i want to change the background color of the entire website at once... can i do that??
yes just do
body {
background-color: color;
}
.
Hey pls help me
<html>
<head>
<title>Practice test </title>
</head>
<body>
<h1 align="center">
Welcome to the world of the environment</font></h1>
<iframe width="560" height="315" src="https://www.youtube.com/embed/bKSGKFUBrGc" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</video>
</body>
</html>
Can u tell me the attributes nd tags
In this code
Plzzzzzz
@native tide @tall sentinel @obtuse robin @native tide
@west chasm
refrain from pinging people
Can u help me
sure, but can you be more specific
html tags are just the things between the angle brackets
<title> is a tag
Ohk
?
Tysmmmmm
Hello guys, I am able to get a response with jwt token via axios in vue3, but it looks like setting the axios header with bearer and jwt token not work.
async submit () {
const credentials = {
username: this.form.email,
password: this.form.password
}
axios.post('http://127.0.0.1:8000/login', credentials)
.then((response) => {
localStorage.setItem('jwtToken', response.data.token);
setAuthHeader(response.data.token);
console.log(response)
})
.catch((err) => console.log(err.response));
import axios from 'axios';
const setAuthHeader = (token) => {
if (token) {
axios.defaults.headers.Authorization = {'Authorization': `Bearer ${token}`}
} else {
delete axios.defaults.headers.Authorization;
}
};
export default setAuthHeader;
in main js i have this
if (localStorage.jwtToken) {
setAuthHeader(localStorage.jwtToken);
} else {
setAuthHeader(false);
}
it works fine with via curl. but it does not seem to be working via vue...
I am stuck at a JavaScript problem. The details are in #help-rice, please help me
When a project is fun to work on the time taken becomes irrelevant. ❤️
and noww im angy
why wont it work
i did everything every tutorial told me
anyone knows what to do?
i alr have my project interpreter configured
Maybe just restart VSCode
Ohh it should be
from flask_sqlalchemy import SQLAlchemy
Reactivate your virtual environment, right now it's not active
Judging from the terminal
Yeah, the yellow underline is related to Pylance error sometimes
okay i am restearting my laptop
when life gives you error
turn it off and on again
I guess it has nothing to do with the laptop, but it never hurts to restart
nothing
i am losing hope
i need that tb to save the links from the images
so it can show it on the bookmark section
You should be able to use flask_sqlalchemy if it's installed, it's just VSCode that's complaining, and run the app from the terminal
i can try
idk how to activate my venv from the terminal tho
i would have never switch from pycharm if it wasnt so expensive to use css :/
If you're in the root of your project just open the terminal there and type:
source your_venv_name/bin/activate
thankss
oh youre right
thanks
so from now on,, only terminal
UGH
i swear im gonna switch to atom
No problem
Definitely it's good thing to get used to the terminal
How are we handling multiple entries for a single column ?
I’m tempted to abstract it with a linked table . But is it normal to maybe put some sort of delimiter for the values instead ?
So option1;option2;option6
More specifically when it comes to database storage
Or would it be better to create a reference table and say
Id 1 - related table id 4 - value option1
Id2- related table id 4 - value option2 etc
I think you should use = instead of : 🙂👍
I am not getting my desired output in a flask app I am working on. The details are in #help-coconut, please help me
how are web browser games…made?
Js
hm, ok
Is it feasible to build a website using Django through which a user can perform data analysis on a file they have stored on their local machine?
i wanted to show a project i made
here it is
https://openup.rf.gd/
i would like your reviews and comments
its a platform to share your secrets and confessions openly on the internet
but anonymously
Hey I've been following this tutorial step by step
https://youtu.be/CTrVDi3tt8o?list=PLCC34OHNcOtqW9BJmgQPPzUpJ8hl49AGy
and I followed whatever was in here but why do I get an error like this?
In this video we'll start to build out the user authentication system by creating a login page.
Django comes with a pretty nice user authentication system that we'll tap into and use for all of this.
First we'll create a new 'members' app to hold all of our authentication stuff. Then we'll create a login page that allows users to log in.
#d...
class MessagesViewSet(viewsets.GenericViewSet, mixins.ListModelMixin, mixins.CreateModelMixin):
pagination_class = pagination.PageNumberPagination
def get_queryset(self):
# The pagination limit is set to 50 items per page,
# so we don't need to use .limit here
return Message.objects.filter(chat__id=self.kwargs["chat_pk"])
def get_serializer_class(self):
if self.request.method in ("POST", "PATCH", "PUT"):
return MessageCreateSerializer
else:
return MessageSerializer
def perform_create(self, serializer):
serializer.save(chat_id=self.kwargs["chat_pk"])
``` When a new message is being created I want to use `MessageCreateSerializer` but when the data is returned I want to return the representation from `MessageSerializer` since it gives a more full serialization, any way to do that?
It might be a problem in the project's url, there's an extra space after authen/
The thing you want is implemented in get_serializer_class() method. Is it not working?
it works, but MessageCreateSerializer has fewer fields compared to MessageSerializer (because it only has fields required when creating a message but MessageSerializer is intended to fully serialize a message)
when returning a response I want to serialization of MessageSerializer
Usually I use viewsets.ModelViewSet, then I have access to create(), list() etc methods, They return the expected serializers.
Instead of doing if self.request.method == "POST" you can do if self.action == "create"
Try it out, I have to go right, now, I have a meeting
If things didn't go well ping me
oh thanks, I didn't subclass ModelViewSet because I think that I won't be needing every method (list, retrieve, delete, etc)
Thanks!
It's weird, I've just checked everything and there's no space in the urls
The fix for it was overriding create() and implementing my own logic
its trying its best lmao
I'm using PageNumberPagination to paginate the messages, but how do I order the messages at by the created_at field
You want order it in the database or in the view? If in the view you could use order_by()
You can specify what HTTP methods you want the view to have
oh
how can i do that, the last time i checked the only way was to only subclass the mixins i needed
but the database fetching is done internally in the paginator, in CursorPagination i can specify the ordering attribute but seems like PageNumberPagination does not support that
Define this attribute in your view:
class MyView(viewsets.ModelViewSet):
http_method_names = ["get", "post"] # And others
thanks
i did not know that
Can you send the urls.py of your app?
No problem 👍
Yeah, there's no ordering in the PageNumberPagination unfortunately
With Django's admin, is it possible to use non fields, like custom functions inside of inlines? I always get field not found.
For instant list_display for inlines, or any way to add to them
Aaaahh readonly_fields is the solution
Double check your form. Make sure it's the method that has POST, not the action.
My bad that's why. Thank you! I was blind for not checking that.
No worries.
Hi all,
I’m trying to make a website that can show results from my SQLite database, something like this: https://imgur.com/xNP95TA
I’m wanting to query a database of
information and narrow down the
query via multiple simultaneous user inputs. Anyone have something that may be able to give me a headstart? Cannot find much on GitHub
Like a live filter fields
Flask + SqlAlchemy: Is it good practice to use data model classes for general purposes across the app? Example class Order will not only store data, but will process order logic, calculate package weights...
Django can do the work too.
hey guys I am making a website and I am using cdnjs libraries to import files (linked to my html file) that allow my site to include a box slider. I was wondering how do I edit the default code that is in a cdnjs library and change the css?
thanks
Django might help you with that.
best if you can make a class specific for what its called. If the class is called Order, then it should only contain everything about the order. And if it contains other classes, then it should have a reference of those other classes as an attribute to the Order class.
is anyone here good at tailwindcss?
like, in terms of being good at implementing your designs
with it
what resources did you use to learn the framework?
I love the lack of dependencies it uses... but im not good at it
i need to learn all the classes i suppose.
hey can you help me with flask
if you have a simple question, just ask it here. If you need more help then that read #❓|how-to-get-help and grab a help channel first
is there a way to automate my workflow with REST like whenever I add a recipe on my app I need to fill 8 forms lol
or just make it bit easier because this job is tedious
Hey people, do you know any way to do SSO integration of social media, with Python? using Django Rest Framework like login and such authentication?
perhaps an good nowdays tutorial.
Thank you so much since there
!pypi django-allauth is pretty good
and here's a video how to use it
https://www.youtube.com/watch?v=NG48CLLsb1A
In this video, I talk about how to set up Google authentication for your Django project.
https://learn.justdjango.com
☝ Get exclusive courses & become a better Django developer
New to Django Allauth? Watch this tutorial
https://youtu.be/dXZim_jgaiI
✌️ Stay in touch
Facebook: https://www.facebook.com/justdjangocode
Instagram: https://www.inst...
does flask and js mix well together?
How to move top block left down
make another div around your square divs
give it a class (or select it however you want) and to that class write display: flex
Yep without hitting submit would be better, so Ajax magic maybe 🙂
flask is a backend server library. js is a language that is commonly used on the frontend of applications. they don't depend on each other as they have different purposes. however yes you can use js to talk with a flask server
It can be very simple or very not simple. It depends on how much communication has to go on between front and back.
if its more than just light effects here and there, it usually makes the app very complex and on another level if you are just starting out with web apps.
but that is what you call a "fullstack application", one with heavy js interface and a backend api.
can fastapi serve basic html pages or do i need to use flask for that
you dont need flask to serve static html if that is what you mean. any web server can do that.
FastAPI can return HTML responses. You can also use jinja2 to render HTML templates.
Documentation:
https://fastapi.tiangolo.com/advanced/templates/
FastAPI framework, high performance, easy to learn, fast to code, ready for production
thanks
Hello.
I tried to create a model on my new Django project, using the following code in my models.py file:
from django.db import models
class userProfile(models.Model):
userID = models.IntegerField()
afterwards, I inserted "userProfile" into my installed apps in settings.py
then I typed makemigrations in my terminal but I get this error:
ModuleNotFoundError: No module named 'userProfile'
Any ideas on what I'm doing wrong?
In the INSTALLED_APPS you should include the app's name, not the model's name you created in the app.
Let's say that you created an app called profiles, you'll have a new folder called profiles. In order for Django to detect the app you must add profiles to the INSTALLED_APPS in your project's settings.py:
INSTALLED_APPS = [
# ...
'profiles',
]
Run Python code in your HTML.
export const ReportForm = (props) => {
Can we not pass props to export const components?
Nothing im trying is working
undefined
oh lord i read that as "moist catgirls" 💀
can anyone here please tell me what's the use of "span" !?!?
According to the MDN, it's basically nothing. https://developer.mozilla.org/en-US/docs/Web/HTML/Element/span
The HTML element is a generic inline container for phrasing content, which does not inherently represent anything. It can be used to group elements for styling purposes (using the class or id attributes), or because they share attribute values, such as lang. It should be used only when no other semantic element is appropriate. is very much lik...
yea that "it represents nothing" made it all confusing
could've just said it's an inline container
Well its used for styling and other things. So its an element that doesn't do anything and we can practically abuse it in HTML markup
yea just tried it in some examples
sidebar css file
.vertical_navbar ul {
position: absolute;
list-style-type: none;
margin-top: 116px;
padding: 0;
width: 250px;
height: 100%;
top: 0;
left: 0;
bottom: 0;
background-color: white;
box-shadow: 17px 0px 14px -19px rgba(0, 0, 0, 0.45);
}
.image_section {
background-color: #F8F5F5;
}
.navbarImage {
width: 200px;
height: 200px;
margin-left: 20px;
}
.navbarIcon {
float: left;
width: 30px;
height: 20px;
padding-right: 10px;
}
.dropdownIcon {
float: right;
width: 33px;
height: 20px;
padding-left: 15px;
}
.collapsible.active .dropdownIcon {
transform: rotate(-180deg);
-webkit-transform: rotate(-180deg);
float: right;
width: 33px;
height: 20px;
margin-right: -15px;
}
.vertical_navbar li a {
display: block;
color: #000;
padding: 8px 20px;
text-decoration: none;
font-family: 'Open Sans', serif;
}
.vertical_navbar li a.active {
background-color: #2176FF;
color: white;
}
.vertical_navbar li a:hover:not(.active) {
background-color: gray;
color: white;
;
}
.content {
max-height: 0;
overflow: hidden;
transition: max-height 0.2s ease-out;
text-align: center;
}
how do i dynamically increase the height of the side bar as more <p></p> content are added?
doesn't min-width affects the sidebar horizontally?
_sidebar.handlebars
<div class="vertical_navbar">
<ul>
<li class="image_section"><img src="/img/defaultUser.png" alt="User icon" class="navbarImage"></li>
<li class="collapsible"><a class="active" href="#MyProfile"><img src="/img/profile.png" alt="icon"
class="navbarIcon">My profile<img src="/img/triangledown.png" alt="dropdown"
class="dropdownIcon"></a></li>
<div class="content">
<li><a href="#changePassword">Change password</a></li>
</div>
<li><a href="#MyPurchases"><img src="/img/schedule.png" alt="icon" class="navbarIcon">My purchases</a></li>
<li><a href="myRewards"><img src="/img/voucher.png" alt="icon" class="navbarIcon">My rewards</a></li>
</ul>
</div>
the content class is a dropdown list under "My profile"
am i a real web dev guys
Hello, guys. I have faced with problem of converting tdata (telegram api) to json file, opentele does not help me. What could you recommend to me?
Depends on whether or not you've built actual websites that you've deployed out there or whether you've helped in the development of one that was deployed
I'd say you're a web dev as soon as you start learning about web dev, but you won't be recognized as one until you have some projects to your name
Look for some other libraries. If you don't know where to look for them besides discord, ask people on reddit/stackoverflow, their python community is a lot more active than the one here on discord. (Though asking stuff on discord is a lot more easier in my opinion)
Thanks🤝.
Lastly, if you can't find any libraries, use the existing libraries to create your own library. Although I won't recommend doing so until you've thoroughly done your research
I tried to create a custom library for MySQL for a flask project of mine and it was a horrible experience. Eventually, I got around to using the SQLAlchemy library
So I can speak from experience
Anyway, good luck 👍
I was joking but-
That's actually really useful
Thanks
https://catmaid-cafe.herokuapp.com
This is my project lmao
I'm quite a novice myself so I can't distinguish between jokes and well, serious stuff ¯_(ツ)_/¯
As a teen that's really into anime (one that loves anime girls at an unhealthy level), that project is epic
Good luck 👍
Hi so I've a question regarding how to solve an error with a form updating /creating model. Details are in help-donuts. Its a simple enough problem I can tell that, very simple. However I've not managed to get anyone to tell me how to resolve the issue in a way that will make it do what I want. So asking on here. Thanks.
Hey, for django testing do you use: built-in django unitest? pytest? django-pytest? Thank you for your answer
@native tide from what I know, PyTest seems to be the best option
Hello all, i have a question about Django/IPFS/Video
I need a little help about video loading on IOS. Videos are stored via IPFS.
Players work well on Desktop but on IOS, the video never load
Ok, I've fixed it. Thanks for the suggestion!
hello
I need help with something
now, is it possible to to post a parameter that is not listed by a specific api
{
"sleep_time": {
"end_time": null,
"enabled": false,
"start_time": null
},
"use_cookie_personalization": true,
"trend_location": [
{
"name": "San Francisco",
"placeType": {
"name": "Town",
"code": 7
},
"woeid": 2487956,
"country": "United States",
"url": "http://where.yahooapis.com/v1/place/2487956",
"countryCode": "US",
"parentid": 23424977
}
],
"language": "en",
"discoverable_by_email": true,
"always_use_https": true,
"protected": false,
"geo_enabled": true,
"show_all_inline_media": false,
"screen_name": "oauth_dancer"
}
```\
like for example here, I would like to change "protected" to true
but, the twitter API is not listing it as a parameter
hi im currently building a chat application using flask and using ngrok to change its url every launch so only users in the know can access it. however im running into an issue where when i use ngrok to connect to the site it shows the ip as localhost and doesnt let me use request.user_agent to gather data such as platform,language and browser which is necessary for fingerprinting users for bans etc. is there any alternative to using ngrok or any way i can make it still able to get the client ip and user agent data?
data=f"""
ip: {get_remote_address()}
platform: {dataagent.platform}
browser: {dataagent.browser}
version: {dataagent.version}
language: {dataagent.language}
useragent={dataagent.string}"""
``` code for getting user data
dataagent=request.user_agent btw
ip: 127.0.0.1
platform: None
browser: None
version: None
language: None```output from above code on request via ngrok
Can someone please help me in #help-pear.
neuralnine vid??
How did you know?
using the same base for my chat app
oh, lol
i also have a similar issue
Well then, maybe you can help.
my messages dont always send to the server and i think its an issue with socketio
ill enter text click send but the message doesnt actuallly get sent to backend
I have some selenium code I wanted to share in case it helps someone simplify their code and/or remove explicit sleeps
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.remote.webelement import WebElement
def wait_for(selector: str) -> WebElement:
"""
Wait for and return the element matching `selector`.
Waits until an element matching the specified
CSS selector becomes visible and interactible,
after which the first such element is returned.
"""
return WebDriverWait(driver, 10).until(
EC.visibility_of_element_located(
(By.CSS_SELECTOR, selector)
)
)
was able to remove all sleeps from some selenium code. Usage is just:
wait_for("button.any-button").click()```
oh it is expecting a webdriver instance named driver for brevity's sake; update that if you're calling it something else or make it a parameter if you prefer
this is my webpage... so i have a navigation bar at the top of the page... but i want the text in it to be in the center... it just doesnt work no matter how i try it... i tried to use margin... but the text gets separated a lot from each other... pls help me with this
anyone??
i'm trying to learn django, everything is fine, i'm loading templates i even have like a main html, but when i try to load some data with a for loop in another html it just won't load
what part of the code should i send, so you guys could help me ?
Your view method for just that template and also the for loop if it’s done in jinja(html)
hi, can anyone search on Google thefacepeek.netlify.app
Using flask
i want to render a template i made before
but i get TemplateNotFound Error
@app.route("/home")
def home():
return render_template("/templates/home.html")
how to i fix the path?
remove the /templates/ from the address of the file
I am creating a flask app which is basically an UI for the API of a game. The user should be able to enter their private API key and this key will be used to make requests to the game's API from this flask app. What is a good way to store this key without the user having to create an account? Is using the session storage or local storage a good idea? Or should it be handled on the server side, and if yes, how?
Can somebody recommend a basic CMS: minimum of features, zero or minimum dependencies, production ready?
I'm looking to quickly build a small website, but hoping that it's good enough to build on it a few features.
You are gonna need it on the server to make the API call, and is no need to keep it on the browser too.
I would make a dictionary, the key being the session ID from the browser, the value is the API key.
Thanks, that is exactly what I got recommended from someone else.
anytime VVoozy
@app.route("/home")
def home():
return render_template("home.html")
did... does the Templates folder has to be in caps or smth?
All small I think. templates
yeah like it is...
Still doesn't work?
nope
now it worked, thank you :D
my images dont load but i think i will figure this out later
Put the text you want to center in a container and then put margin-left: auto and margin-right: auto for the container.
Or make the topnav display:flex and then justify-content: center;
hey guys I want to ask that vscode is better or pycharm for djangp
django
do pycharm has extensions like vscode ?
hey!!, can someone please help me with middleware structure in flask
hi this might be a noob question but how is python helpful in web development? is it used for back-end?
yes
oh sweet thanks
K thanks
Why is the square rotated but not enlarged?
I'm currently trying to resolve a use-case on a Django project. Here's the question on Stack Overflow: https://stackoverflow.com/questions/72679751/django-4-x-conditional-order-by-of-a-queryset
Suggestions welcome...
Yes. Flask and Django are the two most popular web dev frameworks. Flask is simpler; Django is enterprise grade. You use Python to code the application and database layers. You use html to structure front-end web pages, css to style them, and js/htmx to manage dynamic behaviour.
In short, Python is very helpful in web development. With the width of the community combined with the depth of Python libraries, there is a lot that can be accomplished.
<h1>You can see info here about the {{product.name}} desk</h1>
<h3>Price: {{product.price}}</h3>
<img src={{product.preview}} alt="{{product.name}} Preview">
"GET /product/images/gseriesbk/image1-gseriesbk.jpg HTTP/1.1" 404
from flask import Blueprint, render_template, request
views = Blueprint(__name__, "views")
ids = ["gseriesbk", "gserieswh", "88seriesrb"]
desks = {
"gseriesbk": {"name": "G Series", "color": "Black", "price": "7.200.000", "preview": "./images/gseriesbk/image1-gseriesbk.jpg"},
"gserieswh": {"name": "G Series", "color": "Black", "price": "7.200.000", "preview": "./images/gserieswh/image1-gserieswh.jpg"},
"88seriesrb": {"name": "88 Series", "color": "Red & Black", "price": "12.900.000", "preview": "./images/88seriesrb/image1-88seriesrb.jpg"}
}
@views.route("/")
def home():
return render_template("home.html", ids=ids, desks=desks)
@views.route("/product/<desk>")
def product(desk):
desk = desks.get(desk)
return render_template("desk.html", product=desk)
i'm trying to load a picture in flask, but i get an 404 error for the image
thanks for this elaborate response, htmx is news to me! I've definitely been intrigued to learn python
aiming to learn to automate some daily things I do and expand my vision on what it can be used for
htmx is a way of partially updating web-pages (like Ajax but without the Ajax). I started with Python last April. It came up as a powerful language for web development. By June I was into Flask, by July Django. Now, I'm on my third deployed Django project.
Python can be used for a LOT of things. And when it comes to web development, the end results are very, very fast websites. When I compare the speed of the projects I've built (with considerable application complexity) with many web applications out in the wild I'm always pleased by how snappy the web apps built on Python feel.
Why is the square rotated but not enlarged?
web apps are taking over the world, man, its good scope and not gonna run out any soon
this is CSS related, is your endblock nesting any blocks inside?
True story. My profile has a couple of projects I've deployed. The business app I used with clients to support process improvement training I deliver. The event management app is in testing and is solving a currently unsolved problem. I'm currently building a digital library web app doing things I've not seen done before.
I already solved the problem, but thanks for trying to help 😁
this sounds pretty revolutionary stuff, I'm interested in seeing what you're working on if you have a portfolio or something to drop!
.
Someone provided an answer. When using pre-build functions, be sure to import them! face palm
Here is the answer. If you need to conditionally order a filtered query, here's a direction you can take:
from django.db.models import Case, F, Q, Value, When
reading_progress = ReadingProgress.objects.filter(user__username=self.request.user)\
.annotate(
date_to_display=Case(
When(reading_progress='1) On Reading List', then=F('date_added')),
When(reading_progress='2) Reading In Progress', then=F('date_started')),
When(reading_progress='3) Completed Reading', then=F('date_completed')),
)
).order_by(
'date_to_display',
''
)```
Django question: Why do we put our apps in this format:
'users.apps.UsersConfig'
in the installed_apps area of the settings.py file instead of just typing
'users'
Both ways work. The former can be useful to be more explicit about which AppConfig you want to use, if your app has multiple.
This is not for python, but html and css, how do u scale an image down, like I have a logo its current wxh is 2048x2048 how do I scale it down so it will fit and look good in the navbar (either reply, dm, or @ me)
In css?
You can set the dimensions of the image in HTML. They are attributes of the img tag e.g. <img src="..." width="200" height="200/>
If you don't need to image to scale dynamically then that approach is fine.
If you do need it to scale dynamically, you could use object-fit in CSS or width and height in CSS.
python-based server frameworks also really integrate well with asgi deployment which can provide reeaally fast asynchronous operations on servers. my only drawback about django in particular is that there's not much availibility for alternative libraries. for example it's really difficult to switch to a different ORM if you like a different one. i've recently switched to nestJS from django and haven't really looked back. i like it because it comes with all the batteries included as django does, but you also get to kind of pick-and-choose your functionality based on the wide options of different libraries ready do to a task
That's wonderful to read. When you find something that works for you, that's always amazing.
Django is working for me. I'm finding the ORM to be potent. When I bump into a wall where I can't accomplish the objectives I have then I'm sure I'll be shopping around.
That said, I will confess the rumour of async coming to Django is one I'd love to see come to pass!
Are you guys serving your react and django on individual deploys or combining them into one ?
I’m running on heroku for django and Netlify for React at the minute but wondering if that’s best when I push it to production
Hi, I am trying to upload photo from gallery in phone to flask but i get
ImmutableMultiDict([('file[]', <FileStorage: '' ('application/octet-stream')>)])
when i print the file can anyone help me how to upload file from gallery ?
Guys, what is the best approach here? To have logic handling all 3 forms in the welcome endpoint or to redirect to 3 different endpoints which will handle it separately?
@app.route("/welcome", methods=["GET", "POST"])
def welcome():
if current_user.is_authenticated:
return redirect(url_for("index"))
loginForm = LoginForm()
if loginForm.validate_on_submit():
print("LOGIN")
flash(
"Login requested for user {}, remember_me={}".format(
loginForm.username.data, loginForm.rememberMe.data
)
)
# logic authorizing the user
return redirect(url_for("login"))
signUpForm = SignUpForm()
if signUpForm.validate_on_submit():
print("SIGNUP")
return redirect(url_for("signUp"))
resetPasswordForm = ResetPasswordForm()
if resetPasswordForm.validate_on_submit():
print("RESET")
return redirect(url_for("passwordReset"))
return render_template(
"welcome.html",
loginForm=loginForm,
signUpForm=signUpForm,
resetPasswordForm=resetPasswordForm,
)
Not sure which option is better, to have it in one bigger module, or to have it in separate endpoints and risk it being 'too' modular
Hey, i have just deployed my chat app on heroku however im having a few problems. One of which i cant actually login using the https url because i get a 403 forbidden error. I can only login using http in the url. Anyone know why this is the case?
someone helped me fixed it not long ago
although i still got an issue where the time is displayed in utc but when i was using it on local machine it was proper
ah ok
jesus
insane
hello! a random question. is there a way to search YouTube videos without using YouTube data API?
I have a kind of vague question. In Flask + Jinja2, without any frontend framework, what is a nice way to use view functions which needs to return a lot of data in its parameters, e.g.; return render_template('template.html', param1, param2,...,param10)? I think it's better to jsonify the response and handle the json in the templates somehow, but is there a standard acceptable way to do this?
Or is it better to simply bundle the parameters in a dictionary and access them with Jinja?
you can pack/unpack the parameters
params = {
'param1': 1,
'param2': 2
}
return render_template('template.html', **params)
Thanks, didn't think about this
With Selenium or scrapping.
https://www.selenium.dev/
https://beautiful-soup-4.readthedocs.io/en/latest/
thanks mate. I'll check it out
i know about selenium but need to check beautiful soup
i am learning django
this is django framework
if my user form is this raw and i intentionally tried to put 2 different passwords why i am not getting the {{form.errors}} when i am trying to render it on my template is it because all warnings are already shown?
this is the template
yo guys just a question. when using vue app in developer mode via npm run serve it always reload when content is changed. Is it possible to keep this feature when i wont run it in developer mod ?
oh btw. do u think a rest api would work if i host it on some cloud to get some details like YouTube video url and stats etc?
yeah, why wouldn't it
what do you mean by outside developer mode?
request.POST or None means none data will be saved in sql or something else ?
probably means in production
What are you trying to achieve here? Server gets refreshed when code changes. But in production your code won't change so what's the point of the refresh?
anyone have a minimal http server recommendation?
- I am running this in prod
- I do not need templating; I'm not serving HTML; just responding with JSON
CherryPy seems reasonable
I did research for this several years ago and out of all the options I liked Falcon the most. It's a microframework so it doesn't have all the bells and whistles you don't need. It's also actively maintained (which can't really be said for something like bottle).
I think Falcon has some dependencies, but very few.
Actually no, it has none.
I used it for a dead simple HTTP REST API that operates on JSON. Worked perfectly.
Also had support for jsonschema validation so I used that too.
tyvm
Hi, I wanna ask about customization Registration and Login forms.
I use from django.contrib.auth.forms import UserCreationForm. And I want to set only 4 field in User models, name, username, password, avatar. What should I do step by step?
@wet cliff I want to develop in production 
any pros want to help a brotha out lol
YouTube search python is a library that works for me
is it free to use? or does it have any limits on number of requests?
its exactly what i needed mate. thank you
the limits are imposed by youtube, not the library
Hi there, I am trying to generate pdf form a html template in Django. After unsuccessful attempts with xhtml2pdf or weasyprint I managed to get it work with headless chrome (django-hardcopy). However now I have deployed my app to Heroku, and need to somehow connect django-hardcopy with chrome buildpack installed on Heroku. In development, for django-hardcopy, I used a local path for chrome.exe. Now I need to somehow redirect my hardcopy to get chrome form heroku buildpack. Any hints on how to do this? I am using the official chrome buildpack https://elements.heroku.com/buildpacks/heroku/heroku-buildpack-google-chrome
I am trying to share a file using blob using but file name is changing in only android can anyone help me ik this is python server but i am not getting answer from javascript server so post it on here
async function WhatsappShare()
{
var fileArray = [];
for (i = 0; i < document.getElementsByClassName('divclass').length; i++)
{
sid = document.getElementsByClassName('divclass')[i].id;
if (document.getElementById(sid).querySelector("#txtImgLink").value != "")
{
var _ImgLink = document.getElementById(sid).querySelector("#txtImgLink").value;
var blob = await (await fetch(_ImgLink)).blob();
var file = new File([blob], "Test.jpg", { type: blob.type });
if (blob.type == 'image/png' || blob.type == 'image/jpeg' || blob.type == 'image/webp')
{
fileArray.push(file);
}
}
}
if (fileArray != '')
{
navigator.share({ title: "Sharing from Vikas Portal", files: fileArray });
}
else
{
GetDocumentAlt();
}
}```
this is my code
Hello everyone - it would be greatly appreciated if someone can help me out. https://stackoverflow.com/questions/72690027/flask-cant-import-name-create-app-from-website Thanks!
I have a simple question .How does the template get access to the models objects when nothing is passed to the template
Like for example in function based view
s=Student.objects.filter(id=1) return render(request,' template.html',{'s':s})
we do something like this and then we can use the objects in s in the template....but how does this work in Class based view?
you have overwrite context_object_name by default it use student_list (if I'm not wrong)
it's really simple,
Not sure if I got your question 🤔 in CBVs (class-based views) you override the get_context_data to pass the values you want to the frontend, with the name you like
Also this, if you don't override the get_context_data you can override this attr class so that you can access with this name in the template
that being said how is the template able to acess those objects thats my question
you send object to the template)
is it sent automatically?
Django is doing all the tricks for ya under the hoods. It will glue the template and the values you're passing so that you can use there
yeap
ok thank you....
is it same for form view?
like in fbv we made the object of form class then we pass it to the template so is it done automatically in case of formView
from what I can see, yes it will work the same way as in a FBV
Interesting. I hadn't seen that they added this, looks nice.
hey guys, how to have two django projects running on different ports communicate with each other?
Is there even a tutorial for this?
see it
<!doctype html>
<html>
<head>
<title> INDIA </title>
</head>
<body>
STATES OF INDIA <hr>
<ol style="list-style-type:lower-roman">
<li> ANDHRA PRADESH </li>
<li> ARUNACHAL PRADESH </li>
<li> ASSAM </li>
<li> BIHAR </li>
<li> CHHATTISGARH </li>
<li> GOA </li>
<li> GUJARAT </li>
<li> HARYANA </li>
<li> HIMACHAL PRADESH </li>
<li> JHARKHAND </li>
<li> KARNATAKA </li>
<li> KERALA </li>
<li> MADHYA PRADESH </li>
<li> MAHARASHTRA </li>
<li> MANIPUR </li>
<li> MEGHALAYA </li>
<li> MIZORAM </li>
<li> NAGALAND </li>
<li> ODISHA </li>
<li> PUNJAB </li>
<li> RAJASTHAN </li>
<li> SIKKIM </li>
<li> TAMIL NADU </li>
<li> TELANGANA </li>
<li> TRIPURA </li>
<li> UTTAR PRADESH </li>
<li> UTTRAKHAND </li>
<li> WEST BENGAL </li>
</ol>
</body>
</html>
Im using Pub/Sub and Compute Engine. I create a Message from my Django Backend and then also create a Compute Engine instance. The Compute Engine then pulls the message.
Code in the Compute Engine
def callback(message: pubsub_v1.subscriber.message.Message) -> None:
cloud_logger.info("Received message: {}".format(message.data))
# decode message data back form bytes to string
data = json.loads(message.data.decode('utf-8'))
try: # try to create model
create_model(data['target'],
data['uid'], data["model_id"], data["mode"], data["user_type"], bucket)
except Exception as e:
exception_type, exception_object, exception_traceback = sys.exc_info()
filename = exception_traceback.tb_frame.f_code.co_filename
line_number = exception_traceback.tb_lineno
cloud_logger.error("Error: {}".format(
exception_type, exception_object, exception_traceback, filename, line_number))
update_model(0, data['uid'], data["model_id"], 0, "", "failed", data["user_type"], str(e))
message.ack()
streaming_pull_future = subscriber.subscribe(
subscription_path, callback=callback)
with subscriber:
try:
cloud_logger.info(
"Listening for messages on {}..\n".format(subscription_path))
streaming_pull_future.result(timeout=30.0)
except TimeoutError:
cloud_logger.error("TimeoutError")
streaming_pull_future.cancel()
self_kill_engine()
Its receiving the message but then instantly throws a TimeoutError. It worked before when my Compute Enginge started faster, but now it has a longer taking start-script. Does this effect the timeout in the .result() function ? Because the code is getting executed after everything else is installed from the start-script
@normal tokenmaybe you need a system of passing messages from one to the other
elaborate?
I dunno, it could be as simple as having a dir somewhere on each site, which the two sites where the dir is, would check it periodically
you might be referring to microservices. try looking into that
django is a very "heavy" framework, so it might not be suitable for a microservice approach
Yep
Can you guide me to a resource? that I can refer to?
Hi can anyone help me with uploading file from react
when i choose the image, i get something like C:/fakepath/filename.jpg.
seems django doesnt support that path. how can i get rid of it
i've heard it's pretty good. haven't gotten around to reading it myself, but it should give you a solid insight into microservices
can someone here help me with flask
First, you need a hosting service.
You have a public ip already?
You should use gunicorn to host a production server, then link it to a proxy application like nginx
apache
In that case, you can install mod_wsgi
I'm reading along with this btw.
https://wiki.archlinux.org/title/Apache_HTTP_Server/mod_wsgi
flask is a wsgi implementation
ok
ok
fyi your package manager probably has mod_wsgi already if you're using the system python instead of a virtualenv
should be port 80.
ok
Are you port forwarding? Maybe using a no-ip service?
Then using your public ip should work.
Don't run it using flask run
use apache to run it.
flask run is a development server anyway.
which means it's not as efficient and exposes certain things to users
^
ubuntu
just run sudo apt-get install mod_wsgi
sudo apt-get install libapache2-mod-wsgi
now run sudo apachectl restart
don't worry about that
ok
Read this for configuring.
https://modwsgi.readthedocs.io/en/master/user-guides/quick-configuration-guide.html
now how would i make an api?
that should be already written. This is guiding you on how to make it public.
so how am i meant to run it
You're supposed to configure it in your httpd.conf
i dont have that file
it's in /etc/
no
I suggest switching to nginx
no
Then the link above is all you need.
The python file has to contain a application function. You can just assign application = api.app
WSGIScriptAlias /myapp /usr/local/www/wsgi-scripts/myapp.wsgi
See the "Mounting The WSGI Application" section
Did you read the vhost link I sent earlier?
this one?
yes
ok
what do you meant by this
mean
You could have a localhost specific vhost
That's it. Plus you could add some apache specific configurations
ok
do i need to pip install api?
is this the whole file?
yes
should i make that now?
how
i.e. ```py
api.py
from flask import Flask
app = Flask(name)
@app.route("/")
def index():
return "Hello, world!"
application = app
that's a mistake. You just need __name__
Though a name is required for blueprints if you ever get into them.
now how should i change this for me?
you could also do application = app = Flask(...)
i have done this
/ is the root path on the web server.
does that mean that the api will be ip/nameofapi
WSGIScriptAlias /myapp /usr/local/www/wsgi-scripts/myapp.wsgi
do i ahve to put that in virtualhost
Yes.
ok
So that's basically the default.
can i do
<VirtualHost *:80>
WSGIScriptAlias /myapp /var/www/html/admin/planktum/api.py
</VirtualHost>
Should work. Do you have any static files?
what are static files?
files served directly from the file system.
sorry im a bit confused what u mean
Then don't worry about it.
It might be a good idea to learn apache beforehand.
ok
technically, I don't know apache. I prefer to use nginx.
ok
i will try something else
AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using IP Set the 'ServerName' directive globally to suppress this message
how could i get rid of this?
Set the 'ServerName' directive globally to suppress this message
what should i set it to?
ok
hi all, in react im setting a modal body using state on click of a button.
In the state im trying to map an array which relates to the original item.
im populating that array using another state from an axios call to my django backend.
the modal pops up and my original item is listed.
But the fetched data at the bottom is an empty array unless i exit the modal and go back in.
Essentially its setting the second state succesfully but its not rendering in time for the modal.
Id expect it to update the values once they load, but i think since the modal body is specified by a state it becomes static and doesnt update.
does anybody know the correct way to go about this?
Even if i managed to get around this fact, i kinda need the modal data able to update as im going to be potentially adding data in there
function PopUp({subState, children, title, openPopup, setOpenPopup, props, EditopenChecklist}) {
const handlePopUpClose = () => {
setOpenPopup(false);
};
//const{title, children, openPopup, setOpenPopup} = {...props};
return (
<div>
<div className="overlay"></div>
<Dialog className='myModal' open={openPopup} >
<DialogTitle className='myModalTitle'>
{title} <Chip onClick={handlePopUpClose} color="error" label="X"/>
</DialogTitle>
<DialogContent setOpenPopup={setOpenPopup} EditopenChecklist={EditopenChecklist}>
{children}
{subState}
</DialogContent>
</Dialog>
</div>
)
}
I managed to get it to load on first click by creating an additional variable called subState, and populating the axios call into an array within the api call function.
The only problem now is its still there if i open the modal for a different reason (that doesn try to set the subState since its retained)
I can put something in to the modal submit and close function to wipe the substate, but that will only be necessary for half the time. it feels wrong
I want to pass html code through flask in a varible. For example python return render_template('index.html', importable_html="<img src='image.jpg'/>") then within the html I want to have that image load as a normal image with <div> {{ importable_html }} </div> Is this possible?
yeah i think so. you need to put it in brackets i think ,
but if you know youre always going to have an image there it might be cleaner only making the target a variable .
importable_html=('image.jpg')
then in your template...
<img src={importable_html}/>
i cant remember if you need double or single {{}}, its usually double but i rermber something weird about doing this for nits of divs
.
I'm a bit stuck, trying to do something with Flask - and I am wondering if it's even possible. In my route method, I've defined an argument and set a default value. My goal is that when a user submits a form, I redirect to the same route, but want to pass a new string in that variable to have it execute some different logic, so that my jinja template renders a different block of code (namely, the second part of a form).
Is that even possible, or am I approaching this the wrong way? See my route method here:
@app.route("/session_management", methods=["GET", "POST"])
def session_management_builder(action='initial'):
if action == "initial":
title = "SM Builder - Event Info"
form = sm_forms.EventInfo()
if request.method == "POST" and form.validate_on_submit():
print(request.form)
global form_data
form_data = {
"event_name": request.form["event_name"],
"pm_name": request.form["pm_name"],
"ff_pid": request.form["ff_pid"],
"account_name": request.form["account_name"],
"account_number": request.form["account_number"],
"event_code": request.form["event_code"],
"ah_url": request.form["ah_url"],
"start_date": request.form["start_date"],
"end_date": request.form["end_date"],
"event_timezone": request.form["event_timezone"],
"expected_attendees": request.form["expected_attendees"],
}
session_management_builder(action="support_info")
return render_template("session_management.html", title=title, form=form, action=action)
elif action == "support_info":
title = "SM Builder - Support Info"
form = sm_forms.SupportInfo
elif action == "upload_data":
title = "SM Builder - Data Upload"
form = sm_forms.DataUpload()```
The elif statements there aren't written yet, so can be ignored for now.
Then, within my jinja template, in my content block, I have an if statement
{% if action == "initial" %}
Or some other string - and no matter what I do its not working - making me think that perhaps my approach to this is flawed.
session_management_builder(action="support_info")
Im not sure of the solution but it might have to do with how you're setting this variable
and using it in your function, because it might just be reseting back to action=initial everytime you render
def session_management_builder(action='initial'):
because of this
again, im unsure, but you might have to create seperate methods to overcome this
def session_management_builder(action='support_info'):
Your stuff here
if its that you're trying to maintain a trail of the same form data then id focus on grabbing the form response and redirecting using a pk possibly.
just a suggestion, i might not be on the money tho
Hi, I'm wondering what is the best way to host a flask app? Searching for something free or cheap... (I'm European)
Thanks (ping me if you have an answer please)
try this, but keep looking https://eu.pythonanywhere.com/
Host, run, and code Python in the cloud: PythonAnywhere
nice thanks!
o/
i am new
can someone explain that why theres no black line or something for the div there
try to copy / paste the code, don't take a picture of it, so we can test it without rewiting it
see this in the top left corner
it looks like an end of a comment
and you have no comment on your html
so first try to view the Practice.html file firectly in the browser, to make sure the html is ok
then try to find why the program that listens to the port 5500 is not serving it
with right click => view source you can see what the browser receives from that program, it may help you finding out the bug
as a general advice, make the simplest thing to work then add small changes to it and verify them right away, so when something is not working you know it's from the last change
Hello,
i have a Django Modell that has object_id as Primary Key and this is a CharField. I use graphene for API and when i create everything works until graphql has to return something, then it says cannot convert string to float. But i want the primary key to be a string not a float also when graphene returns it
Also heroku might be a good option
I'm curious, never used graphene. But how graphene plays here with the Django model?
Thanks, I'll try!
either heroku or pythonanywhere
I have a mutation that create with a serializer a model and then return wanted values, and there it want to parse string to float
Is there any offers for students?
so the mutation uses this serializer to serialize the model and return it with the wanted values?
Not sure, but I don't think so IIRC
yes so you create the model, and for example you want to know the primary_key(string) and the name(string). It throws an error when it needs to return the primary key as string
yes but if you want a custom domain on pythonanywhere for example you have to pay :/
nice
you can kinda name it for free
not fully it’ll be like “name.herokuapp.com”
if you’re okay with that lol
name as in you can change it to anything
no I have my own domain and I wanna use it
okay np!
is this a code you can share?
Django Model
class EventSourcedModel(models.Model):
object_id = models.CharField(max_length=255, null=True, blank=True)
Serializer
class UnternehmenCreate(Mutation):
unternehmen = Field(UnternehmenType)
class Arguments:
unternehmen_data = UnternehmenInput(required=True)
@login_required
def mutate(self, info, **data):
unternehmen_data = data.get('unternehmen_data')
print(f"unternehmen_data: {unternehmen_data}")
serializer = UnternehmenSerializer(data=unternehmen_data)
serializer.is_valid(raise_exception=True)
return UnternehmenCreate(unternehmen=serializer.save())
Types
## UNTERNEHMEN
class UnternehmenType(DjangoObjectType):
class Meta:
model = Unternehmen
class UnternehmenInput(convert_serializer_to_input_type(UnternehmenSerializer)):
pass
And before i get the UnternehmenType back from the Graphene it wants to convert the primary key to a float
Wait, I'm not sure if my eyes are playing with me, but where the EventSourcedModel enters in this code?
i am using Django drf and i have question, is not bad practice if i validate data in view? concrete in post method
Its my custom basemodel all models extend from that
Hello everyone, when using FastAPI OAuth2PasswordBearer, is there a way to create a custom OAuth2 that instead of receiving username in the body, it receives email
If I create a custom form like below it works, but it can't be used by the swagger, for example if using OAuth2PasswordBearer(tokenUrl="authenticate")
class OAuth2PasswordWithEmailRequestForm:
def __init__(
self,
grant_type: str = Form(default=None, regex="password"),
email: str = Form(),
password: str = Form(),
scope: str = Form(default=""),
client_id: str | None = Form(default=None),
client_secret: str | None = Form(default=None),
):
self.grant_type = grant_type
self.email = email
self.password = password
self.scopes = scope.split()
self.client_id = client_id
self.client_secret = client_secret
Can anyone please help me out? I'm trying to use pydantic to parse the response,but it isn't working.
class User(BaseModel):
name: str
@app.route("/",methods=['GET'])
@webargs(query=User)
def index(**kwargs):
response = kwargs
return response["name"]
I keep getting keyError: 'name'....I'm new to Flask so I don't quite understand the error
I was going through a tutorial and the guy used
this is his filter ss given
`
data3=User.objects.filter(mypage__page_cat='Programming')
`
I know about django field lookups but what is this?Any idea what this is will help a lot
model and views given above
One edit the guy used related name in model fields and changed it to mypage,mypost but my question is how did Post object use User fields and vise-versa
you can query related tables with the double underscores. Django will join the tables for you
Thank you so much
Hi guys has anyone ever done a whatsapp Webhook using whatsapi api and flask with heroku
Is anyone remembering a known video (trying to find a link)
where a small web company guy was telling how to communicate with client
and whole video his lawyer was present and he was telling how lawyer helped him through his work?
the video was something among the lines of how to say no and handle stuff correctly in negotiations / why important to have lawyer
it was kind of really funny video
and video was lasting 1 hour
it was kind of good for freelancers
if google would be able to handle this request, I would have been searching as youtube, funny, web company, freelancers, contract negotiation, lawyers, 1 hour
Apresentação de Mike Monteiro da Mule Design e seu advogado Keith Levine no Creative Mornings, um evento internacional que acontece mensalmente em São Francisco, Los Angeles, Nova Iorque, Zurique, e outras localidades, incluindo uma palestra de 20 minutos e um café.
Para ativar ou desativar as legendas, clique no primeiro ícone no canto inferi...
id hire you.
Hello, I'm a fullstack django dev and from my beginning of my career I've I've been using django( almost 4.6 years). These days FastAPI is becoming so popular and in 4 years of its span, many people started using it and it also has more than 45K GitHub stars in a quick span..
from the beginning of my professional career till now I've never used any other backend framework, because django was serving all my needs and that's why I'm still using it and I still love it.
But going forward should I stick to django?
Why FastAPI is growing so rapidly fast (just look at the GitHub starts)
Is FastAPI is going to be future for python backend web development?
Does django has any future? From version 3 django team has given us the async views and from 4.1 onwards django will provide async capabilities for the ORM as well.
So how does future holds for Django when we compare with FastAPI?
Django will remain popular anyway
I would say with 4.6 years in django you are overexperienced already and should dive into FastAPI
it is just not healthy to be that overspecialized
FastAPI is cooler because..
- In python there are only three frameworks to choose: Flask, Django and FASTAPI, as they are all the most popular and the most supported by community, and you will find more developers already used to those solutions.
- Out of all three FASTAPI is preferable because: it is the most performant out of three, https://www.techempower.com/benchmarks/ , around 3-5 times faster than its competitors.
- FASTAPI is oriented to serve as JSON formated REST API backend first, while Django and Flask require additional addons to have it
- FASTAPI should be providing relatively minimal necessary stuff out of the box to serve as backend, without forcing its architecture too much on the application (like Django does)
- FASTAPI does not have limitations in async support like Django does because of its still incompatible sync Django ORM
- SQLAlchemy is the most popular and supported solution in Python community, supporting async stuff which makes it perfectly compatible with FASTAPI which is async compatible too.
I think performance reason is sort of one of main ones, though considering http delay stuff it is not that important
but considering that async flares the best in http delay stuff, it is actually important
probably scratch the architecture part though, in theory they should be more or less equal at that part 🤔 Framework is framework after all, and it does not matter that FastAPI is more microframework than batter included like Django is
Thanks you for the detailed explanations.. much appreciated 👏
U a welcome. Just to be sure when I was saying overexperienced i was meaning...
...not that you are overexperienced
but that it is usually expected more diversity in skills from senior ranked skills
at least in technologies so closely similar
for true seniors it is actually even does not matter tbh, as they are just expected to have generic best SWE skills
but you know the market... sort of expects you to learn the stuff that is in use? popular?
Totally agree with your point!
with having frontend stuff of course you are already quite diversified but still backend stuff should not be neglected xD
anyway, learning FastAPI u will just increase the pool of jobs you can land on, easier to get hired, so direct advantage for you
Agreed! Thank you so much @inland oak I'll start with FastAPI then 
wow i didn't know fastapi was primarily focused on serving JSON data almost out-of the box. that's cool
how memory efficient is FastAPI in general? o.o
I have a problem, my flask app that is on heroku is not working I am getting this error on the logs.
2022-06-23T01:35:22.841832+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=random-xkcder.herokuapp.com request_id=2aed6ea7-442c-4390-ae00-d139e0a9bd87 fwd="175.157.36.32" dyno= connect= service= status=503 bytes= protocol=https
2022-06-23T01:35:23.695767+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=random-xkcder.herokuapp.com request_id=1486e9fc-a4ef-4319-bdd8-175ec5657fdf fwd="175.157.36.32" dyno= connect= service= status=503 bytes= protocol=https
new error
2022-06-23T04:00:48.603947+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=random-xkcder.herokuapp.com request_id=58c6652b-2b4b-45e1-8a53-92dfe9ef2fee fwd="175.157.36.32" dyno= connect= service= status=503 bytes= protocol=https
2022-06-23T04:00:48.920791+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=random-xkcder.herokuapp.com request_id=f88e4f6a-d2d7-41ac-90f1-110d52afe820 fwd="175.157.36.32" dyno= connect= service= status=503 bytes= protocol=https
Hi I am using flask python I want to use a form but only during a get request will this work? There is no post request. if request.method == 'GET' and form.validate():
Thanks for the help
No need of this anymmore
I'm not a Flask guy but if the request object is similar with the Django one, that would be correct
hello,
I am using django , when I use locahost instead of 127.0.0.1: another project is running
how to resolve this, can someone please help
Are you running another project on the same port 8000? If yes you can use something like python manage.py runserver 8001 so that Django will run in a different port and you can access by 127.0.0.1:8001
no sir
This here might help you then https://stackoverflow.com/a/54769851/3716354 if you're getting this error you must have something running on the same port, need to figure out what. Depending on what the process is you can kill it. Another thing you can check is if your /etc/hosts file (if you're on Linux) have the 127.0.0.1 pointing to localhost
❯ cat /etc/hosts
127.0.0.1 localhost
Hi, I'm using Django for build a quiz app with REST API. But I want to generate the question into JSON response and use it later. Endpoint of generateSoal() is http://127.0.0.1:8000/generate-soal and the endpoint of simpanJawaban() is http://127.0.0.1:8000/simpan-jawaban. How to access the JSON response from generateSoal() into simpanJawaban()?
I don't think it's a good idea to call and endpoint inside the other. I've seen this before and it can became a nightmare. What you can do is to extract the business logic into a separate function and reuse it where you need
Did you have an example or reference links?
Not at hand, but I think that what you wanna do is move the code from generateSoal line 6-19 to a separate function. Also, create a specific serializer for the Soul model. Then that separate function would return something like return SoulSerializer(query, many=True). With that you would be able to use this function in both generateSoal and simpanJawaban
Am I able to .add(*items) to m2m in transaction.atomic() block?
I've never tried it but I can't see why it wouldn't work
The problem is .add() execute a query, but we can't execute any queries inside atomic block
Can't we? I might be totally wrong but for me the purpose of the atomic block is to make sure that all the DB operations are fully executed. If any fail it will roll back. Nothing related to avoid queries to be executed 🤔
Partly you are right. But as I said add() execute additional query means it's creates own transaction (I might be wrong, I'm not as good in DB terms)
Hello, is anyone familiar with leafletJS ?
Or what channel should i ask for people familiar with it?
A JS library or an SDK
Ah I see. So it might create another transaction. Well I don't see it as a problem. Let's say you have something like:
with transaction.atomic():
# some operations
my_instance.m2m.add(*items)
# more db operations
I mean, you have more DB operations than just the .add I think a block of code like that wouldn't be wrong. However if the atomic is just for the .add then I think you don't need it because like you said it already creates its own transaction
I need to add relation for over than 500k objects along with the creation and setting other relation
If you wanna process maps for data analysis you can try to ask ppl there #data-science-and-ml
Yess it’s about maps generally, thanks
That sounds like a lot 😬 Maybe you could use some chunk approach? Or if this is the amount of objects you need to work, a better approach would be to do it async (celery, huey)
It's a tree structure with 2 self relations, so I can't do it async
Hey i recently create a site with django, gunicorn and apache, everything works fine except that ANYBODY on the internet can use my server as a proxy to access any site.
Who had thought that when you configure it as a proxy it will serve all proxy requests, not just the configured ones
ProxyPass / http://127.0.0.1:8000/
ProxyPassReverse / http://127.0.0.1:8000/
Hi guys has anyone ever done a whatsapp Webhook using whatsapi api and flask with heroku
Maybe any tutorial you could share with me
I used heyoo to send WhatsApp messages but receiving I haven't figured how to do it
I have this element but the problem is the id constantly changes when you refresh the page is there a way by getting the element by the title?
how do you get an element by the title tag
What do you mean "get" exactly... using xpath? Can you show some code of your current attempt?
from signal import pause
import selenium
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver=webdriver.Chrome()
driver.get("link")
loginbtn=driver.find_element_by_id("loginbtn")
anmeldename=driver.find_element_by_id("username")
kennwort=driver.find_element_by_id("password")
anmeldename.send_keys("blank")
kennwort.send_keys("blank")
loginbtn.click()
fortsetzen=driver.find_element_by_class_name("btn-primary")
fortsetzen.click()
I figgured out I could just use the class name to get the button element
and by get I mean find the element
I currently have this scss loop defining a bunch of rules on a data- attr. Is there a better way to do this? I tried using calc(attr(data-u-height) * 1rem); but firefox said it was invalid.
@for $height from 1 through 52 {
.elevation-device[data-u-height="#{$height}"] {
// add twice the height -1 to compensate for the border
height: calc($cell-height * $height + ($height - 1) * 2px);
}
}
Isn't a way to change, in FastAPI, the OAuth2 flow from Username at the form to Email variable?
it's just a variable name. You can display it to the users however you like.
just add a comment to the api notes that username is email
how can I run a python file in a website? I want like a terminal in a website so that the user cannot see the code, makes sense?
cause if not I have to share the code or use repl it to make users run the file and its a bit messy/uncomfortable
how exactly?
It probably is thanks I will test it
How you implement is going to depend on the web dev framework you are using. What framework are you using?
Technically this kind of logic is not really tied to framework
we first think about it at the abstract level of code blocks / pseudo code stuff
frameworks are all kind of same in the end, and they just introduce slightly different implementation details to such business logic stuff
this kind of logic could be not even tied to Programming Language details
it is nice to read Code Complete by McConnel book. he explains the difference about it too
Although it is book more concentrated only on Code Architecture I think so far 🤔 U would need several more books to get all aspects of Software development cycle, perhaps System Analysis and Design book by Alan Dennis should be enough to complete knowledge to a minimal sufficient picture
But all of it would be teaching you about how to develop from the most abstract to implementation details
to make the picture complete you would also need to learn a different stuff how to program best from implementation details / bottom refacrorized to higher level stuff
That would require Unit testing Khorikov -> Test Driven Development By Kent Beck -> and perhaps Refactoring by Martin Fowler?
Ergh. Time to add all extra appeared stuff to my diagram of learning which i drawing for all this stuff
hi,
I have a locally working app with a custom User model, which has a foreign key in it to UserTier model. When I try to run it in my CI/CD, when python manage.py makemigrations goes off, I get:
django.db.utils.OperationalError: no such table: users_usertier
I don't have any migrations in my repo.
It is a very important project for me and I can't seem to find anything helpful.
Anyone knows what could help? 🥺
Are you having messed up Python Packages discovery which you are resolving by adding folders to PYTHONPATH?
anyway, try to make sure you have added app with UserTier to django settings authorized applications
authorized applications you mean just whether I added it to apps?
The easiest way to detect what is wrong with your code, just git clone the repo from zero and try to achieve makemigrations in it
it should help you to identify steps needed to be added to CI CD
I have fully working entire project with AWS and stuff, but on the current local database. If I try to delete database and migrations and get it migrated from 0, i get that error
thats what CI/CD did basically, and the error is on makemigrations exactly
I didn't upload database or migrations folder to git, so it starts from 0
Perhaps you did not clean database completely
you do know that Django also keeps in database performed migrations data?
a special table just about performed migrations?
drop database and create it again, it will ensure better database cleaning (don't forget to backup needed data)
yeye, that's exactly when the error appears
locally it works cause it was built gradually
but when I remove the database and migrations folder
and try to create a new, clean one
I try to run makemigrations and that's what I get:
django.db.utils.OperationalError: no such table: users_usertier
shrugs, not enough info to identify what you do wrong
class UserTier(models.Model):
name = models.CharField(max_length=250)
class UserManager(BaseUserManager):
# casual UserManager from Django Docs
class User(AbstractBaseUser, PermissionsMixin):
username = models.CharField(max_length=30, unique=True)
user_tier = models.ForeignKey(
UserTier, on_delete=models.SET_NULL, null=True, related_name="users"
)
objects = UserManager()
USERNAME_FIELD = "username"
and in settings:
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"rest_framework",
"rest_framework.authtoken",
"dj_rest_auth",
"users",
"images",
]
# Custom user model configuration
AUTH_USER_MODEL = "users.User"
I think that's the only stuff related to custom User Model in my project (besides custom admin panels)
✅ fixed... I was trying to access UserTier objects in my apps.py in on_ready() function
thank you for your time, I appreciate it, you helped me in looking into weird places 🙂
If I'm creating a social network website with Django, would it be a good idea to use Django's built in User model(which makes users show up directly in the admin interface) or should users be added to some different database table?
you should probably just make a new user model that inherits off of the builtin user model. it has alot of properties that you'll likely want to keep track of in your users
just be sure to point django to your new user model using AUTH_USER_MODEL in settings
also keep in mind you can specify any model to show up in the admin panel, not just users
is there a benefit to do that instead of using the builtin user model?
well, the builtin user model probably wouldn't contain all the fields you want to manage in your users.
Ah, yeah
Let's say I have a Django model which has a bunch of countries in it(it has country names, abbreviations, and id's.)
Now let's say I'm creating a user registration form(using UserCreationForm) where I want the users to be able to pick one of the countries from my earlier model to sign up.
How would I go about implementing that?
it would probably have:
country = forms.ChoiceField
but what would the arguments here be?
my country model is this, fyi:
class Country(models.Model):
name = models.TextField(max_length=50)
abbr = models.TextField(max_length=3)
id = models.IntegerField(primary_key=True)
def __str__(self):
return self.name
I found the answer myself. I used:
country = forms.ModelChoiceField(queryset=Country.objects.all())
But if someone else has a better solution please feel free to share!
Got a bit of an issue with Flask, hope someone can clear this up for me.
Im trying to display a webcam feed through openCV on the screen, which worked fine while i was calling the function when it was on index.html .
Now that i've separated the pages with a help of a navbar, i cannot get the webcam to show up.
I have the route set as
@app.route('/webcam')
def get_webcam():
return(render_template('webcam.html', camera=camera))
@app.route('/webcam_display')
def webcam_display():
return Response(generate_frames_webcam(),mimetype='multipart/x-mixed-replace; boundary=frame')
and in the HTML
<div>
<img src="{{ url_for('webcam_display') }}" width="50%"/>
</div>
The navbar is set up as
topbar = Navbar(
View('ANPR', 'index'),
View('Webcam', 'get_webcam'),
View('Oak-D', 'get_oakcam'),
)
nav = Nav()
nav.register_element('top', topbar)
nav.init_app(app)
and then rendered with
<body>
{% extends "bootstrap/base.html" %}
{% block navbar %}
{{nav.top.render()}}
{% endblock %}
<h1>ANPR</h1>
<form method="post" action="{{ url_for('tasks') }}">
<input type="submit" value="Stop/Start Webcam" name="webcam" />
</form>
<div>
<img src="{{ url_for('webcam_display') }}" width="50%"/>
</div>
</body>
in the body.
Seems like navbar might be blocking everything else from showing for some reason, since on the index page i added some h1/h2 tags that do not show up.
Have anyone tried to add file uploads with tus to fastapi? I'd appreciate some examples or at least tips
where would it be possible to fully learn javascript ?
youtube or gg / java
gg / java ??
its a server....
i cant send invite here
i will send in dms
ok...
Not for tus, no. Anyway I figured that it won't make sense as fastapi will have to get the whole file anyway before passing it to tus
I want to get started with web development, what would be a good place to start?
I've heard HTML or CSS being recommended, any good resources to work with those?
mdn has some good (community written) turotials
True, here you will find plenty of resource for HTML/CSS/JS e also Django
I see, thanks a ton
I've tried getting into some HTML before, I always stumble but I guess that is partly because of my lack of patience while approaching it
I think the best approach is to get to see it already working. Try following some tutorials like the Django official tutorial or the DjangoGirls one (I mean, if you're interested in Django for web development)
Django seems like a fine choice, and of course I asked here because I'm interested in web development in relation to using Python, but I was thinking more about Flask
I'm not a Flask guy but it's also a good choice and a very used one. You will be able to find plenty of resources online (blogposts, YouTube, etc)
Is it recommended to use drf with session authentication with a react frontend?
since the documentation says this
https://www.django-rest-framework.org/api-guide/authentication/#sessionauthentication
This authentication scheme uses Django's default session backend for authentication. Session authentication is appropriate for AJAX clients that are running in the same session context as your website.
What about applications not running on the "same session context"
Django, API, REST, Authentication
basically if your django and react are served on the same url
hmm...what if it's not?
is there still a possibility to use session auth?
I have two permission class. IsAuthorGroup will check if the user belongs from the author group and IsOwnerOrReadOnly will restrict the user to performing post and delete if he is not the object's owner.
But the problem is anyone from IsAuthorGroup performing post and delete request event he isn't own of the object.
How to restrict anyone from IsAuthorGroup performing post and delete request if he isn't owner of the object?
here is my code:
def has_permission(self, request, view):
if request.user and request.user.groups.filter(name='AuthorGroup'):
return True
return False
class IsOwnerOrReadOnly(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
if request.method in permissions.SAFE_METHODS:
return True
# Write permissions are only allowed to the owner of the blog.
return obj.author == request.user or request.user.is_superuser
class BlogViewSet(viewsets.ModelViewSet):
queryset = Blog.objects.all()
serializer_class = BlogSerializer
pagination_class = BlogPagination
lookup_field = 'blog_slug'
permission_classes = [IsOwnerOrReadOnly & IsAuthorGroup]```
anyone familiar here with github pages / netlify or heroku
pretty much anything like that?
don't ask to ask, just ask :)
well i just want somewhere to upload my portfolio stuff
if i ever have something that is good enough to show off
so since i cant really spend much money on website hosting service
i was just thinking about if github pages is good enough for stuf like that
yeah github pages is a great place to host portfolios
hi,
when I do an authorization decorator, do I have to call the function inside of it? or it's just enough to return it?
def is_correct_user(func):
"""
Check whether the requesting user is the one who the image belongs to.
"""
@functools.wraps(func)
def wrapper_is_correct_user(request, *args, **kwargs):
img_name = kwargs['img_name']
if request.user.id != int(img_name.split("_")[0]):
return Response({"status": "Forbidden"}, status=status.HTTP_403_FORBIDDEN)
func(request, img_name=img_name, *args, **kwargs) # DO I HAVE TO HAVE THIS?
return func(request, img_name=img_name, *args, **kwargs)
return wrapper_is_correct_user
Hey...
I am a beginner ...I just completed HTML ....
What should I do next ??...plz help
to-do app in django
learn css and then js
jinja2.exceptions.UndefinedError: 'int' is undefined
{% if int(todo[2].replace("-", "")) <= int(date)%}
I can't use the int function? 🤔
hello i have a question
i am trying to do this
to make a model form
but the form ends up having a drop down of foreign keys
i just want it to log the currenlty logged in user
with modelform data which is being saved
Currently the sendBtn button and the username input box are not center aligned with the message text area, how would I do this? Thank you in advance.
Hi,
I know I can access user profiles by using their ids if I use int:user_id in my urls file. But how can I access user profiles using the profile names? I tried <user_username> but that didn't work
Question for Django ^
you need to specify the type. try <str:username>
I fixed it, I used slug:username
yeah slug works as well
class Country(models.Model):
name = models.TextField(max_length=50)
abbr = models.TextField(max_length=3)
id = models.IntegerField(primary_key=True)
def __str__(self):
return self.name
class User(AbstractUser):
country = models.ForeignKey(Country, on_delete=models.CASCADE, default='default')
def __str__(self):
return self.username
When I run migrations on this, I get the following error:
ValueError: Field 'id' expected a number but got 'default'.
any ideas on a fix?
Try removing default='default'
I know this is broad but is there any suggestions for fixes when I get key errors on production but not in development?
Catch it in exception maybe?
It really depends on how you want to handle errors. You could have it stop the script entirely or just return a default or just return some sort of error message somehow or log it
hmm could try that
Yeah I've got it logging from website into a discord channel but again that just throws key errors. I'll have a further look this morning though and try some exception catching
Managed to narrow it down to an API call that is throwing a key error in production but not in dev fyi
can someone help me with this error please => AttributeError: 'Request' object has no attribute 'occupier' my code => ``` class OccupierLoginView(APIView):
def get(self,request,format=None):
if request.occupier.is_authenticated == False or request.occupier.is_active == False:
return Response('Invalid credentials', status=403)
occupier = OccupierSerializer(request.occupier)
return Response(occupier.data, status=200)
def post(self,request,format=None):
print('Login Class')
occupier_obj = Occupier.objects.filter(email=request.data['username']).first() or Occupier.objects.filter(username=request.data['username']).first()
if occupier_obj is not None:
credentials = {
'username': occupier_obj.username,
'password': request.data['password']
}
occupier = authenticate(**credentials)
if occupier and occupier.is_active:
occupier_serializer = OccupierSerializer(occupier)
return Response(occupier_serializer.data, status=200)
return Response("Invalid credentials", status=403) ```
hello, I am pretty new to coding but am good at python skill wise. I want to make a program that automatically lists an item from Gumtree to Facebook Marketplace - would this be possible and will it be hard? I have no experience making large web projects liek these. Only puzzles.
I am stuck at something in my flask app. The details are in #help-ramen, please help me if you can
is it possible to wirte if condition inside {{ }} in jinja ??
You can probably do it be chaining cond | reject | map | default
Does the python way not work, x if y else z
Let me see the form.py
it worked man, thanks
can someone help me with this error please => AttributeError: 'Request' object has no attribute 'occupier' my code => ```from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from .serializers import OccupierSerializer
from .models import Occupier
from django.contrib.auth import authenticate
Create your views here.
class OccupierView(APIView):
def post(self, request,format=None):
print('creating occupier')
occupier_data = request.data
print(request.data)
occupier_serializer = OccupierSerializer(data=occupier_data)
if occupier_serializer.is_valid(raise_exception=False):
occupier_serializer.save()
return Response({'occupier':occupier_serializer.data}, status=200)
return Response({"msg:ERR"}, status=400)
class OccupierLoginView(APIView):
def get(self,request,format=None):
if request.occupier.is_authenticated == False or request.occupier.is_active == False:
return Response('Invalid credentials', status=403)
occupier = OccupierSerializer(request.occupier)
return Response(occupier.data, status=200)
def post(self,request,format=None):
print('Login Class')
occupier_obj = Occupier.objects.filter(email=request.data['username']).first() or Occupier.objects.filter(username=request.data['username']).first()
if occupier_obj is not None:
credentials = {
'username': occupier_obj.username,
'password': request.data['password']
}
occupier = authenticate(**credentials)
if occupier and occupier.is_active:
occupier_serializer = OccupierSerializer(occupier)
return Response(occupier_serializer.data, status=200)
return Response("Invalid credentials", status=403)````
Ok, I changed it to:
class User(AbstractUser):
country = models.ForeignKey(Country, on_delete=models.CASCADE)
But I still get this error when I try to migrate:
ValueError: Field 'id' expected a number but got 'default'.
ok you want the author field to only contain the logged in user, right ?
how to show this image on my web page? src is changes so i cant just copy it
It changes because you're not supposed to steal someone else's hosting. Put it on imgur or something
Or whatever server is hosting your html
when i open url https://manga.site/title/v8/c47?page=11 there is that image, but on https://manga.site/title/v8/c47?page=12 there is another
i want on my web page button that loads these image from that place
If manga.site isn't your page, then forget it.
those images are their assets, not yours
Can someone please try to help me here.
Yes
Hi ! Can i have some assistance with flask?
So basicaly i have two buttons, when clicked, both call backend functions
So when i click the first button, a backend function is called and stores its data in a global variable
When the second button is pressed, it calls a function that uses the global variable, but this doesnt work because the two functions must be called at the same time.
How can i fix this ?