Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Accessing Django Foreign Key Object Values through Django Shell
How do I correctly access Foreign Key Values through the Django Shell? I am trying to access the Foreign Key Values of the Placement Field (an integer from 1 to 8) through the Django Shell. When I query I receive values greater than 8 (the max of data currently entered), which is unexpected. Django Admin Screenshots: Champion_Placement Table , Match_Placement Table Query: manage.py shell from stats.models import * Champion_Placement.objects.all('placement').values() <QuerySet [{'placement': 10}, {'placement': 10}, {'placement': 10}, {'placement': 10}, {'placement': 10}, {'placement': 10}, {'placement': 10}, {'placement': 10}, {'placement': 10}, {'placement': 11}, {'placement': 11}, {'placement': 11}, {'placement': 11}, {'placement': 11}, {'placement': 11}, {'placement': 11}, {'placement': 11}, {'placement': 12}, {'placement': 12}, {'placement': 12}, '...(remaining elements truncated)...']> Models: from django.db import models class Summoner(models.Model): puuid = models.CharField(max_length=100) name = models.CharField(max_length=30, null=True) def __str__(self): return f'{self.name} - {self.puuid}' class Match_Placement(models.Model): match_id = models.CharField(max_length=100) placement = models.PositiveSmallIntegerField() puuid = models.ForeignKey(Summoner, on_delete=models.CASCADE) def __str__(self): return f'{self.match_id} - {self.placement}' class Champion(models.Model): champion_id = models.CharField(max_length=40) name = models.CharField(max_length=30) cost = models.PositiveSmallIntegerField() def __str__(self): return f'{self.name}' class Item(models.Model): item_id = models.PositiveSmallIntegerField() name = models.CharField(max_length=40) def __str__(self): return f'{self.name}' class Champion_Placement(models.Model): match_id = models.ForeignKey(Match_Placement, related_name='%(class)s_match_id',on_delete=models.CASCADE) placement = models.ForeignKey(Match_Placement, related_name='%(class)s_placement', on_delete=models.CASCADE) champion_id = models.ForeignKey(Champion, related_name='%(class)s_champion_id', on_delete=models.CASCADE) champion_level = models.PositiveSmallIntegerField() item_1 = models.ForeignKey(Item, … -
How can you make a collapsible menu in Django?
I'm trying to build an admin dashboard in Django and I've came across a problem. Here would be the HTML code: I want that when the user clicks "Email Searcher", more values appear. Those values are called "Butons" and "Cards". But I don't know how someone can make this happen in Django. <li class="nav-item"> <a class="nav-link collapsed" href="{% url 'emailfinder' %}" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="true" aria-controls="collapseTwo"> <i class="fas fa-fw fa-cog"></i> <span>Email Searcher</span> </a> <div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#accordionSidebar"> <div class="bg-white py-2 collapse-inner rounded"> <h6 class="collapse-header">Custom Components:</h6> <a class="collapse-item" href="{% url 'example' %}">Buttons</a> <a class="collapse-item" href="cards.html">Cards</a> </div> </div> </li> any help would really appreciate it! -
Django - Add custom fields to records
Suppose we have a Mode Table with common fields (id, name, date_creation) class Table(models.Model): id = models.AutoField(primary_key=True, unique=True) name = models.CharField(max_length=128, blank=True, null=True) date_creation = models.DateTimeField(blank=True, null=True) Some Tables must have a "Wheels" attribute (eg: wheels="plastic"), while other tables do not require this attribute and require something else. eg : Table 1: id = ..., name = ..., date_creation = ..., wheels = "plastic" Table 2: id = ..., name = ..., date_creation = ..., feet = "wood" How can i manage this extrafields in Django in order to deserve them in Django Rest Framework? -
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 …