Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Deploying Django on Amazon Elastic Beanstalk
I'm trying to deploy Django on EB but here's my issue: The deployment goes well, and I can migrate and create a superuser from the .config file in the .ebextensions directory. The only thing is, the Django server doesn't start by itself, and I have to python manage.py runserver via SSH to get it working. Which brings up another issue: when the EC2 instance shuts down, the Django server stops too and is not restarted at the next instantiation. Here's my .config file: container_commands: 01_migrate: command: "source /var/app/venv/staging-LQM1lest/bin/activate && export $(sudo cat /opt/elasticbeanstalk/deployment/env | xargs) && cd /var/app/staging/my_project_name && python manage.py migrate --noinput" leader_only: true 02_createsu: command: "source /var/app/venv/staging-LQM1lest/bin/activate && export $(sudo cat /opt/elasticbeanstalk/deployment/env | xargs) && cd /var/app/staging/my_project_name && python manage.py createsu" leader_only: true option_settings: "aws:elasticbeanstalk:application:environment": DJANGO_SETTINGS_MODULE: "monga.settings" "aws:elasticbeanstalk:container:python": WSGIPath: /var/app/current/my_project_name/my_project_name/wsgi.py NumProcesses: 3 NumThreads: 20 I even tried to add the following without success (it cannot even be deployed, probably because it gets stuck with the runserver command): 03_runserver: command: "source /var/app/venv/staging-LQM1lest/bin/activate && export $(sudo cat /opt/elasticbeanstalk/deployment/env | xargs) && cd /var/app/staging/my_project_name && python manage.py runserver" leader_only: true What should I do to get the Django server to run automatically? -
Risk of exposing an ID of entry in DRF framework
I'm building an API and I've started using the GenericAPIViews. In this example class InsertActivityChange(UpdateAPIView): authentication_classes = [] permission_classes = [] serializer_class = ActivitiesSerializer lookup_field = 'id' def get_queryset(self): return Activities.objects.filter(id=self.kwargs['id']) def put(self, request, *args, **kwargs): return self.update(request, *args, **kwargs) path('insertactivitychange/<int:id>', views.InsertActivityChange.as_view(), name='insertactivitychange'), I've used a generic class to do updates for an object. My concern is if I'm risking much by allowing the ID to be directly inputted after the URL. Obviously, I'd further mitigate the risk by properly configuring the authentication and permission class, so is the ID of the entry even a security risk? -
How to redirect to another view/page if the form is invalid
In the event that the form is not valid, how do I redirect the user to another page? def dothings(request): form = dumyForm(request.POST or None) if form.is_valid(): #do 123 else: # INSTEAD OF REINITIALIZING THE FORM LIKE THIS, I WANT TO REDIRECT TO ANOTHER PAGE form = form = dumyForm() return render(request,'dummy.html',{}) -
Venv not wrapping third-party libraries leading to module not found
I tried starting a Django project through python manage.py <folder_name> only to get the following stack trace: Traceback (most recent call last): File "C:\Users\User\PycharmProjects\pythonProject\web_projects\mysite\manage.py", line 12, in main from django.core.management import execute_from_command_line File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\django\core\management\__init__.py", line 12, in <module> from django.conf import settings File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\django\conf\__init__.py", line 19, in <module> from django.utils.deprecation import RemovedInDjango40Warning File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\django\utils\deprecation.py", line 5, in <module> from asgiref.sync import sync_to_async ModuleNotFoundError: No module named 'asgiref' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\User\PycharmProjects\pythonProject\web_projects\mysite\manage.py", line 23, in <module> main() File "C:\Users\User\PycharmProjects\pythonProject\web_projects\mysite\manage.py", line 14, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? The last line makes it evident what's missing but Django was already installed. First time, it wasn't included in the venv folder but even after including it through primitive copy-paste mechanism it didn't execute. How can it be resolved? -
How can I display form instance?
How can I pass the form with an actual filled profile informations (like ProfileUpdateForm(instance=x) in function views). I did it this way and have no idea how to pass an actual profile instance to the form class ProfileDetailView(FormMixin, DetailView): model = Profile context_object_name = 'profile' template_name = 'profiles/myprofile.html' form_class = ProfileUpdateForm def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): form.save() return super().form_valid(form) def get_success_url(self): return reverse_lazy('profiles:profile', kwargs={'pk': self.get_object().pk}) -
UNIQUE constraint failed: auth_user.username when creatin a django sign up form
I need to create sign up form manually and i can't so if you can help me it will be so kind from you :-) here it my code with VS code debugger -
Made a mistake. Didn't push the django migration file to github and there have been subsequent migrations. Now I don't know how to include that file
My changes were migrated to the prod database but I didn't include my migrations file in the pull request. Now on github, since migrations have been performed after mine, there is another migration file where mine should be, and then more after that. Not sure how to resolve this issue. -
Django built-in server cannot decode URL parameters
I'm not sure if this is a Django-specific issue but right now I see it in my project. Because browsers tend to cache favicon and I have changed them for my website, I came up with a trick to force anyone who have visited my site before to receive the new icons, adding "?" followed by some random characters to the image file name, so currently it is like this: <link rel="icon" type="image/png" sizes="32x32" href="{% static 'images/favicons/favicon-32x32.png?v=Gv6qnaoWO5' %}"> Now the issue is, the favicon is not loading and when I check the source I see this: <link rel="icon" type="image/png" sizes="32x32" href="/static/images/favicons/favicon-32x32.png%3Fv%3DGv6qnaoWO5"> and when I click on the above link, I get 404 error from django.views.static.serve. If I remove the "?" and rest of characters, everything works fine. If memory serves, this is normal encoding of special characters and the web server should decode it, but this is not happening on Django's built-in server. So, is there a fix for this, or I should wait until moving the site to production? -
Why doesn't DRF enforce non-empty field?
I am using a custom user model: from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): username = models.CharField(max_length=120, unique=True, blank=False, validators=[MinLengthValidator(6)]) email = models.EmailField('Email Address', unique=True) FCM_ID = models.CharField(max_length=300) I was hoping that I won't be allowed to create a user with blank email field, but for some reason, I can do so without any errors. User().save() successfully adds a user with all blank fields. The unique condition, however, is enforced as expected. Why is blank=False not enforced? Here's the custom user manager: from django.contrib.auth.base_user import BaseUserManager class CustomUserManager(BaseUserManager): def create_user(self, email, **kwargs): if not email: raise ValueError("The email must be set") email = self.normalize_email(email) user = self.model(email=email, **kwargs) user.save() return user def create_superuser(self, email, password, **kwargs): ... -
How do I use the {% url %} tag in a library app?
How do I use the {% url .. %} template tag in a "library" app to create a link to the library-app's own views? Given a site with mysite/urls.py: urlpatterns = [ url(r'^myapp/', include('myapp.urls', namespace='mysite')), ] and an app with myapp/urls.py: urlpatterns = [ url(r'^mylib/', include('mylib.urls', namespace='mylib')), ] and the library app with mylib/urls.py: urlpatterns = [ url(r'^commands/$', views.commands, name='list-commands'), url(r'^command-1/$', views.command_1, name='command-1'), ] where the views.commands view displays a template that should contain a link to /myapp/mylib/command-1/, ie. mylib/templates/mylib/list-commands.html <a href='{% url "command-1" %}'>command-1</a> It will of course work if I change it to: {% url "mysite:mylib:command-1" %} but the author of mylib doesn't know about neither mysite or myapp...? I have a feeling I've misunderstood something basic... -
Divide the SUM of two integers and return a Float in Python/Django
I've spent long time trying to return a Float result from the division of Sum(value1) and Sum(value2) Here's my code: kpiCapaTotal = reportKpiCeFilter.aggregate(kpiCapaTotal=Sum('operation_time') / Sum('load_time') * 100).get('kpiCapaTotal') It returns: 89,0 but the correct should be 89,3 I tried : kpiCapaTotal = reportKpiCeFilter.annotate(kpiCapaTotal=Sum('operation_time') / Cast(Sum('load_time'),FloatField()) * 100, output_field=FloatField()).get('kpiCapaTotal') It returns an error: "QuerySet.annotate() received non-expression(s): <django.db.models.fields.FloatField>." Also with aggregate: kpiCapaTotal = reportKpiCeFilter.aggregate(kpiCapaTotal=Sum('operation_time') / Cast(Sum('load_time'),FloatField()) * 100,output_field=FloatField()).get('kpiCapaTotal') Error: "QuerySet.aggregate() received non-expression(s): <django.db.models.fields.FloatField>." I'dont know how to divide the SUM of two integers and return a Float, do you have any idea? Python Version: 3.7 Djando Version: 2.1 -
Django call custom code based on model instance
I am working on a gamification framework in Django. I have a model Badge that describes a badge that users can obtain. I would like to associate to each and every badge a function that will basically run a query against my database and return True if the member can receive the badge or False otherwise. I was thinking of storing the function name as a CharField and use eval() but I was wondering if there would be a more Pythonic/Djangonic way to achieve this? -
Bootstrap 5 modal django - modal on separate html not opening from the base page
base.html when clicking on user profile icon, it should open login modal from another page on the base page. Now, instead of the modal raw html page opens with the content of login modal <a class="navbar-tool ms-1 ms-lg-0 me-n1 me-lg-2" href="{% url 'ecomapp:usersignin' %}" data-bs-target="#signin-modal" data-bs-remote= "{% url 'ecomapp:usersignin' %}" data-bs-toggle="modal"> <div class="navbar-tool-icon-box"><i class="navbar-tool-icon ci-user"></i></div> </a> login.html <div class="modal fade" id="signin-modal" tabindex="-1" role="dialog"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <!-- content --> </div> </div> </div> -
How to change data inside table django?
I have been creating clone of Twitter. User can register, login, write tweets. Tweet modal is here: class TweetModel(models.Model): text = models.TextField(max_length=300, blank=False) created_at = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True) username = models.CharField(max_length=100, blank=True) def __str__(self): return f'{self.username}: {self.text[0:15]}' Once user changes his/her username, I want to change username in the tweets they write also. How can I handle this? Thank you. -
MultiValueDictKeyError at /categories 'category'
Models.py #the category class class Category(models.Model): category = models.CharField(max_length=64) def __str__(self): return self.category class Listing(models.Model): title = models.CharField(max_length=64, default="") bid = models.ForeignKey(Bid, on_delete=models.CASCADE, related_name="listing", default=None,) description = models.TextField(default="") image_url = models.CharField(max_length=200, default="") date = models.DateTimeField(default=timezone.now) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="listings", default="") is_closed = models.BooleanField(default=False, blank=True, null=True) watchlist = models.ManyToManyField(User, blank=True, related_name="watching") owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="listing", null=False, blank=True, default="") def __str__(self): return self.title Views.py *This is where I think the problem is because i'm not very familiar with the methods, and this is where it points out the error. The choose_category page just gives you a form with the POST method to select the category and then I'm trying to submit the form to my category page. def choose_category(request): categories = Category.objects.filter() return render(request, "auctions/choose_category.html", { "categories":categories }) def categories(request): if request.method == "POST": categories = Category.objects.get(category=request.POST['category']) return render(request, "auctions/categories.html", { "categories": categories }) choose_category.html {% extends "auctions/layout.html" %} {% block body %} <form action="{% url 'categories' %}" method="post"> {% csrf_token %} <div class="form-group"> <label for="categories">Category</label> <select class="form-control" name="categories" id="categories"> {% for category in categories %} <option>{{category}}</option> {% endfor %} </select> </div> <input class="btn btn-primary" type="submit" value="Done"> </form> {% endblock %} categories.html % extends "auctions/layout.html" %} {% block body %} … -
set display to none if string is not translated
I am writing a translation program and I am trying to implement a functionality where, If the translation string in the .po file is empty ( msgstr "" ) the parent elements visibility will be set to none. As an example, if I have this template code: {% language target_language %} <td><p> {% translate Hello %} </p></td> {% endlanguage %} If the target languages po file should look like this: #: translation/forms.py:10 msgid "Hello" msgstr "" then I would like to set: {% language target_language %} <td style="display: none"><p> {% translate Hello %} </p></td> {% endlanguage %} How could I go about implementing this? I have worked myself through the Django internationalization but haven't found anything to point me in the right direction. I'm using Django 3.1 and Python 3.8. Best Regards Max -
Not able to redirect to another page after clicking on submit button django
So, I have implemented a bit of post, get and update in the following code. After submitting the values into the database. The return redirect is not changing the page to UserProfile.html which in urls.py is user_profile Code urls.py path('user_profile', views.user_profile, name="user_profile"), views.py def edit_profile(request): try: # checking if the user exist in UserProfile through the logged in email id user_data = UserProfile.objects.get(emailID = request.user.email) # if request.method == "POST" and request.FILES: if request.POST.get('action') == 'post': name = UserProfile.objects.all() response_data = {} # user_img = request.FILES['user_img'] name = request.user.username emailID = request.user.email phone = request.POST.get('phone') college_name = request.POST.get('college_name') branch = request.POST.get('branch') # response_data['user_img'] = user_img response_data['name'] = name response_data['emailID'] = emailID response_data['phone'] = phone response_data['college_name'] = college_name response_data['branch'] = branch # updating the current logged in user values user_data = UserProfile.objects.get(emailID = request.user.email) if(user_data.emailID == request.user.email): UserProfile.objects.filter(emailID = request.user.email).update( name = name, emailID = emailID, phone = phone, college_name = college_name, branch = branch ) return redirect('/user_profile') except UserProfile.DoesNotExist: name = UserProfile.objects.all() response_data = {} # creating new user if request.POST.get('action') == 'post': # user_img = request.FILES['user_img'] name = request.user.username emailID = request.user.email phone = request.POST.get('phone') college_name = request.POST.get('college_name') branch = request.POST.get('branch') # response_data['user_img'] = user_img response_data['name'] = name response_data['emailID'] … -
How to access the instance of the ClusterableModel parent object from a child orderable before the orderable has been saved?
When creating orderables as children of a clusterablemodel, is there any way to access properties of the parent before that parent instance has been saved? The ParentalKey is None until the orderable instance has been saved. Maybe it's possible to pass variables to the orderable when the orderable instance is created? I want to filter the choices offered on the orderable based on the parent properties but can't find any way to do this, only one-filter-for-all. Abbreviated code from a Wagtail test project: @register_snippet class ParentSnippet(TranslatableMixin, ClusterableModel): code = models.CharField(blank=False, null=True, max_length=10) title = models.CharField(blank=False, null=True, max_length=50) .... class ChoiceListIterator(object): def __iter__(self): dropdown_list = list(ChoiceListClass.objects.values_list('code','title')) return dropdown_list.__iter__() class ChildOrderable p_key= ParentalKey( "ParentSnippet", related_name="child_items", ) choice_list=ChoiceListIterator() submenu_selector=Select() submenu_selector.choices = choice_list dropdown_test = models.CharField( blank=False, null=True, max_length=10, choices=choice_list ) panels = [ FieldPanel("dropdown_test"), ] This is fine for showing everything from the ChoiceListClass (just something to return items for this example), the dropdownlist is populated dynamically. Ideally, I want to be able to pass either the parent snippet or properties based on the parent snippet into the ChoiceListIterator constructor and then use this to filter the dropdown_list. eg choice_list=ChoiceListIterator(parent_snippet_instance) But how to access the instance of the parent object creating the orderable … -
Implement Google Indexing Api Django
I am working on a Django project where I need to implement Google Indexing Api . I want to instantly crawl and index all the api's on our site. -
Hide certain fields Django Filter Forms
I have been searching around a bit but I can't find the answer. search.html <form action="" method="get"> {{ filter.form|crispy }} <input type="submit" class="btn btn-primary" /> </form> filters.py class GameFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_expr='icontains') popularity = django_filters.RangeFilter() class Meta: model = Game fields = ['gamemodes'] together = ['name', 'releases__date'] I still want to be able to search on those fields, but I dont want to show certain fields in the filter.form. Example, I want to be able to search on popularity, but I dont want its field generated in the filter.form. Currently all fields are being shown How do I do that? -
Django page not found (404) in my core/urls.py file. Only works when the urls are rearranged
I am relatively new to Django. I've set up my URLs in my core/urls.py file this way and I do get a 404 error when I opened localhost:8000/posts/ on the browser. Code is shown here urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<slug:slug>/', views.SingleView.as_view(), name='single'), path('posts/', views.PostsView.as_view(), name='posts'), ] However, everything works fine when I reverse the slug and posts/ to make the posts come before the slug. Like this: urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('posts/', views.PostsView.as_view(), name='posts'), path('<slug:slug>/', views.SingleView.as_view(), name='single'), ] Please help me figure it out. -
How do I obtain references to other data being submitted in the Django admin?
I have a multiple-choice test app in Django 3.0. It has two models, Question and Choices # models.py class Questions(models.Model): question = models.CharField( help_text='Text of question' ) class Choices(models.Model): def clean(self): choicesSet = Choices.objects.filter(q=self.q) if ( choicesSet.count() != 4 ): raise ValidationError( "Four Choices must be provided." ) q = models.ForeignKey( Questions, on_delete=models.CASCADE ) option = models.CharField( help_text='Text of choice' ) The Admin page for Questions includes inputs for four Choices. When Choices are input, I want to make sure that a complete set of four are input at the same time. I attempted to do this with the Choices.clean() function shown, but it fails. When I enter four choices and attempt to save, each Choice returns the error "Four Choices must be provided". I think what's happening is that since the record is not successfully saved, choicesSet = Choices.objects.filter(q=self.q) returns zero because no Choices are foreign-keyed to the Question q=self.q yet. How can I obtain references to the other three Choices in the clean() function of one Choice during validation? I've read the documentation for Model validation and Form and field validation, but it's more confusing than helpful. -
custom EditProfile in Django forms, submit button not working
I created EditProfile FORMs, in my forms.py file: from django.contrib.auth.forms import UserChangeForm from korisnici.models import CustomKorisnici from django import forms class EditProfile(UserChangeForm): email = forms.EmailField(widget=forms.EmailInput(attrs={'class': 'form-control'})) first_name = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'})) last_name = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'})) phone_number = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'})) bio = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'})) phone_number = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'})) class Meta: model = CustomKorisnici fields = ('username', 'first_name', 'last_name', 'email','bio','phone_number','profile_image') def __init__(self, *args, **kwargs): super(EditProfile, self).__init__(*args, **kwargs) self.fields['username'].widget.attrs['class'] = 'form-control' self.fields['phone_number'].required = False self.fields['profile_image'].required = False self.fields['bio'].required = False After I run a default Django form in my HTML file(edit_profile.html): <div class="form-group"> <div class="container"> <div class="form"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button id="btn" class="btn" type="submit">Edit Profile</button> </form> </div> </div> </div> When I click on submit button, it is working fine, my profile page was edit and data is change in base. But when I customize my form in bootstrap, the submission button is not doing anything. Here is my bootstrap form: <form method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <label >Username</label> <input type="text" class="form-control" name="username"> </div> <div class="form-group"> <label >First name</label> <input type="text" class="form-control" name="first_name"> </div> <div class="form-group"> <label >Last name</label> <input type="text" class="form-control" name="last_name"> </div> <div class="form-group"> <label >Email </label> <input type="email" class="form-control" … -
OSError sending email django
i create a website using python and django. i have a contact me form in it , but when i click the submit button i face with an error: OSError at / [Errno 101] Network is unreachable this is my settings.py: # Email Settings EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = '587' EMAIL_HOST_USER = 'alime1@gmail.com' EMAIL_HOST_PASSWORD = '******' EMAIL_USE_TLS = True EMAIL_USE_SSL = False and this is my views.py: from django.shortcuts import render from django.http import HttpResponse from django.core.mail import send_mail from .models import Page def index(request): if request.method == "POST": name = request.POST['name'] email = request.POST['email'] message = request.POST['message'] # send an email send_mail( 'project website' + name, # subject message, # message 'alime1@gmail.com', # from email [email], # to email ) return render(request,'pages/index.html',{'name':name}) else: pages = Page.objects.all() context = { 'pages': pages } return render(request,'pages/index.html', context) and this is my form : <form action="{% url 'index' %}" class="waypoint" data-animation="pop-in" data-delay=".5s" method="post"> {% csrf_token %} <input placeholder="Name" type="text" name="name" required /> <input placeholder="Enter email" type="email" name="email" required /> <textarea placeholder="Your Message" type="text" name="message" ></textarea> <div id="success"> <div> Your message was sent successfully. Thanks!<span id="close" class="mdi mdi-close" ></span> </div> </div> <button type="submit" class="button"> Send </button> <!-- <input class="button" type="submit" id="submit" value="SUBMIT" /> … -
How do iI convert md files to HTML and render them in Django
I have some md files in an 'entries' folder in my django app folder and i wanna get them, covert them to HTML then render them. This is my util.py def get_entry(title): """ Retrieves an encyclopedia entry by its title. If no such entry exists, the function returns None. """ try: f = default_storage.open(f"entries/{title}.md") return f.read().decode("utf-8") except FileNotFoundError: return None def convert_md(filename): """ Converts given md file to html """ #file= f"{filename}.md" file= default_storage.open(f"{filename}.md") md= file.read() html= md.markdown(md) return html This is my views.py def wiki(request, topic): if util.get_entry(topic) != None: html= util.convert_md(topic) return render(request, "encyclopedia/pages.html", { "title": topic, "body": html }) else: return render(request, "encyclopedia/pages.html", { "title": "ERROR", "body": "THIS PAGE IS NOT AVALIABLE." }) I also have... path("wiki/<str:topic>", views.wiki) in my urls.py but I'm still getting a FileNotFoundError at /wiki/Python error