#web-development
2 messages · Page 210 of 1
what should i do after htmland css for web development
fastapi is working with pydantic very closely, I recommend using it when working with fastapi
when I get redirected from callback the token should appear?
I changed the value of a token to None
async def show_token(
request: Request,
token: str = None
):
just to test the code
change it to the original value - idk what it was
cool, have a good one 🙂
.bm Nice module to work with fastAPI
@uneven plume, please enable your DMs to receive the bookmark.
yeah, Pydantic is awesome
.bm Nice module to work with fastAPI
FastAPI uses pydantic internally afaik
Oh ya, just wasn't 100% sure
Yep, just checked, it requires starlette and pydantic
It uses pydantic for schema generation and data validation
hello, I am unable to login to django admin panel using custom user model that I created
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.contrib.auth.hashers import make_password
from phonenumber_field.modelfields import PhoneNumberField
class UserAccountManager(BaseUserManager):
def create_user(self, email, username, first_name, last_name, phone, password=None):
if not email:
return ValueError("User must have an email address!")
if not username:
return ValueError("User must have a username!")
if not first_name:
return ValueError("User must have a first name!")
if not last_name:
return ValueError("User must have a last name!")
if not phone:
return ValueError("User must have a phone number!")
user = self.model(
email=self.normalize_email(email),
username=username,
first_name=first_name,
last_name=last_name,
phone=phone,
)
hashed_password = make_password(password)
user.set_password(hashed_password)
user.save(using=self._db)
return user
def create_superuser(self, email, username, first_name, last_name, phone, password):
user = self.create_user(
email=self.normalize_email(email),
username=username,
first_name=first_name,
last_name=last_name,
phone=phone,
password=password,
)
user.is_admin = True
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
class UserAccount(AbstractUser):
username = models.CharField(null=False, blank=False, max_length=30, unique=True)
first_name = models.CharField(null=False, blank=False, max_length=50)
last_name = models.CharField(null=False, blank=False, max_length=50)
email = models.EmailField(null=False, blank=False, unique=True)
date_joined = models.DateTimeField(auto_now_add=True)
last_login = models.DateTimeField(auto_now=True)
phone = PhoneNumberField(unique=True, null=False, blank=False, max_length=13)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
USERNAME_FIELD = "username"
REQUIRED_FIELDS = ['first_name', 'last_name', 'email', 'phone']
objects = UserAccountManager()
def __str__(self):
return str(self.username)
def has_perm(self, perm, obj=None):
"Does the user have a specific permission?"
# Simplest possible answer: Yes, always
return True
def has_module_perms(self, app_label):
"Does the user have permissions to view the app `app_label`?"
# Simplest possible answer: Yes, always
return True
so which result on google are you not too sure about?
How can I debug mod_wsgi? I think I have it configured correctly, but my Flask app keeps giving 404
The apache error.log file says "file does not exist" for me, and gives /var/www/html/myapp which makes me figure that mod_wsgi isn't mapping the requested URL to my app.
But I can't se anything wrong in my WSGI configuration.
Hi guys, I'm trying to deploy a website using Heroku. Heroku is connected to github and any pushes I make to github will update the website. I am a bit confused how to make my environmental variables private?
These are the variables that I get using os.getenv()
and make private on my own computer
don't share your computer and they become private.
Though you shouldn't be using prod instances locally.
i see but i guess I don't quite understand how the website can use them if I'm not hosting the website on my computer but on the cloud
using heroku
you would configure them using the heroku command or via the web interface
Ive noticed the PokeAPI serializes their response to make it easier to read, how can I learn to do that? Is that a result of how they query their database or is it down through your own code?
generally you dont want to pretty print the responses themselves
most browsers and api clients for testing will pretty print it automatically
I guess so. Ive been trying to find out what it is referred to as and "serialize" was the closest I could find
but also the user's responsibility to pretty print if they want.
otherwise you're just gonna be needlessly increasing the response size
I dont think thats what I meant actually. https://pokeapi.co/ In this example, their API returns a lot of data on ditto, but its further grouped by abilities, game indices, held_items, etc
You can return related entities if you're talking about that
in
def create_superuser(self, email, username, first_name, last_name, phone, password):
user = self.create_user(
email=self.normalize_email(email),
username=username,
first_name=first_name,
last_name=last_name,
phone=phone,
password=password,
)
user.is_admin = True
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
do this
def create_superuser(self, email, username, first_name, last_name, phone, password):
user = self.create_user(
email=self.normalize_email(email),
username=username,
first_name=first_name,
last_name=last_name,
phone=phone,
password=password,
)
user.admin = True
user.taff = True
user.superuser = True
user.save(using=self._db)
return user
how can I post code in the chat?
Have anyone ever tried to access external APIs from django migration file? And did it work as well?
Ill just share a link so I dont flood the chat. https://codeshare.io/LwZM37 currently, the response from the API i'm creating is the top example, but I would like to make it look like the bottom example. How can I learn to do this?
Migrations shouldn't depend on an external api, it's pretty bad idea
What if api changes? What if it's unavailable?
Migrations should run and rollback regardless
yes that's right
anyone has done token authentication in drf with mandatory email confirmation + password rest etc?
I have flask app and I have setted up nginx with it
When I use ip in my browser uri I get my website but when I use domain I dont get my website what is issue?
server {
listen 80;
server_name scrupa.com www.scrupa.com;
location / {
include proxy_params;
proxy_pass http://unix:/home/dhairya/PD2/myproject.sock;
}
}
this is my configuration
Serialize means to put in a stream in memory or a file.. the contents of an object or data type.. serialized content tend to be read in sequence from start to end like a file stream
It has a pointer typically to the current node or location in the stream
Nowadays we serialize to JSON too
Much more typical in a Web context although XML, CSV, TSV, Word, Excel i have seen too in prod web code
You can write your own serializer methods or classes to formats if you need to but you need an in depth knowledge of the formats to ensure it works.
Have you set up the domain with your provider?
I am having a problem with django
It says module <app>. Urls not found
can anyone help me?
how should I put this in the middle and be responsive?
<section id="panels">
<a href="{{ url_for('intro') }}" class="panel">
<h2>Introduction</h2>
<p>New to hata? Here we have introduction about hata!</p>
</a>
<a href="{{ url_for('topic') }}" class="panel">
<h2>Topic</h2>
<p>Don't have any idea? Take a peek here and see topics</p>
</a>
<a href="{{ url_for('ref') }}" class="panel">
<h2>References</h2>
<p>Need references? Jump right in to see other references!</p>
</a>
<a href="{{ url_for('meta') }}" class="panel">
<h2>Meta</h2>
<p>Want to know more about project? Lez Go!</p>
</a>
</section>```
/* PANELS */
#panels {
align-items: center;
}
#panels .panel {
background-color: lightgrey;
border-radius:6.9px;
box-sizing: border-box;
color: black;
display: inline-block;
margin: 6.9px;
padding: 20px;
text-align: center;
text-decoration: none;
width: 269px;
}```
I’m pretty sure that you’d need to make #panels a flex container in order to use align-items
#panels
Maybe just add margin: auto; to the #panels element and remove the display: flex and align-items: center
welp it came back to the original state
this
is this the right channel to ask about aiohttp? or is there a better one
maybe #async-and-concurrency ? But it's not really a question about async and concurrency, it's about the library itself
Maybe add display: grid; and align-content: center; to #panels and remove the margin
Bruh
What is #panels parent?
nothing
So.. the body tag?
but add the few lines I added above
Maybe add width: fit-content; and margin: auto; to #panels and remove the existing css declarations there
I have that on plus display: grid; now it's in the center
pog
Remove the display grid and align-content center
-_- bruh
Maybe add
display: grid;
grid-template-columns: auto auto;
align-content: center;
You’d need to change the size of the content
Wait
was there horizontal scrolling
no?
What I meant is that did you zoom out and take the screenshot
Nope
Maybe you need to set the navbar width to 100vw
Navbar? 
Hey guys, can anyone tell me how do I return two variables using HTTPResponse in Django? The below is working:
return HttpResponse("Secret Key: %s" %secret_key)
But, this is not working:
return HttpResponse("Secret Key: %s" %secret_key, "ABC: %s" %sc)
In that case you’d need to change the size of the content in some way

