Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - render django-filter(filterset) bar with crispy forms
I'm quite new and would appreciate some help. I created a filter bar (with filterset from th django-filter module) but I'm unable to render it with crispy forms. Are crispy-forms compatible with django-filter? I tried it and crispy works well with all my other forms and modelforms, but it seems like django-filter rejects to render in bootstrap. HTML <div class="row"> <div class="col"> <div class="card card-body"> <form method="get"> ****{{ myFilter.form}}**** */tried also {{ myFilter.form|crispy}} {{ myFilter.form.variablefieldhere|as_crispy_field}}** <button class="btn btn-primary" type="submit"> Search</button> </form> </div> </div> </div> Filter.py import django_filters from .models import log class logFilter(django_filters.FilterSet): class Meta: model = log fields = { 'varfliedhere': ['icontains'], 'varfliedhere': ['icontains'], 'varfliedhere': ['icontains'], 'Boolean varfliedhere': ['exact'], } Shoul i try to set the FormHelper in forms? But in that case, how do i render it in crispy? In the others forms i rendered them 1 by 1 as: {{ myFilter.form.variablefieldhere|as_crispy_field}} and works, but can't understand how to solve this problem. Thanks in advance! -
Django3.2.6 : TypeError: 'NoneType' object is not callable
I am learning this Django Framework from this summer. I have get the error <TypeError: 'NoneType' object is not callable>. I am trying to narrow down the problem. However, after I have delete a lot of code, I still cannot figure this out from the most simple code. My code is showed as below. admin.py from django.contrib import admin from rest_framework.renderers import AdminRenderer from .models import Car @admin.site.register(Car) class CarAdmin(admin.ModelAdmin): list_display = ('id', 'brand', 'model') models.py from django.db import models from django.contrib import admin class Car(models.Model): brand = models.TextField(default='Honda') model = models.TextField(default='EK9') class Meta: db_table = 'car' def __str__(self): return self.model the error LeodeMacBook-Pro:sharky leo$ python ./manage.py runserver /Users/leo/opt/anaconda3/lib/python3.8/site-packages/environ/environ.py:628: UserWarning: /Users/leo/Documents/python_test/leo_first_python_side_project/sharky/sharky/mysite/.env doesn't exist - if you're not configuring your environment separately, create one. warnings.warn( /Users/leo/opt/anaconda3/lib/python3.8/site-packages/environ/environ.py:628: UserWarning: /Users/leo/Documents/python_test/leo_first_python_side_project/sharky/sharky/mysite/.env doesn't exist - if you're not configuring your environment separately, create one. warnings.warn( Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/leo/opt/anaconda3/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/Users/leo/opt/anaconda3/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/Users/leo/django/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/leo/django/django/core/management/commands/runserver.py", line 114, in inner_run autoreload.raise_last_exception() File "/Users/leo/django/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/Users/leo/django/django/core/management/__init__.py", line 375, in execute autoreload.check_errors(django.setup)() … -
How to get name from id of ForeignKey in django?
Issue When I call {{cats}} I'm getting an id, How can I get the category name in the same place? My Html File {% extends 'base.html' %} {% load static %} {% block title %} Blogue | {{cats}} {% endblock %} {% block content %} Views.py def CategoryView(request, cats): category_posts = Post.objects.filter(category=cats) return render(request, 'categories.html', {'cats':cats.title(),'category_posts':category_posts}) Urls.py urlpatterns = [ ......... path('category/<str:cats>/', CategoryView, name='category-list'), ] Models.py class Category(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name def get_absolute_url(self): return reverse('home') class Post(models.Model): title = models.CharField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() post_date = models.DateField(auto_now_add=True) category = models.ForeignKey(Category ,max_length=60 ,default='Others', on_delete=models.CASCADE, related_name= 'cats') def __str__(self): return self.title + ' | ' + str(self.author) def get_absolute_url(self): return reverse('article-detail', args=(str(self.id))) I've tried changing using the category class but not getting the correct output yet, and also tried using 'categories_post' but that too didn't help. Any help would be appreciated! Thank You in Advance. -
Deploying two Django projects in the same port in sub directories NGINX + GUNICORN
I have a Django project running with NGINX, GUNICORN and SUPERVISOR. I want to deploy another Django project in a sub-directory, in the same domain and port. -
504 browser request timed out- Ajax+django
Browser is queuing my ajax requests and the requests are being timed out if they are not getting a response under 1 minute(TTFB>1). I tried changing timeout and setTimeout values in ajax . I checked if it is Nginx server timeout and increased the proxy_timeout values still there is no result. Can someone please explain how can I increase browser timeout values. -
In Django project, styling through JavaScript is not working
I am new in Django and Python. During working, I am trying to fix the problem all day long but failed. Everything seems okay and working on w3schools and others testing sites also. Here is the two line code from index.js- alert(window.innerWidth); document.getElementById("body2").style.color = "#0000ff"; first line shows the window's width but the second line doesn't do anything. I have tried to change color, font-size, weight...etc but nothing works where everything works fine on inline, internal or external css. Only problem on styling from JS. Here, Head section of base.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>CSP: Home</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> <link rel="shortcut icon" type="image/png" href="{% static 'favicon.png' %}"> <link rel="stylesheet" type="text/css" href="{% static 'base.css' %}"> {% block ecss %} {% endblock %} </head> I have linked index.js and index.css through ecss block.... -
Random database disconnects with Django and Postgresql in AWS
I'm trying to get to the bottom of a problem with Django and database connection errors. At this point I'm after debugging tips as I think the symptoms are too non-specific. Some background - I've been using this stack, deployed in AWS for many years without issue: Ubuntu (in this case 20.04 LTS) Nginx Uwsgi Postgresql (v12 in RDS - tried v13 but same errors) An AWS load balancer sends traffic to the Ubuntu instance, which is handled by Nginx, which forwards on to Django (3.2.6) running in Uwsgi. Django connects to the database using psycopg2 (2.9.1). Normally this setup works perfectly for me. The issue I have it that the database connection seems to be closing randomly. Django reports errors like this: Traceback (most recent call last): [my code...] for answer in q.select_related('entry__session__player'): File "/usr/local/lib/python3.8/dist-packages/django/db/models/query.py", line 280, in __iter__ self._fetch_all() File "/usr/local/lib/python3.8/dist-packages/django/db/models/query.py", line 1324, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/usr/local/lib/python3.8/dist-packages/django/db/models/query.py", line 51, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "/usr/local/lib/python3.8/dist-packages/django/db/models/sql/compiler.py", line 1173, in execute_sql cursor = self.connection.cursor() File "/usr/local/lib/python3.8/dist-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.8/dist-packages/django/db/backends/base/base.py", line 259, in cursor return self._cursor() File "/usr/local/lib/python3.8/dist-packages/django/db/backends/base/base.py", line 237, in _cursor return self._prepare_cursor(self.create_cursor(name)) File "/usr/local/lib/python3.8/dist-packages/django/db/utils.py", line 90, in __exit__ … -
I am trying to integrate RazorPay Payment System
The below code of razorpay docs gives in the value of the client-user and the amount of money to be paid. How can I take the amount and username saved in a model in the database.? Like, I have an table of orders and a function is defined inside the Model Class to get the total amount of the whole order(eg. I have two items to buy and the 'get_total' function returns me the total order amount) if request.method == "POST": name = request.POST.get('name') amount = 50000 -
Error while giving following command python manage.py makemigrations
I am giving following command python manage.py makemigrations, but I am getting the error, from employee.forms import EmployeeForm ModuleNotFoundError: No module named 'employee.forms' I am not able to rectify the error please guide -
DRF: Set ChoiceField default programmatically from DB query
I asked a similar question here about setting the default value of a TextChoices field on a model. Now I'm taking it to the next level. I've moved the choices settings from the model to the serializer ChoiceField. The site is Django/DRF/django_tenants backend with Vue frontend. I want the front/backends to be using the same set of choices and, just as important, the same default values. So I created an OptionGroup table. Here are two sample rows from that table (some options omitted): { "results": { "id": 1, "name": "payment_method", "defined_in": "option_table", "default_option": "5", "options": [ { "id": 2, "name": "Bank Transfer", "value": "2" }, { "id": 5, "name": "Credit Card", "value": "5" }, { "id": 8, "name": "PayPal", "value": "8" } ] } } { "results": { "id": 3, "name": "invoice_type", "defined_in": "class", "app_label": "invoices", "choices_class": "InvoiceType", "default_option": "standard", "options": [ { "name": "Standard", "value": "standard" }, { "name": "Retainer", "value": "retainer" }, { "order": 1, "name": "Estimate", "value": "estimate" } ] } } The first one (defined_in = "option_table") has its options defined in a related Option model. The second one has its options defined in a subclass of TextChoices in the backend code. In addition to keeping … -
Parse GraphQL query to find fields to be able to prefetch_related?
When using DjangoListObjectType from graphene_django_extras, I can define a custom qs property on a SearchFilter. The qs function has the object as its only argument, and through that I can get the request, and in turn the query string which includes the queried fields. Before hacking together my own parser to get these fields, am I going about this the wrong way? Or is there something else out there? The idea is to have quite a rigid approach, as we have 7 types of paginated list types with fields that result in a few unnecessary database hits, so we want to prefetch a few fields. Graphene has a dataloader approach which kind of looks right, but more complicated than just prefetching them at the qs stage. -
Django, just showing once when I use multiple forms with rich editor
I am creating comment area and reply to comment area for users. And I using django-ckeditor for this but there is a problem. When I add "reply form" just showing once in the page. Not showing other forms. The reply system its works just its not showing ckeditor(Rich editor). I am add some photos for better understanding: second form in same page: inspect of first form: my Models: class UserMessages(models.Model): postMessages = RichTextUploadingField(null=True, verbose_name="Message") post = models.ForeignKey( UserPosts, on_delete=models.CASCADE, verbose_name="Linked Post", null=True) username = models.ForeignKey( User, on_delete=models.CASCADE, verbose_name="Username", null=True) replies = models.ForeignKey("self", blank=True, null=True, on_delete=models.CASCADE) my Forms: class MessageForm(forms.ModelForm): class Meta: model = UserMessages fields = ("postMessages",) widgets = { "postMessages": forms.TextInput(attrs={"class":"form-control"}), #And I tried this but not works.. class ReplyFormMessage(forms.ModelForm): class Meta: model = UserMessages fields = ("replies",) my HTML: <form method="POST" > {% csrf_token %} {{form.media}} {{ form }} <input type="hidden" name="replies_id" value="{{ message.id }}"> <input type="submit" value="Reply" class="btn btn-default"> </form> as for me, ckeditor just using one id for all form in page. So, do you have an idea? -
Django gabarit tag - how to return a variable as string instead of text
I am working on a django project. I came accross a trouble. I have an instance somewhere in my view called roadnetwork. In my html(or js) template, I would like to get this instance name via {{roadnetwork.name}} as a string and not a text. Any help is appreciated! -
Django POST request pending issues (AJAX) and doesn't come out on the terminal
move post request status stays pending The forward button supposed to send post request(move) and receive by the web server but as in the image nothing come out on the terminal when I pressed the button. here's the involved code: <button class="btn btn-primary btn-lg btn-block"onmousedown="runScript(this)" onmouseup="end()" name="UP" value="up" id="buttonUp" style="margin-bottom: 5px">FORWARD</button> function runScript(button) { counter = setInterval(function(){ $.ajax({ url: 'move', //The URL you defined in urls.py type: "POST", data: { UP: button.value, 'csrfmiddlewaretoken': '{{ csrf_token }}', }, success: function(data) { //If you wish you can do additional data manipulation here. // wrapper.innerHTML = count + "bit" + data;\ wrapper.innerHTML = "Ultrasonic: " + data; if (data < 5) { userInput.innerHTML ="Object Close"; } else { userInput.innerHTML =""; } count ++; } }); }, 500); } -
Django: Continue the execution of Cron job even if my server restarts
I have a cron job in Django and I want that to be executed at its scheduled time. But the problem is in between that if my server restarts then the scheduled job is not persisted and is not executed. I want that job to be persisted and executed even if my server is restarted. Thanks in advance! -
Django CKEditor 5 frontend. Submit stops working when I add {{ form.media }} to template
I'm following this guide to set up SKEditor5 for my django project. It works fine in Admin. However, for it to work in my frontend form, I need to add {{ form.media }} and my Submit button simply stops doing anything. Note, without the {{ form.media }}, I do not see SKEditor on the frontend but Submit works just fine. There's very little information about Django CKEditor5 out there. Maybe CKEditor5 only work in Admin and not made for front end? Or maybe I should replace {{ form.media }} with something else? Please, help. models.py from django.db import models from django import forms from django_ckeditor_5.fields import CKEditor5Field from PIL import Image from django.contrib.auth.models import AbstractUser class Article(models.Model): title = models.CharField(max_length=100) content = CKEditor5Field('Content', config_name='extends') def __str__(self): return self.title views.py from django.views.generic import ListView, CreateView from .models import Article class IndexView(ListView): model = Article template_name = 'test_app/index.html' context_object_name = 'articles' class ArticleCreateView(CreateView): model = Article fields = '__all__' template_name = 'test_app/create.html' success_url = '/' create.html <form method="POST" action=""> {% csrf_token %} <p>{{ form.media }}</p> <p>{{ form.as_p }}</p> <input type="submit" value="Add Article"> </form> urls.py from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include urlpatterns … -
How to set CSRF token in Django Ajax call in case of a url submit outside a Django form?
I'm trying to make an AJAX call to update the rendered data when clicking on an icon like below. However, it always returns: Forbidden (CSRF token missing or incorrect.): /shuffle_pollers What I understand from the Django doc is that I could set the token within the form, but in my case I don't use a form to call the url. So how can I implement the CSRF token into the Ajax call? // Refresh pollers on shuffle click $('#shuffle-icon').click(function () { // Get the CSRF token function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getCookie('csrftoken'); // Ajax handler $.ajax ({ url: '/shuffle_pollers', type: 'post', mode: 'same-origin', success: function () { $('.pollerfeed').removeChild(); } }) }) <div class="shuffle-icon-ctn"> <img id="shuffle-icon" src="{% static 'images/shuffle-logo.svg' %}"> </div> def shuffle_pollers(request): if request.method == 'POST': print('Triggered') return request -
How to use data from filter() in template in django python
i want know how can i use data in template here is the model: class NewOrders(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) items=models.TextField(null=True) and here is how i am getting data in view using filter method: def Myorders(request): #show my orders morder = NewOrders.objects.filter(user=request.user) print(morder) context={ 'my_orders':morder, } return render(request,'myorder.html',context) which gives my output like this: <QuerySet [<NewOrders: 21>]> now i want this items in model in template: {% for entity in my_orders %} <p> item name: {% entity.items %}</p> {% endfor %} but after dong this i get error: entity.items', expected 'empty' or 'endfor'. Did you forget to register or load this tag? -
How to dynamically filter using a ListView
I want to dynamically filter my results in the front-end using only my ListView class with a search input. It should first display the entire list of users, but when something gets typed in the search input it should filter the results based upon that input. What is the best/shortest way to do this using only my classBased View? My current code: Template: <div class="card mt-3"> <div class="card-body"> <form action="" form="get"> <input data-url="{% url 'klantbeheer' %}" class="zoekklanten" name="q" type="text" placeholder="Zoek op contactnaam..."> </form> {% if object_list %} <div class="single-table"> <div class="table-responsive"> <table class="table text-center"> <thead class="text-uppercase bg-dark"> <tr class="text-white"> <th scope="col">Bedrijfsnaam</th> <th scope="col">Contactnaam</th> <th scope="col">Locatie</th> <th scope="col">Actie</th> </tr> </thead> <tbody> {% for user in object_list %} <tr> <td>{{ user.bedrijfsNaam }}</td> <td>{{ user.contactNaam }}</td> <td>{{ user.adres }}</td> <td> <a href="{% url 'klantupdaten' user.id %}"><i class="fas fa-edit"></i></a> <a href="#" data-url="{% url 'klantverwijderen' user.id %}" class="deletegebruiker" data-bs-toggle="modal" data-bs-target="#dynamic-modal"><i class="fas fa-trash-alt"></i></a> </td> </tr> {% endfor %} </tbody> </table> </div> </div> {% else %} <p>Geen gebruikers gevonden</p> <p> <a href="{% url 'klantaanmaken' user.id %}" class="btn btn-primary">Maak klant aan</a> </p> {% endif %} </div> </div> View: class ManageUserView(SuperUserRequired, ListView): model = User template_name = 'webapp/klant/beheerklant.html' #Query based upon contactName def get_queryset(self, query): #Contactnaam bevat QUERY EN … -
Access djagno model before creation one
Consider the following application structure. You have two models: Recipe and Ingredient, which are related to each other (obviously, each recipe has some ingredients and many ingredients can be in some recipes). Note, that you have decided to use M2M (many to many) relation between these two models with an explicit intermediate model -- RecipeIngredient -- which also contains one additional field named amount. With all of the above, I have only two question for you. How would you save Recipe instance with multiple ingredients through django shell if Recipe instance still is not created. You can consider, that you already have ingredients in your DB. And the second one, how one can access amount field while creating a recipe? If you are confused, I can reformulate the question. How you would save a recipe with specified ingredients and their amount? (If there is a simple model relation I can use, please, describe it). from django.db import models from django.contrib.auth import get_user_model from django.core.validators import MinValueValidator, MaxValueValidator User = get_user_model() class Recipe(models.Model): author = models.ForeignKey( User, on_delete=models.CASCADE, related_name='recipies', verbose_name='Author of a recipe' ) name = models.CharField(max_length=200, verbose_name='Name of a recipe') image = models.ImageField() text = models.TextField(verbose_name='Description of a recipe') ingredients … -
Django: redirect the user from the login page if he has already logged in
I want to redirect the user from the login page if he is already logged in; this means that the user who logged in will no longer have access to the login page. the login page looks something like this: example.com/login this is my code in view.py: def login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: logIn(request, user) return redirect('/') else: messages.info(request, 'username or password is wrong') context = {} return render(request, 'account/login.html', context) -
Django authentication with firebase?
How can I override default Django authentication with firebase authentication with Phone, Google, Facebook, Email? I planned to build a mobile application where I used firebase for authentication ( why firebase because with this I can easily access cloud databases, more control over ads, analytics, testing, and distribution ) But the rest of the things I planned to used Postgres / MongoDB and Django ( why Django it's easy to build pre-build admin panel and manage ) But the problem is that how can I control my Django authentication because 90 to 95 % of databases are stored in Django so I also need that authentication so we can get more control over data with security Like we have a comment, like, a poll system in my application, and the data are stored in Django. So if we have a users model in Django so we can easily map the data in Django otherwise it's taken a lot of effort and it also compromises the security. Note: there might be one solution is there but I don't want to use that because it makes an application is more complex and it also has security issues. The solution is to create … -
run haversine formula on MariaDB server using annotate() in django orm
Hii I trying to run the Haversine formula on the MariaDB base on my model the model is class MeteorologicalSite(models.Model): lat = models.DecimalField("Latitude", max_digits=17, decimal_places=15) lon = models.DecimalField("Longitude", max_digits=17, decimal_places=15) class Site(models.Model): lat = models.DecimalField("Latitude", max_digits=17, decimal_places=15) lon = models.DecimalField("Longitude", max_digits=17, decimal_places=15) and this is the Haversine function def Haversine_formula(self, site): from django.db.models.functions import Cos, Sin, ASin, Sqrt, Radians lat1 = Radians(site.lat) lon1 = Radians(site.lon) lat2 = Radians(F("lat")) lon2 = Radians(F("lon")) r = 6372.8 sql_haversine_formula = 2 * r * ASin( Sqrt( Sqrt( Sin((lat1-lat2)/2)**2+ Cos(lat1)* Cos(lat2)* Sin((lon1 - lon2)/2)**2 ) ) MeteorologicalSite.objects.filter(radiation=True)\ .annotate(mycolumn=sql_haversine_formula) and it doesn't run it return <django.db.models.query.QuerySet object at 0xffff57b99ca0> I tried to use lat and lon for 1 and 2 as Decimal directly and it still doesn't work so I understand that my problem is in the way I use annotate or in me sql_haversine_formula Does anyone have an idea why this does not work? sorry for my English -
How to update value when i used only request.POST method for save data into database.? i did not use any form class
enter image description here model for database. enter image description here data save method. -
Make models in admin site appear only in debug mode otherwise display one model
I want to make my models appear in admin site only when debug variable is set to True, when debug is set to False I only want to display one model I am looking for an elegant way to implement this I thought I could do something like this: if not DEBUG: admin.site._registry = {} admin.site.register(Model 1) But where does this code should live? I want it to execute after execution of all admin.py modules from all applications where models registration takes place. To sum it up DEBUG = TRUE Admin site shows: Model 1 Model 2 Model 3 DEBUG = FALSE Admin site shows: Model 1