Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django get specific QuerySet with GET ajax Call on button click
i have a problem and i dont know if im using the good way to solve it , but their is the problem , i have a client list that i show on the client page , by getting all client with a simple clients = client.objects.all() so all client can have a lot of sessions, and session have a lot of clients, its like a ManytoMany relation, so what im trynna do its to show the assigned session of client one by one by clicking on a button (the button open a boostrap modal ) , so i tried to send the id of the the chosen client on click and send it into a django view with ajax GET method, and take this ID directly to find all sessions related with this client and return the query to this page , so the ajax is working correctly and i can send the id , but its like the view its not sending anything . so their is my code hope you can help me : Html (the div im inserting on the forloop client) : <div class="list-group list-group-me"> <ul class="list-group list-group-horizontal"> <li class="list-group-item">{{ client.name }}</li> <li class="list-group-item">{{ client.email … -
Django Cookie consent
I am looking for a decent documentation and ideally also a full example on how to use the cookie-consent app in django. I found this app here: github code on cookie-consent but I cannot imagine how to use it. And the documentation provided does not help much... as I do not understand what to do to implement. regards Marina -
In django if I have more than one database , how do I tell django to create which model-table in which database?
For example I have these two databases. Now while creating a model class, how do I tell django to initiate that model table in the 'movie' database and not in the 'default' one. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'projectInfo', 'USER': 'root', 'PASSWORD': '123@abc', }, 'movie': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'movieDB', 'USER': 'root', 'PASSWORD': '123@abc', } } -
Gmail sending with attachment in Django
I am trying to send Gmail with attachments also in Django. here my views.py: def index(request): if request.method != 'POST': form = EmailForm() context = {'email_form': form} return render(request, 'app/index.html', context) form = EmailForm(request.POST, request.FILES) if form.is_valid(): subject = form.cleaned_data['subject'] message = form.cleaned_data['message'] email = form.cleaned_data['email'] attach = request.FILES['attach'] try: mail = EmailMessage(subject, message, settings.EMAIL_HOST_USER, [email]) mail.attach_file(attach.name, attach.read(), attach.content_type) mail.send() context = {'message': 'email sended'} print("email sended") return render(request, 'app/email_template.html', context) except: context = {'message': 'Either the attachment is too big or corrupt'} print("Either the attachment is too big or corrupt") return render(request, 'app/index.html', context) context = {'message': 'Unable to send email. Please try again later'} return render(request, 'app/index.html', context) forms.py: class EmailForm(forms.Form): email = forms.EmailField() subject = forms.CharField(max_length=100) attach = forms.Field(widget = forms.FileInput) message = forms.CharField(widget = forms.Textarea) template: <div class="container-fluid"> <div class="col-xl-4"> <h1>Welcome in django's world</h1> {{message}} <form method="POST" action ="." enctype="multipart/form-data"> {% csrf_token %} <br></br> {{email_form.as_p}} <label>&nbsp;</label><label>&nbsp;</label><label>&nbsp;</label> <input type ="submit" name = "send" value = "Send"/> </form> </div> </div> Now each and every time I tried to sent mail, it shows Either the attachment is too big or corrupt, that means it goes by the except: block, instade of try block. Now how can I solve this … -
Django: After updating a post, how can i make the "updated" success message temporary, till I refresh the page. Cause now it stays after refresh
Django: Hi everyone, After updating a post, how do i redirect success message to full details page TEMPORARILY. because for my code now, after i update, i can see the updated message but even after refreshing, the updated success message remains there. kindly advise thank you! views.py def edit_blog_view(request, slug): context = {} blog_post = get_object_or_404(BlogPost, slug=slug) if request.POST: form = UpdateBlogPostForm(request.POST or None, request.FILES or None, instance=blog_post) if form.is_valid(): obj = form.save(commit=False) obj.save() return redirect('HomeFeed:detail', slug=slug) form = UpdateBlogPostForm( initial = { "brief_description": blog_post.brief_description, "image": blog_post.image, "body": blog_post.body, } ) context['form'] = form return render(request, 'HomeFeed/edit_blog.html', context) def detail_blog_view(request, slug): context = {} blog_post = get_object_or_404(BlogPost, slug=slug) context['success_message'] = "Updated" context['blog_post'] = blog_post return render(request, 'HomeFeed/detail_blog.html', context) detail_blog.html {% if success_message %} <div class="alert alert-success" role="alert"><h3 style="text-align: center;">{{success_message}}</h3></div> {% endif %} -
getting total number of records saved in django bulk_create
is there any way to get the number of total records inserted in Django model using bulk_create?? Entry.objects.bulk_create([ ... Entry(headline="Django 2.0 Released"), ... Entry(headline="Django 2.1 Announced"), ... Entry(headline="Breaking: Django is awesome") ... ]) In the above example, 3 records are inserted into the database. How can I get the total number of records using bulk_create?? -
template not showing the message
i was using Django Login system and it has a message error when i do run the template of the login and i do the mistake it doesn't give me and error login.html: <body> <div class="container"> <h1>Login</h1> <form action="" method="post"> {% csrf_token %} <div class="form-floating mb-3"> <input type="text" class="form-control" id="floatingInput" placeholder="name@example.com" name="username"> <label for="floatingInput">Username</label> </div> <div class="form-floating"> <input type="password" class="form-control" id="floatingPassword" placeholder="Password" name="password"> <label for="floatingPassword">Password</label> </div> {% for message in messages %} <h4 style="color: red;">{{message}}</h4> {% endfor %} <button type="submit" class="btn btn-dark mt-2">Log in</button> <a href="{% url 'register' %}" class="btn btn-dark mt-2 ml-3">Register</a> </form> </div> views.py: def login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') if username and password: user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect('home') else: messages.error(request, 'Username or Password is Incorrect') else: messages.error(request, 'Fill out all the Fields Please') return render(request, 'register/login.html', {}) -
How to fix UnboundLocalError at /accounts/register
I made a registration from for my django app.But when I click on the submit button I'm getting this error: local variable 'first_name' referenced before assignment Request Method: POST Request URL: http://127.0.0.1:8000/accounts/register Django Version: 3.1.4 Exception Type: UnboundLocalError Exception Value: local variable 'first_name' referenced before assignment Exception Location: E:\django\Hello_world\accounts\views.py, line 8, in register Python Executable: C:\Users\Asus\Envs\test\Scripts\python.exe Python Version: 3.9.0 Python Path: ['E:\django\Hello_world', 'c:\users\asus\appdata\local\programs\python\python39\python39.zip', 'c:\users\asus\appdata\local\programs\python\python39\DLLs', 'c:\users\asus\appdata\local\programs\python\python39\lib', 'c:\users\asus\appdata\local\programs\python\python39', 'C:\Users\Asus\Envs\test', 'C:\Users\Asus\Envs\test\lib\site-packages'] My code is views.py def register(request): if request.method == 'POST': first_name = request.POST[first_name] last_name = request.POST[last_name] username = request.POST[username] email = request.POST[email] password1 = request.POST[password1] password2 = request.POST[password2] user = User.objects.create_user(username=username, email=email, password=password1, first_name=first_name, last_name=last_name) user.save(); print('user created successfully') return redirect('/') else: return render(request, 'register.html') and the html file is: register.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Registration</title> </head> <body> <form action="register" method="post"> {% csrf_token %} <input type="text" name = 'first_name' placeholder="First Name"><br> <input type="text" name = 'last_name' placeholder="Last Name"><br> <input type="text" name = 'username' placeholder="Username"><br> <input type="email" name = 'email' placeholder="E-mail"><br> <input type="password" name = 'password1' placeholder="Password"><br> <input type="password" name = 'password2' placeholder="Confirm Password"><br> <input type="submit"> </form> </body> </html> -
django ManyToMany create object
i have two model with ManyToMany relations.. class foo(models.Model): .......... class bar(models.Model): foo = models.ManyToMany(foo) i use ModelForm for creating bar.. i wanna access new bar object (after save). if form.is_valid(): new_obj = form.save() i can access before save with : if form.is_valid(): new_obj = form.save(commit=False) but i can access it after save...what can i do? -
Check if user's email is verified in Firebase
I am currently making a login page with Django and Firebase, where after the user has been created, a link for verifying the email will be sent. I tried to add a feature where if the user has not verified the email, he/she is not able to log into the web application. Currently this is what i tried in my views.py (using pyrebase): import pyrebase config={my firebase configuration} firebase=pyrebase.initialize_app(config) db=firebase.database() auth=firebase.auth() def postsign(request): email=request.POST.get('email') passw=request.POST.get('pass') try: user=auth.sign_in_with_email_and_password(email,passw) usercheck = auth2.get_user(user['idToken'],email_verified) if usercheck == False: message="Please verify your email!" return render(request,"template.html", {"msgg":message}) except: message="Invalid credentials. Try again." return render(request,"login.html", {"msg":message}) I tried looking through the documentation, however, I only found a code for javascript, like in this post, and this link which is kind of what I am trying to achieve https://firebase.googleblog.com/2017/02/email-verification-in-firebase-auth.html -
how to use rest-framework simple JWT package for custom user model?
I have created a custom user model in Django. Now I'm authenticating with the below code. class Login(APIView): def post(self,request): email = request.POST['email'] password = request.POST['password'] user = authenticate(request, email= email,password=password) print(request.user) if(user is not None): print("Logged In") return Response("Hello") But from the official documentation I can't find how to achieve this is usecase. They just use TokenVerifyView.as_view() in urls.py file. How to use JWT authentication with this custom user model. -
how to create billing application in Django
I have planned to create billing application using Django. I need to store order in database, user's order as separate customer profile. I don't want to create each customer as user. I just want to store customer order details and print out the bill. I don't know how to create model and I cannot think the logic. Help me. -
How to perform code navigation in Django using docker
I could not find the code definition using Ctrl + click when I use Docker + Django in my project, since source code are now in container. How could I configure my VScode to enable code navigation? I am using django-cookiecutter with use-docker configuration. -
Django Views, having 2 redirects in 1 view
Is it possible to have 2 redirect() in the same django view. so when the like button is in the home page, i want it to redirect back to home page, if like button is in detail page, i want to redirect back to detail page? For instance: def LikeView(request, slug): context = {} post = get_object_or_404(BlogPost, slug=slug) post.likes.add(request.user) if in homepage: return redirect('HomeFeed:detail', slug=slug) else: return redirect('HomeFeed:main') -
Django Change Variable From DataBase on Referencing
I'm currently learning Django and I wanted to start off with a really simple blog app. I have a model for my post: class Post(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey( 'auth.User', on_delete=models.CASCADE, ) body = models.TextField() Then I'm referencing it on my home page template: {% extends 'base.html' %} {% block content %} {% for post in object_list %} <div class="post-entry"> <h2><a href="{% url 'post_detail' post.pk %}">{{post.title}}</a></h2> <p>{{post.body}}</p> </div> {% endfor %} {% endblock content %} I would like to make post.body to be only first 50 or so characters but post.body[:50] returns sytnax error. How could I do that? -
Should I avoid using unnecessary db transactions (django+postgresql environment)?
I'm using Django, using a Postgres DB, and I wonder: say I have a function like this: def yay_func(obj): log('yay') obj.is_yay = True obj.save() If I wrap this function in a transaction, will I cause any strain on my db? I checked the Django connections object, so I know another db request is made for creating a "save point", but I wonder if it's something I should consider when I'm trying to optimize my performance. -
Django where to swagger i want request body and response body
Swagger to look like this i want to know where to specify the request model and response model and schema in response body the serializers are taking the model which i specify they do give what is in the response change the request body as model and response model as the response which is coming t=in the reply -
Like post model with this Author already exists
What i want to do is basically user can like an article once. But this error keeps me from liking another article. Here is my code: class LikePostModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User, unique=True, on_delete=models.CASCADE,related_name='postlikes',null=True) article = models.ForeignKey(Article, on_delete=models.CASCADE,related_name='postlikes_set') created = models.DateTimeField(auto_now_add=True) How can i solve this problem? -
Changing API Versioning Strategy
I'm working on an API, using django rest framework which is currently in production. The versioning strategy in use is namespace versioning. I would like to switch to acceptheader versioning as it seems to suit the project better. Is there a way to make the change smoothly without breaking previous API versions. -
Unable to access User Registration page(Django)
Was following the Corey Schafer tutorial on Django. While trying to make the user registration part,i encountered this error: File "/home/trungks/django1_new/django1_new/urls.py", line 22, in <module> path('register/', user_views.register, name='register'), AttributeError: module 'users.views' has no attribute 'register' I did exactly what he was doing but still got this error. My code in register.html : {% extends "blog/base.html" %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4"> Join Today </legend> {{ form }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit"> Sign Up </button> </div> </form> <div class="border-top pt-3"> <small class="text-muted"> Already Have an Account?<a class="ml-2" href="#">Sign In</a> </small> </div> } </div> {% endblock content %} My code in views.py in the user folder: from django.shortcuts import render from django.contrib.auth.forms import UserCreationForm def register(request): form = UserCreationForm() return render(request, 'users/register.html', {'form': form}) My code in the urls.py: from django.contrib import admin from django.urls import path, include from users import views as user_views urlpatterns = [ path('admin/', admin.site.urls), path('register/', user_views.register, name='register'), path('', include('blog.urls')), ] Where did i go wrong? -
Add keys to Django i18n loaded Tags
I'm trying to add a key to my all languages in my project After {% load static i18n %} I have this loop in my template to help me investigate: {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} {{ language }} {% endfor %} and the output looks like this: {'bidi': False, 'code': 'en-gb', 'name': 'British English', 'name_local': 'British English', 'name_translated': 'Inglês Britânico'} {'bidi': False, 'code': 'pt-br', 'name': 'Brazilian Portuguese', 'name_local': 'Português Brasileiro', 'name_translated': 'Português Brasileiro'} I would like to add to this another key like 'lang_simple': 'en' or 'lang_simple': 'pt' but haven't figured out how to find where this is coming from. I tried looking for it using this answer, but didn't get very far: https://stackoverflow.com/a/20009830/7091922 If anybody has an idea, please let me know! Happy new year! -
Get ID in Django
I have a website made in Django, where people shall be able to post questions and answer them -just like a copy of Stack Overflow. When the user visits http://localhost/?post=Example it filters the database for posts with the name example. Later on I will do so there can only be exactly one post with the same name. Currently it just renders the post/question in the HTML document using {{post.author}} for instance. posts = Post.objects.filter(title=post) context = {'posts':posts}#, "answers":answers} return render(request, 'store/post.html', context) On Stack Overflow it is possible to answer a question. There can be multiple ones. So in my code I did this by making a foreignkey in a model called Answer that is linking the answer to a post. In the HTML document I made a for loop -just like I did for the post/question and looped through all answers and displayed them under the question. class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank = True) name = models.CharField(max_length=200, null=True) email = models.EmailField(max_length=200, null=True) about = models.CharField(max_length=100, null=True, help_text="Use this field for notes about the customer.") image = models.ImageField(null=True, blank=True) @property def imageURL(self): try: url = self.image.url except: url = 'placeholder.png' return url def __str__(self): return self.name class … -
How i can fix UnboundLocalError at /accounts/register [closed]
During work with the registration form when I click the submit button I'm getting this error: UnboundLocalError at /accounts/register local variable 'first_name' referenced before assignment Request Method: POST Request URL: http://127.0.0.1:8000/accounts/register Django Version: 3.1.4 Exception Type: UnboundLocalError Exception Value: local variable 'first_name' referenced before assignment Exception Location: E:\django\Hello_world\accounts\views.py, line 8, in register Python Executable: C:\Users\Asus\Envs\test\Scripts\python.exe Python Version: 3.9.0 Python Path: ['E:\\django\\Hello_world', 'c:\\users\\asus\\appdata\\local\\programs\\python\\python39\\python39.zip', 'c:\\users\\asus\\appdata\\local\\programs\\python\\python39\\DLLs', 'c:\\users\\asus\\appdata\\local\\programs\\python\\python39\\lib', 'c:\\users\\asus\\appdata\\local\\programs\\python\\python39', 'C:\\Users\\Asus\\Envs\\test', 'C:\\Users\\Asus\\Envs\\test\\lib\\site-packages']` Here is my views.py file: from django.shortcuts import render, redirect from django.contrib.auth.models import User, auth # Create your views here. def register(request): if request.method == 'POST': first_name = request.POST[first_name] last_name = request.POST[last_name] username = request.POST[username] email = request.POST[email] password1 = request.POST[password1] password2 = request.POST[password2] user = User.objects.create_user(username=username, email=email, password=password1, first_name=first_name, last_name=last_name) user.save(); print('user created successfully') return redirect('/') else: return render(request, 'register.html') -
Two submit buttons for one form in Django to use two diffrent functions from views
I'm new in Django and now I'm working on my first project. My home.html file includes form (bootstrap class) witch contains entries to fill with data. These data are integer type. method='GET At the bottom of the form i have two submit buttons. My intention is that first of them is going to grab data from entries, calculate them and show results on site of browser using home function from views. Second button is going to grab the same data, calculate them and use them for conversion to pdf by ReportLab by some_view function in views. My questions are. How to keep imputed values in entries (now these fields are cleared after clicking submit button) How can I use these two buttons separately as I mentioned above. Now I can make only one button active and I have to choose If I want use one function or another. views.py import reportlab import io from django.http import FileResponse from reportlab.pdfgen import canvas #================================== from django.shortcuts import render from . import slownie def home (request): ls='' ls1='' ls3='' liczba= request.GET.get("li200") liczba1=request.GET.get("li100") liczba3=request.GET.get("li50") if liczba and liczba.isdigit(): liczba=int(liczba)*200 ls=slownie.slownie(int(liczba)) if liczba1 and liczba1.isdigit(): liczba1=int(liczba1)*100 ls1=slownie.slownie(int(liczba1)) if liczba3 and liczba3.isdigit(): liczba3=int(liczba3)*50 ls3=slownie.slownie(int(liczba3)) suma=0 if … -
ProgrammingError at /search/ function similarity
I am trying to add full text search to my django website, but I am getting this error: ProgrammingError at /search/ function similarity(character varying, unknown) does not exist LINE 1: SELECT COUNT(*) FROM (SELECT SIMILARITY("blog_post"."title",... Here is my SearchForm: class SearchForm: query = forms.CharField() And here is my post_search view function: def post_search(request): form = SearchForm() query = None results = [] if 'query' in request.GET: form = SearchForm(request.GET) if form.is_valid(): query = form.cleaned_data['query'] results = Post.published.annotate( similarity=TrigramSimilarity('title', query), ).filter(similarity__gt=0.1).order_by('-similarity') return render(request, 'blog/post/search.html', {'form': form, 'query': query, 'results': results}) I am using a Postgres database(version 13.1.1), Django 3.1 and Python 3.7.5 What is the problem here?