yes i m so sorry i accidentally put my query on this channel
@trim isle dm
I did
guys, im trying to set up a phpmyadmin on debian , the page loads, but is blank
the sourcecode is there, but it simply doesnt display anything
Re-posting here because the main help channel is very busy:
I want to parse "normal" text to HTML, which library or approach can I use? Basically I have just text delimited by line breaks and I want to surround every paragraph with HTML <p></p> tags. Only paragraphs, no headings or other data
When I try to run the finished product I made from this tutorial "Python Website Full Tutorial - Flask, Authentication, Databases & More"
I get a blank homepage, I only see the upper menu.
Any help figuring out why I see the notes(home) page empty?
Insufficient information
{% extends "base.html" %} {% block title %}Home{% endblock %} {% block content %}
<h1 align="center">Notes</h1>
<ul class="list-group list-group-flush" id="notes">
{% for note in user.notes %}
<li class="list-group-item">
{{ note.data }}
<button type="button" class="close" onClick="deleteNote({ note,id })">
<span aria-hidden="true">×</span>
</button>
</li>
{% endfor %}
</ul>
<form method="POST">
<textarea name="note" id="note" class="form-control"></textarea>
<br />
<div align="center">
<button type="submit" class="btn btn-primary">Add Note</button>
</div>
</form>
{% endblock %}```
this is the code itself for the home page in HTML, which shows up blank.
I would recommend https://hetzner.cloud/ , quite nice prices, quality and easy to use for beginners
Is there any free ones?
I don't remember there free ones 🤔
if u wish free ones... there are options too
i need a free one
Digital Ocean, Vultr, Linode, AWS, Google, Azure
all provide free servers during first try-period time
all for different time limits though
Digital Ocean 100$ for 60 days
Google 300$ for 3 months / + some servers for 6+ months
won't it require a cc?
#help-candy I sent everything there
yes it will
it will cost nothing
i don't have a cc
some providers accept PayPal
Anything else except heroku?
For free and without security check by cc... I don't know.
raise your own server then 😉
as long as u can have public IP from your ISP
oh
Thanks, I'll check it out
Yes you can, check the link
can u help me?
watch the vid, if you need a more advanced system use django. So much free and simple information online.
I am testing a simple python socket server where i need to pass files content to the client, and the client can request a file by entering it in the url such as : localhost:8080/nicefile.txt and then i would send that file to them so they can view it in the browser. However how can i parse the url (localhost:8080/nicefile.txt) that they entered so i know which file to send?
my advise is use a HTTP server and framework like Gunicorn + Flask
doing it with your own raw socket server is a bad idea
umm.....what?
id have to use raw socket programming
a client can go onto the localhost server and enter a file such a nicefile.txt in the parameters then i would like to know how to retrieve/print the filename they entered
its for my own knowledge learning curve...
alr, well for starters forget about serving the file
first step is writing the HTTP server itself
host = ''
port = 8080
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((host, port))
sock.listen(5)
while True:
csock, caddr = sock.accept()
print("Connection from: " + str(caddr))
req = csock.recv(1024)
csock.close()
This simple web server, how would i get the incoming data such as the parameters?
web socket then
you'll need to implement the following for it to be a web server and compatible with browsers
- Flow control
- HTTP/1 Spec parsing
- Body streaming and request parsing / feedback
websockets are completely different and are even more ontop of the HTTP spec.
https://github.com/python-hyper/h11 is probably your friend for the HTTP parsing
Uvicorn implements -probably the simplest to understand handling of H11 https://github.com/encode/uvicorn/blob/master/uvicorn/protocols/http/h11_impl.py
I think ur overcomplicating this
you want to serve a file to the browser right?
I must implement a web server that is capable of serving files from a lo- cal folder. This means that you are only required to implement the HTTP GET method, but you may want to implement the HEAD method as well, as it may be useful for testing. The server should be able to run indefinately, by which it is meant that it should not just process a given number of response and then stop.
The server should work as a plain file server and should accept a path to a folder and a port number. The server may also take an address to listen on, but if this is not implemented, the server should listen on all addresses on the port specified. Files and folders in specified path should be served up by the webserver. If a folder on the server is accessed (with a URL ending in a /) then you should serve up the contents of file named index.html, if one exists, or a listing of the files and folders, if index.html does not exist.
h11 is your friend
i cant use other libraries or external modules but your saying i should look at the code of h11?
you could do an incredibly basic / incorrect web server by just hard coding values and making some broad assumptions about the data you're receiving
i think thats fine
which, yes, is a bit more simple just reading like 1KB and just hoping it contains everything
however if it's gotta to actually be a correct web server then you're looking at a few thousand LOC
1st of all i am 11 years old 2nd i am new to python
if starting with Django what is the best doc without the default one?
Is it a problem to have different ajax requests in the same script file?
The code is code (At least in programming languages with standard logic). Separation to different files is purely for your own code organizations. So answer, no, there should be no problems from that.
ok cool. I've got two different ajax calls that should execute on different button clicks but I'm having a problem handling them in flask. Both calls post to the same route and I thought I could handle it by doing this
def process():
if request.method == 'POST' and request.form['call1']:
do something
if request.method == 'POST' and request.form['call2']:
do something```
But I'm getting a bad key error 'call1' when I click the button that should post call 2
btw u have wrong indentation
secondly, checking in python key existence by boollean request.form['call1'] should be not correct
ah should be something like 'call2' in request.form right?
def process():
if request.method == 'POST' and 'call1' in request.form:
do something
if request.method == 'POST' and 'call2' in request.form:
do something
yes
request.form['call1'] will just raise an KeyError i think, if call1 is not existing
request.form.get("call1") can extract without raising errors (it should return "" if not existing)
request.form.get("call1", Your_default_value) or you can point explicitely what whouls be returned if not found
Ok will give that a try
Hey guys, Im making an app which takes input from user's camera. So I am using opencv and face recognition. The app is working fine, the problem lies with deployment. Does anybody have any idea regarding deploying opencv camera based applications?? If so, pls do help
I am using a Flask based web server to capture the user's image from a live video stream form the user's camera. I need help in connecting with the user's camera. Locally I would have used cv2.VideoCapture(0), but this is not the case when it's deployed, so can anybody help with this and to deploy it.
use rtsp, if it's an ipcamera
import jwt
from django.db import models
from datetime import datetime, timedelta
from django.conf import settings
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
from cores.models import TimestampedModel
class UserManager(BaseUserManager):
def create_user(self, username, email, password):
if not username:
raise TypeError('User must have a username.')
if not email:
raise TypeError('Users must have an email address.')
user = self.model(username,
email=self.normalize_email(email))
user.set_password(password)
user.save
return user
def create_superuser(self, username, email, password=None):
if password is None:
raise TypeError('Superusers must have a password.')
user = self.create_user(username, email, password)
user.is_superuser = True
user.is_staff = True
user.save()
return user
class User(AbstractBaseUser, PermissionsMixin, TimestampedModel):
username = models.CharField(db_index=True, max_length=255, unique=True)
email = models.EmailField(db_index=True, unique=True)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
# The `USERNAME_FIELD` property tells us which field we will use to log in.
# In this case we want it to be the email field.
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
# Tells Django that the UserManager class defined above should manage
# objects of this type.
objects = UserManager()
def __str__(self):
"""
Returns a string representation of this `User`.
This string is used when a `User` is printed in the console.
"""
return self.email
please guys i need help the create_user and create_superuser returns: TypeError: create_user() missing 2 required positional arguments: 'email'
class Product(models.Model):
name = models.CharField(max_length=1024)
count = models.IntegerField(default=1)
def __str__(self):
return self.name
Do you know, why terminal doesn't return a object without name istead name of the object? Help, guys
object has included name in its attributes.
Hey, does someone know a python library for web push notifications? Creating the vapid keys (private & public) & sending the notification to a browser using the keys? Tag me if you know
Yes
okay, I try it
>>> str(Product.objects.get(id=1))
'Product object (1)'
I wanted to get this form:
>>> str(Product.objects.get(id=1))
<Product: python_keychain>
I l think you should use str in your model
Hey, I am wondering, how to add python plotly to website
I used __str__ in my model
@real edge
Hey guys!!
I'm looking for some REST API challenge to study!!
Like building some CRUD API...
Does anyone know some?
I dont understand what you want to return, if you want your "name" , wrapping in str should work
Does anyone know if django's loaddata command wipes the database before loading the fixtures?
I did a run just a while ago and I noticed that my data on AWS RDS is already gone. The command is still loading the fixtures though I can't see anything from my app's models in the database except the built in stuff
How do I get access to user's webcam?
how can we pass multiple images from React axios and Django rest framework
Hello how do I turn this public key to PEM format?
{'kty': 'RSA', 'e': 'AQAB', 'kid': 'e49b9f971574455ba969b20697a2c7b6', 'alg': 'RS256', 'n': 'rEFxuU7IZiiKzyjVQ9U3yW594Hll-jjuWK-vYZBC9JZ4FmWMSsG3auvkpieUjrkMKKEP5YSLbhOOzjcRPRxSEcDfJl7jSD6mvWN05wokYFxUc9RT2p4kOkXPq26Wio4ksVJhFp1dkuJRyPIBW3xT2ipqnDmzUPzC4nKEwZC6vRz0sU4I7fFKLqGf4fmvi2nmJile-ctfcN8GV2Cam84WAgiIg7LrzYFQMeIj0fAmeBUXO4TAddsF6l6_JJu3uDXnzrDYJL9bEZiTk3Anf4SVeTle-hLDeAkTGbHI0Juqf1SEegGMRQ0mM0xcZe7Hmn3CFul3ahfEvGAYyny2tzHNUw'}
so i can do this:
jwt.decode(token, audience="secret-client-id", algorithms=['RS256'], key=key)
Hello, why am I getting these errors in my Chrome console? Everything works fine but was just wondering what it could be. Thanks!
Hey, does someone know a python library for web push notifications? Creating the vapid keys (private & public) & sending the notification to a browser using the keys? Tag me if you know
Hello, how to configure config variables in heroku for django? (postgresql database variables)
You can add or edit config vars from your heroku app settings
it will automatically figure it out?
yes
thanks !
you can use pywebpush
https://github.com/web-push-libs/pywebpush
https://github.com/Ayman-Isam/Class-of-2024-Blog/tree/main/blog
I'm getting an error of AttributeError: type object 'PostCommentDeleteView' has no attribute 'as_view'
where is your PostCommentDeleteView class located?
Sorry I forgot to push my code
class PostCommentDeleteView():
model = Comment
fields = ['content']
template_name = 'blog/post-detail.html'
def test_func(self):
post = self.get_object()
if self.request.user == post.author:
return True
return False
def get_success_url(self):
return reverse_lazy('post-detail',kwargs={'pk':self.kwargs['pk']})
you must inherit one of generic view class from django views
Great👍
django.db.utils.IntegrityError: The row in table 'blog_comment' with primary key '15' has an invalid foreign key: blog_comment.author_id contains a value 'Ayman' that does not have a corresponding value in auth_user.id.
I'm also getting this error
@odd belfry
I get this error while I'm trying to migrate
class Comment(models.Model):
post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE)
author = models.ForeignKey(User,on_delete=models.CASCADE)
content = models.TextField()
date_added = models.DateField(auto_now_add=True)```
which column you are altering?
the author, it was set to this py author = models.CharField(max_length=32,default='Unknown')
you are changing char field to foreign key field, right?
yeah
there are several ways
before migrate, need to replace author name with author.id with update query
if author_id not found with current author name, then need to set a valid user id (cause your filed is non nullable)
yes
Cannot assign "'Ayman'": "Comment.author" must be a "User" instance.
I'm getting this error now
hi everyone. I tried to build a flask simple website but it gave me a 404 so I tried on another website I created which was working and it gave me a 404 for all of my websites which are working!
please help me
Share code
which one?
Script that is giving 404
this is a test I did that didn't work also
all of them are not working
anymore
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
app.run(debug=True)
Try this
Can I automate a website updating based on a hit repo commits?
it didn't work
fastapi.exceptions.FastAPIError: Invalid args for response field! Hint: check that <class 'main.SoluteSolvent'> is a valid pydantic field type getting this error while executing the fastapi code
Share debug logs
?
I was trying to replicate this flask code in fastapi
The terminal text
You are using pycharm?
vsc
I think you are not running the script properly.
Ctrl + s to save file
Run the file through terminal
python filename
And make sure url is using '/' route on browser
Visit that url and share browser screenshot with url.
it removes the / when I press enter
Route is fine. Code is fine.
Where is the debug status?
It prints 404 in terminal?
After visiting browser
You can close and restart the server
the number of times I did that is infinite
Why does it make it so when the window resizes it moves with it but when I scroll down in the page the background stops? And there is a white part there?
body {
background-image: url(../img2/Picture1.png);
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
background-repeat: no-repeat;
width: 100%;
position: absolute;
top: 0;
left: 0;
}```
Hello
Is it possible to build an array in a for loop and use it in another loop?
Currently it's being duplicated
In PHP I would normally assign it to a key(based on the index) and display that
Array1 = []
For I in range(0,5):
Array1.append(I)
For j in Array1:
Print(j)
Create empty list before for loop and append that list in for loop.
try to change your port
if name == 'main':
app.run(debug=True, port=1234)
try that
it's working
but it is openning a different website in a different repsoitry which is closed
Why am I getting this error
Views.py
class PostCommentCreateView(LoginRequiredMixin, CreateView):
model = Comment
fields = ['content']
template_name = 'blog/comment_form.html'
def form_valid(self, form):
form.instance.post_id = self.kwargs['pk']
form.instance.author = self.request.user
return super().form_valid(form)
def get_success_url(self):
return reverse_lazy('post-detail',kwargs={'pk':self.kwargs['pk']})
class PostCommentUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
model = Comment
fields = ['content']
template_name = 'blog/comment_form.html'
def form_valid(self, form):
form.instance.post_id = self.kwargs['pk']
form.instance.author = self.request.user
return super().form_valid(form)
def get_success_url(self):
return reverse_lazy('post-detail',kwargs={'pk':self.kwargs['pk']})
def test_func(self):
post = self.get_object()
if self.request.user == post.author:
return True
return False
class PostCommentDeleteView(DeleteView):
model = Comment
fields = ['content']
template_name = 'blog/comment_confirm_delete.html'
def test_func(self):
post = self.get_object()
if self.request.user == post.author:
return True
return False
def get_success_url(self):
return reverse_lazy('post-detail',kwargs={'pk':self.kwargs['pk']})
Urls.py
path('post/<int:pk>/comment/', PostCommentCreateView.as_view(), name='post-comment'),
path('post/<int:pk>/comment-update/', PostCommentUpdateView.as_view(), name='post-comment-update'),
path('post/<int:pk>/comment-delete/', PostCommentDeleteView.as_view(), name='post-comment-delete'),
Models.py
class Comment(models.Model):
post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE)
author = models.ForeignKey(User, on_delete=models.CASCADE)
content = models.TextField()
date_added = models.DateField(auto_now_add=True)
def __str__(self):
return '%s - %s' % (self.post.title, self.author)
You don't have a Comment with a pk of 4 in your database
It matches the expected URL but the query to fetch the comment is returning nothing
In which model
i say this to Ophir
Oh sorry
But It should be a post with pk of 4 and a comment on that post and that comment needs to be updated
Bruh I just realized I'm using post.id instead of comment.id
UpdateView by default looks for the path parameter called pk. Since you are telling it that the model for PostCommentUpdateView is Comment it is looking for a Comment with pk=4
path('post/<int:post_pk>/comment-update/<int:pk>/', PostCommentUpdateView.as_view(), name='post-comment-update'),
class PostCommentUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
model = Comment
fields = ['content']
template_name = 'blog/comment_form.html'
def form_valid(self, form):
form.instance.post_id = self.kwargs['pk']
form.instance.author = self.request.user
return super().form_valid(form)
def get_object(self, *args, **kwargs):
return get_object_or_404(self.model, pk=self.kwargs['pk'], post=self.kwargs['post_pk'])
def get_success_url(self):
return reverse_lazy('post-detail',kwargs={'pk':self.kwargs['pk']})
def test_func(self):
post = self.get_object()
if self.request.user == post.author:
return True
return False
No I fixed the issue, I was using post.id instead of comment.id on buttons
Wait it's not working again
@upbeat ruin you can write to a file maybe?
Hi, Im making web scraper and i have problem with UL and LI, when i try to scrape them i get only this ```
</ul>
<ul class="connectedState" id="state1">
</ul>
but in google its filled with <li>? anyone know why?
I was wondering how I could create a html button that executes a python flask file in my directory, or if that's even possible.
I'm looking to switch between databases depending on how I run Django. For example, it's a huge pain to get mssql server up and running for github actions ci/cd, so I want to use sqlite3 for that portion, but I want to stick with mssql server when I run python manage.py runserver. How do I create this split?
Using sqlalchemy?
You can conditionally set an environment variable containing a database url
I.e. dialect://user:pass@host:port/db
!pypi dj-database-url
<@&831776746206265384> here too
Thank you. this is exactly what I needed!
Oh one question though, it looks as though I should be able to specify which database to run? because the way settings.py DATABASES is written
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'mydatabase',
}
}
Can't I just add the ability to set the DB by adding an argument like python manage.py test --use-db default? somehow? this is probably way more complex but might use less dependencies.. or maybe I have no idea what I am saying
Don't see why not
The documentation simply says that "its possible to specify more" https://docs.djangoproject.com/en/4.0/ref/settings/
Set a value when runserver is used
Do you mean like
if sys.argv[1] == 'runserver':
DATABASES = { 'db2': {...} }
ah I dont think I can do that since it will tell me that default is required or something
doesn't test create an entirely different database to test on?
I'm not sure this is necessary
it is common to use many settings files, one for each environment you might need like settings_local.py, settings_dev.py, settings_prod.py. You can define different DATABASES in each. Maybe that's what you want?
so I thought this was the case too, but when I test using sqlite3 it seems okay, but when I test with mssql configured it throws an error saying pk=1 doesnt exist, but that shouldnt be possible if its a new db being created
this seems to describe how new databases are created when testing
Upon doing a little bit of debugging, print(Snippet.objects.all()) within my test returns a queryset with pks not starting at 1
Thanks I'll give that a read and see if it gives me hints
do you have many tests which set up and create snippets?
you have a set_up method in your test class I believe that gets run once per test
so you could be creating and deleting many snippets
I have two tests, and yeah indeed I have a setup that only initializes an object and creates two snippets
but in my first test case I am not creating further snippets, only this:
snippet1 = Snippet.objects.get(pk=1)
snippet2 = Snippet.objects.get(pk=2)
it may be illuminating to print something out during your setup
to see if it is running multiple times
Good idea, I'll try that
You're a genius, that was the easiest debugging trick ever
I found out that this whole test thing is being called twice, which generates two sets of snippets
The problem is this! Well, not a problem, but I didnt realize that the data is not destroyed at the end of each test, so I am making snippet instances per test
yeah, I had a feeling!
is the solution to have a init(self): constructor that establishes my objects?
is it important these primary keys be 1 and 2?
it seems weird to test on that
using set_up should be good
Not exactly, I'm new to testing though so I have no idea what I'm supposed to test 😉
My first instinct was to test to make sure models actually get made and they can be accessed
Second instinct was to test that saving them to the db is possible at all
It seems like you are trying to test things which django already tests for thoroughly
you need to test the things you have written
not django's code
fair enough, I suppose yeah django does check that I wrote my models and serializers correctly
if you had a custom save method which updates a modified_at field or something, you could create a model and check that the modified_at field changes after re-saving
if you really want to check that objects are being saved you can check the Snippet.objects.count() before. Then save x new snippets and check that the new count is x more than it was originally
Ah yes that was my intention, but I wrote spaghetti instead
but from what you said, I suppose I should just trust that methods do what I expect them to do if I didnt write them
so maybe checking objects being created and saved is redundant
Ok great, thanks a lot. I learned so much just now
🙂
how do I make it use the pk of the post and not of the comment in success url
you changed the url like i posted before?
you could just use self.kwargs['post_pk']
Another Django question, but when I run python manage.py runserver, I think the code inside of it gets executed twice. Is this normal? For example if I put a print statement print("print statement inside settings.py") in there, I get this in my console
$ python manage.py runserver
print statement inside settings.py
print statement inside settings.py
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
Aha, found the solution. For those wondering, Django does indeed read settings.py twice! This is because Django wraps settings.py and does things at a lower level with it, so print statements will appear twice.
It is not a bug though apparently!
More reading revealed to me that
Django uses two process for the reloading feature (ie. restart on code change), if you run ./manage.py runserver --noreload you get only one process.
Sorry for answering my own question. I figure this will help those who try to use search in discord
Yeah, but I forgot to do post_pk and just did pk
But then I get errors and my urls in my post_detail file are not working
when i feed this as input in fastapi CC(C)(C)Br in get request url the ( is converting into % some number how to stop this
inputs
Hey I need to customise the login function in django, what should I do to get it done. I have used a custom authentication backend for this and I'm getting the user from it but when I pass that user to the login() it won't create session for the user. What should I do now?
its being urlencoded, why would you want to stop it?
I have been trying social media authentication in django, so I used python soical auth and was successfully able to log users in, I am trying to get profile photo of the logged in user, and save it in my backend. I don't know how to do it ,can some one pls share.
have them upload images, then store them somewhere?
Okay

When I try to update a comment I get this
Views.py
class PostCommentUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
model = Comment
fields = ['content']
template_name = 'blog/comment_form.html'
def form_valid(self, form):
form.instance.post_id = self.kwargs['pk']
form.instance.author = self.request.user
return super().form_valid(form)
def get_success_url(self):
return reverse_lazy('post-detail',kwargs={'pk':self.kwargs['post_pk']})
def test_func(self):
post = self.get_object()
if self.request.user == post.author:
return True
return False
class PostCommentDeleteView(DeleteView):
model = Comment
fields = ['content']
template_name = 'blog/comment_confirm_delete.html'
def test_func(self):
post = self.get_object()
if self.request.user == post.author:
return True
return False
def get_success_url(self):
return reverse_lazy('post-detail',kwargs={'pk':self.kwargs['post_pk']})
Models.py
class Comment(models.Model):
post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE)
author = models.ForeignKey(User, on_delete=models.CASCADE)
content = models.TextField()
date_added = models.DateField(auto_now_add=True)
def __str__(self):
return '%s - %s' % (self.post.title, self.author)
Urls.py
path('post/<int:post_pk>/comment/', PostCommentCreateView.as_view(), name='post-comment'),
path('post/<int:post_pk>/comment-update/<int:pk>/', PostCommentUpdateView.as_view(), name='post-comment-update'),
path('post/<int:post_pk>/comment-delete/<int:pk>/', PostCommentDeleteView.as_view(), name='post-comment-delete'),```
Post_detail.html
<div>
<a class="btn btn-secondary btn-xs mt-1 mb-1" href="{% url 'post-comment-update' post.id comment.id %}">Update</a>
<a class="btn btn-danger btn-xs mt-1 mb-1" href="{% url 'post-comment-delete' post.id comment.id %}">Delete</a>
</div>
How to serialize a response containing nested list, inner list are list of objects.
something like this, [[obj 1, obj 2, obj 3], [obj 4, obj 5, obj 6]]
I'm able to serialize, [obj 1, obj 2, obj 3] by passing many=True in schema object for the model, but in the previous response the same schema is returning empty responses.
see the logs, it's printing correctly but when returning the list getting empty response in the list
I think it's because the paragraph is not loaded before the script tag, because it's after the script tag
oh so the script should be inside body?
yeah
or just make a .js file
Usually, scripts are put at the end of the body tag
yeah and?
and add the <script tag on the end of body tag
But, yeah, a file is good too
with src='yourfile.js'
yeah
<script src="yourfile.js"></script>
anyone can help me with this?
It's something with the sessions and session tokens idk
!rule 5?
The rules and guidelines that apply to this community can be found on our rules page. We expect all members of the community to have read and understood these.
Yep. I couldn't see an explicit API section and most companies won't allow scraping by default
even after the script is at the end of body tag, the button continues not to work :(
you have to add the id='demo' to the button
change your function name to something else, for example "onClick"
No, HTML IDs are unique between all HTML elements
What if you put the script tag between the paragraph element and the button element?
No heres the problem what i found
the script inside onclick should be put in double quotes
like onclick = "script"
and i used java script double quotes aswell
so like if i used single quotes there wouldnt be a problem
Please see the rules, looking for paid work is not allowed on this server
how to build the encryption flow? https://imgur.com/a/Yms99YV
Hello folks,
I'm trying to register a blue print in flask that will handle custom exceptions,
when I do app.register_blueprint(config_error_handler_bp), the exceptions isn't caught
why is that ?
but if the blueprint that's raising the exception is the one that's decorated with the error_handler decorator, it does catch it
im making a web application in angular that will need a REST API and websockets (for messages) and authentication, and have trouble deciding my back end framework, it's between flask and django
I've used neither (only spring / spring boot, asp.net / .net), i do have experience in python tho
I've done some research on the frameworks and know that flask is more barebones and django includes a lot more functionality, but I'm not quite sure if django would be overkill for my needs or not
Django is more product ready solution IMO
there is project to resolve your websockets: Django Channels
there is project to have everything out of the box for REST API: Django Rest Framework
Flask should be having its own analogs though, but I never tried them, just heard about Flask Restful
FastAPI could be a better choice than flask
I was just deciding on learning a back-end framework
why ?
It offers the same set of features but is more performant, has built-in DI system and is integrated with pydantic providing data validation and openapi spec
wdym?
Where can you deploy it ?
It's not different from deploying any other python web app
I know, i'm talking about support
because for example
I've just read that pythonanywhere doesn't support asgi
Because I have 2 apps deployed on pythonanywhere
and i thought about switching to FastAPI for better performane
but i think it'll be better to move from pythonanywhere, because it's very limite
d
Why not use any vds provider instead?
Idk what that is
FastAPI is great... if you're building an API.
FastAPI framework, high performance, easy to learn, fast to code, ready for production
You mostly see SPA frontends these days
I like using SPAs... hate having to build them.
Also, it's easy to package FastAPI in a Docker container with uvicorn and a reverse proxy of your choice.
Same applies to any other framework - django or flask as popular examples
It's really more about developer experience
Yeah, just run docker on a cheap vps with *docker compose and you're set.
Ooh, DO has a container registry product now.
Anyways, I wanted to brainstorm some architecture.
I have an API backend (Django because we known Django) and SPA frontend. Both the frontend and backend are behind a CloudFront distribution. The backend is ECS and we pass traffic with a certain path back to it. Frontend is served from S3 with CloudFront acting as a CDN.
I'm thinking I could replicate this locally with Nginx as a reverse proxy serving the SPA statically and passing traffic through to the backend container.
cool, thanks :)
is this web-dev including questions regarding Web3 and Dapp?
how to build the encryption flow? https://imgur.com/a/Yms99YV
Has anyone setup the python backend in cpanel for a website?
I was wondering how I could create an html button that executes a python flask file
Just using Https will already make stuff encrypted.
Plus u can make VPN tunnels between your servers
Html form created button to call URL in POST form
Div object can be made looking as custom looking button. Wrapping to a tag will make it calling GET request to specified url
And finally attaching JavaScript event listening to click, can make any object to call any type of request
How to connect celery with flask and Redis as message broker and do machine learning predictions
# flask rest API code for inference
response = {}
@app.route('/predict', methods=["POST", "GET"])
def predict():
if request.method=='POST':
solute = request.form["solute"]
solvent = request.form["solvent"]
else:
solute = request.args.get("solute")
solvent = request.args.get("solvent")
results = predictions(solute, solvent)
response["predictions"] = results[0].item()
response["interaction_map"] = (results[1].detach().numpy()).tolist()
return flask.jsonify({'result': response})
I am doing inference of a machine learning PyTorch model and want to use celery and Redis for queuing prediction. I have written the inference code in the flask as a rest API and now got confused about how to add celery tasks and Redis message broker.
are you on windows?
it still applies
(context django) how can I create a custom model field for chess.Board class of python-chess lib? I read the docs but they are too hard for me to follow. I think subclassing CharField and saving FEN strings provided by board.fen() would do the job.
Good morning I want to ask if somebody can help me. I want to but music over a whole website so that if you open a new html file the music is still playing. over every file in the website
yes, that sounds like a good idea
looking at the python-chess docs, i'd probably do the same
Hello Guys, we have used python flask for developing the website https://avilpool.xyz/. Frontend is html coded. Need your comments on this.
Crypto Tracker made for investors and creators. In search of next BTC/ETH/BSC, shit coin detection, scam token detection, shitcoin
I see no questions
Thanks. man.
ive got a form that looks like that, each row represent a record in the database and I want to submit this through ajax, what would be the best way to pass the data? Should I put each row in it's on form and then try to submit multiple forms at once through ajax? or maybe build a list of some sort and submit the list as a single form?
if you want to do it via AJAX, then there's no trivially easy solution. You'll have to get the values from the form in JS, then send that as a JSON post request to your app, and make any visual updates you want to show to the user in JS
It doesn't have to be ajax, but I was more wondering how to handle the individual rows since each row is basically an identical form
I am trying to queue predictions using celery in flask . I was trying to add async results in celery but i have no idea where to add can some one please help - https://docs.celeryproject.org/en/stable/reference/celery.result.html
def predictions(solute, solvent):
mol = Chem.MolFromSmiles(solute)
mol = Chem.AddHs(mol)
solute = Chem.MolToSmiles(mol)
solute_graph = get_graph_from_smile(solute)
mol = Chem.MolFromSmiles(solvent)
mol = Chem.AddHs(mol)
solvent = Chem.MolToSmiles(mol)
solvent_graph = get_graph_from_smile(solvent)
delta_g, interaction_map = model([solute_graph.to(device), solvent_graph.to(device)])
return delta_g, torch.trunc(interaction_map)
@celery.task()
response = {}
@app.route('/predict', methods=["POST", "GET"])
def predict():
if request.method=='POST':
solute = request.form["solute"]
solvent = request.form["solvent"]
else:
solute = request.args.get("solute")
solvent = request.args.get("solvent")
results = predictions(solute, solvent)
response["predictions"] = results[0].item()
response["interaction_map"] = (results[1].detach().numpy()).tolist()
return flask.jsonify({'result': response})
hi can anyone please help me with disabling back button once user logs out from an app in flask (without deleting cache)
that would be done with javascript.
Are you using a frontend or just plain javascript/jinja templates?
I tried the windows.history.forward() method in my JS ..but I was looking for a better solution
hello friends
is anyone familiar with django messaging framework?
how would you make a django message to go away after x amount of secs?
I need to create the following flow in django ,. how is this possible?
1. User sends a request to the web server. A direct access to the database is forbidden.
2. The request is sent to the authentication server to be validated.
3. Authentication server provides an access token that can be expired after a short period.
4. Web-server verifies an access token and responds with decrypted data.
<link rel="stylesheet" href="{{ url_for('static',filename='style.css') }}" />
this is getting a lot of errors
why
File "manage.py", line 42, in <module> main() File "manage.py", line 38, in main execute_from_command_line(sys.argv)
Does anyone has a nice Flask community server maybe?
#python-community message
there’s a link to the Pallets server in this message
You’ll have to scroll up a little actually
hello guys, i use Vue and Django and my cookies are not setting, when i make request in insomnia my cookies are set
hello,I am new to Django and I wanted to know why do we have to use modelform as we can get the data through a form created by html.Thanks!
Is this maybe what you need? https://riptutorial.com/sqlalchemy/example/12146/order-by
Learn sqlalchemy - Order By
When i have app A in django and i login, can i use sessionid in app B? In my project dont work it, but i hope that its problem
How would you go about storing data for a survey?
There's about 20 questions that use radio dials and want to loop through them and get question, and both extreme points
what's the issue?
that's the ip you're visiting?
yeah i think you need to use something like ngix
an article from digital ocean. id say follow this
what do you want to do here? run this in production or development?
i dont understand why you would want to run this in development on digitalocean
currently the way it is, this thing is only available on localhost, on wherever your droplet is being hosted
it's not being exposed to the public
much similar to how a local server works on your pc
@thorn igloo ^
dont you still have the droplet?
but anyways, my point still stands, no point in running this in development on digitalocean
just use gunicorn or so
i don’t know how… can u add me, i wouldn’t mind paying u a lil to help me set it up
the link i sent is detailed in what you need to do, just follow it
actually this is better
might even have what you're looking for
I just reverse proxy my flask server
And boom it works
Even without using socket
I have flask app and I have created virtual env. in this but when I try to install packages with req.txt file I get this error
how I can make a popup box when I go to specific box
using flask first time?
ERROR: Failed building wheel for scipy
Running setup.py clean for scipy
ERROR: Command errored out with exit status 1:
command: /home/ubuntu/huawei-knowledge-graphs/PD/myprojectenv/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-th7_4ljx/scipy/setu
p.py'"'"'; __file__='"'"'/tmp/pip-install-th7_4ljx/scipy/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"'
);f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' clean --all
cwd: /tmp/pip-install-th7_4ljx/scipy
Complete output (11 lines):
/tmp/pip-install-th7_4ljx/scipy/setup.py:116: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses
import imp
`setup.py clean` is not supported, use one of the following instead:
- `git clean -xdf` (cleans all files)
- `git clean -Xdf` (cleans all versioned files, doesn't touch
files that aren't checked into the git repo)
Add `--force` to your command to use it anyway if you must (unsupported).
----------------------------------------
ERROR: Failed cleaning build dir for scipy
Failed to build psycopg2 psycopg2-binary scipy
ERROR: pandas 1.3.5 has requirement python-dateutil>=2.7.3, but you'll have python-dateutil 2.7.2 which is incompatible.
ERROR: scikit-learn 1.0.2 has requirement scipy>=1.1.0, but you'll have scipy 1.0.1 which is incompatible.
Installing collected packages: attrs, click, Werkzeug, itsdangerous, MarkupSafe, Jinja2, Flask, Flask-Login, greenlet, SQLAlchemy, Flask-SQLAlchemy, numpy, pytz, six, python
-dateutil, pandas, passlib, pluggy, psycopg2, psycopg2-binary, py, pytest, threadpoolctl, scipy, joblib, scikit-learn, sklearn, jellyfish, recordlinkage
Running setup.py install for psycopg2 ... error
I want to deploy my site
I have installed this packages in my local machine it didn't gave me this error but when I use venv I get this error
IDE name?
already upgreaded
WARNING: Requirement 'scipy-0.16.1-cp27-none-win_amd64.whl' looks like a filename, but the file does not exist
ERROR: scipy-0.16.1-cp27-none-win_amd64.whl is not a supported wheel on this platform.
got this
pip install C:\Python27\numpy-1.11.2rc1+mkl-cp27-cp27m-win32.whl
pip install C:\Python27\scipy-0.18.1-cp27-cp27m-win32.whl
I am using linux
yes
$ sudo apt-get install libatlas-base-dev gfortran
$ sudo pip3 install scipy
try this
$ sudo apt-get install libatlas-base-dev gfortran
$ sudo pip3 install scipy
one by one
what is showing
pip install -r requirements. txt
what is the problem then?
yes
see I want to deploy this site with gunicorn but for that I need virtual env right?
can I do that without that?
because every config I see it has virtual env
You have deployed any flask app on virtual machine?
so i can not guide anything related this deployment
ok
How do I make a subdomain?
Same A(or AAA for ipv6) record as for main domain
Just instead of @ or www, we write subdomain. Example:
A dev 35.65.56.55 600
hi im trying to run my web in vscode but it wouldn't run it says (Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases.) so anyone could help me to run it ?
Oh wait
How do I connect my website as a subdomain using flask? (In one hosting)
Flask is not the tool to make subdomain.
U just point DNS records to ip server with flask
How do I do that then? 
👆
Code wise 
U setup DNS settings for your domain
Using GUI in Domain provider
Or terraform / pulumi any other infra tool to do the same as code
Oh it's not easy then 
Pulumi has Python support ;)
@inland oak
I explained how to set subdomain for real server.
The guide explained two things
-
how to test domain restricted applications at developer machine (useful)
-
how to have routing at flask application level to handle two domains from same application.(in my opinion that is useless information, because usually we want second domain for second application. I never encountered the need to handle two domains from one application. That is silly and against microservices approach)
Monolith is not the way.
im sure that its not form the pc its form vscode cause i wrote in the cmd and it was all right
Create venv for your project (from console) at root folder where u open it
And in corner of vscode, select venv path to it, if it was not autselected
In 99.999% cases we don't need vscode access to global python anyway
it tells me the same when i try to make a venv
The whole purpose of subdomains is to have different application from different IP to it.
If it is the same app. Just use different sub path.
The only case when it is acceptable to direct two domains to one ip... In k8s ingress. And in nginx reverse proxy. Because they both fastly making internal redirects to different apps
i wrote (python -m venv work_env) in the terminal
Select it at the corner of vscode
Bottom left of right
You could do the same using any reverse proxy really, it doesn't have to be hosted in k8s
I mentioned reverse proxy
I would have added k8s prefix then ;b
I see thanks! But I don't know much about nginx or the other one I'll learn it later!
I didn't ever use ingress outside of k8s, I wonder if it is possible or it is purely kubernetes native app
Learn nginx, that would be easier. There is free book about it
There are other solutions, like traefik 🤔
They serve different purposes, don't they?
If you use nginx solely as a reverse-proxy then not really
Ingress is for routing
Traffic reverse proxy + advanced caching
Nginx can do caching too though
Traefik can do simple load balancing, and caching is only available in enterprise version 🤔
Nginx gives most of access to caching (part is only in enterprise)
And load balancing is almost fully only in enterprise
Haproxy could work as a free load balancer
Or just to use cloud providers lbs
I am doing prediction on a machine learning model using PyTorch and in Django rest framework. while loading I am getting TypeError: 'method' object is not subscriptable error. How to rectify this error. My views.py file
response = {}
@api_view(['GET'])
def result(request):
solute = request.POST.get['solute']
solvent = request.POST.get['solvent']
results = predictions(solute, solvent)
response["predictions"] = results[0].item()
response["interaction_map"] = (results[1].detach().numpy()).tolist()
return Response({'result': response}, status=200)
class ApiConfig(AppConfig):
name = 'api'
MODEL_FILE = os.path.join(settings.MODELS)
model = joblib.load(MODEL_FILE)
``` my `apps.py` file
You're using dict.get wrong
.get is function, requires (), not []
Then how to change it?
Either do request.POST["key"] or request.POST.get("key")
do i need to use {}
File "C:\Users\MAHESH\Desktop\iiit hyderabad\django rest api\api\views.py", line 384, in result
solute = request.POST['solute']
File "C:\Users\MAHESH\anaconda3\lib\site-packages\django\utils\datastructures.py", line 78, in __getitem__
raise MultiValueDictKeyError(key)
django.utils.datastructures.MultiValueDictKeyError: 'solute'
``` after changing i got this error
There is no value with this key I guess
Use get to be not having errors if there is no strict need to have it, optionally provide default value
Or try catch error and do what needs to be done in case it is missing
Although u know, I am quite sure it is wrong way to address post data in Django
Yep, you should be using forms
I remember they were in dictionary ending with .data
I am taking two strings from the user and doing a prediction and sending the results as json using rest api. Is this login justify my code? Do i need to use models?
But it is a django rest api and the frontend side is react.
Then use drf
Or other framework like FastAPI, i personally don't really to write api's using django
request.POST.data ?
Django, API, REST, Serializers
Or request.data I don't remember
i am trying to integrate celery and redis. I have already written it using flask but unable to integrate with celery so i was shifting to drf.
@app.route('/predict', methods=["POST", "GET"])
def predict():
if request.method=='POST':
solute = request.form["solute"]
solvent = request.form["solvent"]
else:
solute = request.args.get("solute")
solvent = request.args.get("solvent")
results = predictions(solute, solvent)
response["predictions"] = results[0].item()
response["interaction_map"] = (results[1].detach().numpy()).tolist()
return flask.jsonify({'result': response})
``` flask code
Huh. Celery is agnostic to framework
If you're using drf at this moment then you should use serializers to validate and clean your data
ok
i have problem finding tutorials using flask and celery
Use official celery docs
They have valid enough getting started instructions
There are no attachments to specific framework
In its original version at least
ok
Even if there is no database interactions?
Yep
Serializers != Models
You would still use pydantic models(serializers) in fastapi app, right?
Even if there's no db interactions
I guess it makes sense. Getting nice inbuilt JSON errors from validators work
Haven't used FastAPI yet. Going to fix it later
Just as an example:
class UserCreateSerializer(serializers.Serializer):
username = serializers.CharField(min_length=3)
It's guaranteed to be a string, otherwise when doing any operation on something that you expect to be a string you'd just 500:
username = None
username.lower()
For now all the different DevOps tools consume my time ;)
Going to setup monitoring/logging/autoalerts in k8s next
Cool. Validator without database usage
I wonder if DRF can catch it
Or without db in drf it would not give error
Catch what? 🤔
That it is a string or not
It would, you should just create your serializer and validate it
from rest_framework import serializers
class CommentSerializer(serializers.Serializer):
email = serializers.EmailField()
content = serializers.CharField(max_length=200)
created = serializers.DateTimeField()
serializer = CommentSerializer(data={"some": "data"})
serializer.is_valid(raise_exception=True)
Let's assume that while not tested it is not guaranteed in drf ;)
Wdym it's not guaranteed?
Okay, I did not see it ;)
Thanks
I can see now
I meant that if you're not using drf serializers and just accessing request.POST["something"] it's not guaranteed to be of the type you expect or be cleaned (e.g. trailing/leading whitespaces)
I did not see before usage of serialisers alone without model
That is why was doubtful
Yep, there's ModelSerializer but if you expect some data to be in your query for example you could create a serializer for it
I see no problems here.
Query URL data can be accessed in same dictionary way as post data
I know that drf has built-in pagination, but it's just an example:
class Query(serializers.Serializer):
page = serializers.IntegerField(min_value=1, default=1)
page_size = serializers.IntegerField(min_value=1, max_value=1000, default=100)
def some_view(request):
query_serializer = Query(request.params)
query_serializer.is_valid(raise_exception=True)
query_data = query_serializer.validated_data
Not all of your data would come from db, you might call other services, so using something like django-filter is really meaningless here
class Prediction(serializers.Serializer):
solute = serializers.CharField()
solvent = serializers.CharField()
``` I have created serializer now i want to use this serializer inside views how can i use it?
response = {}
@api_view(['GET'])
def result(request):
solute = request.POST.get('solute')
solvent = request.POST.get('solvent')
results = predictions(solute, solvent)
response["predictions"] = results[0].item()
response["interaction_map"] = (results[1].detach().numpy()).tolist()
return Response({'result': response}, status=200)
``` where should i have to keep here the above serialize in my `views.py` @serene prawn
You probably have to use an APIView
https://www.django-rest-framework.org/api-guide/views/
Django, API, REST, Views
but i am already using @api_view(['GET]) ??
Yep, you just need to use your serializer then, usually they're stored in separate module (e.g. serializers.py),
@api_view(['GET'])
def result(request):
serializer_in = serializers.Prediction(data=request.data)
serializer_in.is_valid(raise_exception=True)
data = serialzier_in.validated_data
response = {}
results = predictions(data["solute"], data["solvent"])
response["predictions"] = results[0].item()
response["interaction_map"] = (results[1].detach().numpy()).tolist()
return Response({'result': response}, status=200)
I just always used class-based views 😅
<div class="owo">
<div class="uwu">
is owo the parent and uwu is child?
Or this isn't a relationship?
it depends on closing elements
<div class="owo">
<div class="uwu">
</div>
</div>
in this situation uwu is child of owo. and owo is parent of uwu.
uwu is content of owo
<div class="owo"></div>
<div class="uwu"></div>
in this situation they are both elements of the same level. childs of smth.
and both empty in content
I am struggling with my Flask SQAlchemy query. I have categorized articles. I can query the articles easily enough and get their associated categories. My problem is doing the reverse -- query the category and retrieve associated articles.
The following is from my models
`class Category(db.Model):
__tablename__ = "category"
id = db.Column(db.Integer, primary_key=True)
slug = db.Column(db.String(64), index=True, unique=True, nullable=False)
name = db.Column(db.String(128), nullable=False, index=True)
categories = db.relationship(
"Category",
secondary=article_categories,
lazy="subquery",
cascade="all,delete",
backref=db.backref("articles", lazy=True),
class Articles(db.Model):
`
and from my view
@artitcle.route("/category/<category_slug>", methods=["GET"]) def by_category(category_slug): category = Category.query.filter_by(slug=category_slug).first_or_404()
I can retrieve the category but I cannot retrieve the associated articles. Is there something missing from my model?
Could you send code of both of your models again?
`class Category(db.Model):
__tablename__ = "category"
id = db.Column(db.Integer, primary_key=True)
slug = db.Column(db.String(64), index=True, unique=True, nullable=False)
name = db.Column(db.String(128), nullable=False, index=True)
article_categories = db.Table(
"article_categories",
db.Column("article_id", db.Integer, ForeignKey("articles.id")),
db.Column("category_id", db.Integer, ForeignKey("category.id")),
)
class Articles(db.Model):
categories = db.relationship(
"Category",
secondary=article_categories,
lazy="subquery",
cascade="all,delete",
backref=db.backref("articles", lazy=True),
__tablename__ = "articles"
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, ForeignKey("users.id"), nullable=False)
uuid = db.Column(db.String(36), index=True, unique=True, nullable=False)
title = db.Column(db.String(180), index=True, unique=False, nullable=False)
released_at = db.Column(db.DateTime, nullable=True, index=True)
categories = db.relationship(
"Category",
secondary=article_categories,
lazy="subquery",
cascade="all,delete",
backref=db.backref("articles", lazy=True),
)`
Use a codeblock
I have been trying to figure out how to do that i discord.
@fickle mantle Why your categories relationship is in Category class though?
It actually is not. That was pasted by accident. I updated the models here
Does someone know why Django Python gives me this error when trying to run python manage.py makemigrations?
if self.max_length is not None and choice_max_length > self.max_length:
TypeError: '>' not supported between instances of 'int' and 'str'
I have checked my models, everything looks fine.
anyone know anything about webscraping?
not sure if this is the right channel
kinda loopy rn
A whole book about it
have a shame. it is supposed to be bought. google it on your own.
Hey guys
yes
bwt how?
can unathorized user change data?
if you will leave loopholes in your web server, then yes 😉
or if you will make interface to do so
ignore my autism
ohh
I need to populate a survey with 3 different words for each input. Trying to figure out how to store the data to loop through it to auto-generate it
Looks like you need int(choice_max_length)
In this picture there is a yellow circle
inside the i
how can I place things like that over the text with html and css
With positioning. Look up absolute and relative positioning in CSS.
Can anyone help with exchange codes?
If anyone knows how I would go about setting up an smtp server in python pls dm me
You don't set it, you pass it to the smtp module via functions
can someone help me with this? it is related with flask framework
Connection is my class btw
if I did this one
data = Connection(document = doc)
session.add(data)
session.commit()
it will raise error (psycopg2.errors.InFailedSqlTransaction) current transaction is aborted, commands
ignored until end of transaction block
and when I do this
data = Connection(document = doc)
session.add(data)
try:
session.commit()
except:
session.rollback()
session.flush()
It does not save to db but it raise saved successfully please help
I am using Django rest framework to do prediction on two strings and using celery to run inference. But I was unable to make use of celery workers even though I have done everything perfectly. I am getting predictions from drf only
I am using redis as a broker.
My tasks.py
@shared_task(bind=True)
def predictions(self,solute, solvent):
mol = Chem.MolFromSmiles(solute)
mol = Chem.AddHs(mol)
solute = Chem.MolToSmiles(mol)
solute_graph = get_graph_from_smile(solute)
mol = Chem.MolFromSmiles(solvent)
mol = Chem.AddHs(mol)
solvent = Chem.MolToSmiles(mol)
solvent_graph = get_graph_from_smile(solvent)
delta_g, interaction_map = model([solute_graph.to(device), solvent_graph.to(device)])
return delta_g, torch.trunc(interaction_map)
#My `views.py`
@api_view(['GET'])
def result(request):
response = {}
solute = request.GET.get('solute')
solvent = request.GET.get('solvent')
results = predictions(solute,solvent)
response["interaction_map"] = (results[1].detach().numpy()).tolist()
response["predictions"] = results[0].item()
return Response({'result': response}, status=200)
I guess the problem is not adding .delay() to results = predictions(solute,solvent) but if I add results = predictions(solute,solvent).delay() I am getting error.
Even though I am getting my prediction perfectly without any error their is no celery task is running please help me where I am doing wrong
flower panel
Could you send an actual error you're getting from your database?
Can you use document.getElementById in a py file?
EmailField renders <input type="email"> while StringField renders <input type="text">
I wish to use an npm package but my app is on a flask server. Can anybody help?
.help
I'm working on a flask project with 2 other people what should we do first the front end or backend?

is it possible to translate django responses on rest framework? (multi-language responses)
so when i try to run the code it says no module named flask, i tried to change python interpreter but its not working anyone have an idea that might work?
which is better flask or django to pursue a career
there is nothing called app in flask library
u have initialize an app like
app = Flask(
name)
oh
yeh
let me try
from flask import Flask
and then
app = Flask(name)
__name __
underscore2nameundeerscore2
omg
wtf
--name--
instead of -- __
name
ez
install flask
i did
Grammar noob
Flask
from flask import Flask
yeah there isnt any error in the code but i can see the result
cant
what npm package do you need? is there a python alternative?
remove
app = Flask(name) from function
ignore shitty vsc errors then
lol
same
I was curious if whether having cloud serve act as my database for the iot system can affect the system's performance?
because I was using mongodb, but only realized that it can only store the images in a string type unlike cloud server which you can see the images taken from the iot directly from the server.
Can someone help regarding php laraval
It's better to ask in a php server
It depends
Django anytime
Can you explain what you want to do.
hey
is there anything like one click and hacked, and can anyone explain me about it?
bruh
u taking to me?
yes
ohh ok
there is no tool for that
phishing sitE?
u gotta know ethical hacking and cybersec stuff to setup your own tools
ik preety much abt it
and this is not the channel to talk bout that
what do u know bout it
jst tell me surfacely
as far as I think u r trying to phish someone and kid this ain't the place to talk hacking stuff
don't send me reqs
this ain't the place to talk hacking stuff so i send u req
no i don't accept strangers reqs
ok
u gotta search on the topic
anyways its web development
and learn with a structure
did a lot reacearch bwt not satisfied
so i came here
to get some knowledge abt it
tell me what u did
and maybe u wanna know more bout it so talk in #cybersecurity
i searched but, what I found was there is like the victim(who is going to be hacked ) should also provide
authentication to get hacked
and i wanna know can some one get hacked by just clickng a link
yes they can btw
how to deploy django app the easiest way?
use heroku
and why cant we deploy it in netlify?
or the best is pythonanywhere.com
bwt what?
sorry man never heard of it
ok thanks
u can use pre built Kali Linux tools
idk if they are available on github or not
such as
I don't remember the name I'm not a cybersec guy
but u can use it to clone webpages and host it
just like make a fake LinkedIn page and host it
And send it to someone and if someone enters their credentials to login u get what they entered which is the their credentials
this has been sick nowadays
everyone is aware of it
and i was taking abt hacking systems not linkden acc
ik it
it's kind of not easy to hack into systems
u have to either setup a malware or a backdoor u developed physically in a system and get access
i jst wanna know is how is it possible to get hacked by jst clicking to link and not doing any thing else
it ain't possible
it is never possible
unless ur very trained and can code tools that can make this possible
no i read an article at morning
it was about RAT link
if yes then do what it says
u still will have to get the malware in the victim's phone somehow
and if it is successful u have the access to the system
it was like getting a malware in browser and if victim closes the browser then u will be no longer getting information
idk bout that bruh
u read the edit part
but it is possible he said
sounds like a cookie stealing attack (CSRF) , most modern websites will have procedures to prevent this
I made this basic thing


