Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I set the default value for instance variable?
class SafetyValveSerializer(serializers.ModelSerializer): # Instead of exposing the state's primary key, use the flag field state_flag = serializers.SlugRelatedField(source='sv_state', queryset=SafetyValveState.objects.all(), slug_field='flag') class SafetyValveState(models.Model): sv_state_key = models.AutoField(primary_key=True) flag = models.IntegerField(unique=True) description = models.CharField(max_length=50) How do I set the default value of state_flag to 0 when call SafetyValveSerializer partially not passing state_flag? -
How can i in Django Oscar filter EAV Attributes in Frontend?
In Django Oscar when i add a new product class i can insert new dynamic attributes. This is a implementation from Django EAV. Now i want in frontend to view a form with all EAV Attributes and when this form is submit then Django Oscar filter products after this EAV attributes. Have anyone a idea how i can implement this? I try nothing till yet. I know that i can filter with products.objects.filter(eav_attributename='blabla') but how can i make a form with all EAV Attributes? When user submit it how can a filter products after several EAV fields? -
Django - Annotate Count() of distinct values grouped by Date
I have the following Model: class Visualization(models.Model): .... user: FK user start_time: DATETIME product: FK product .... Example data: | User ID | Start Time | Product ID | | :----: | :----------: | :-------: | |1|2021-09-07 14:03:07|3| |2|2021-09-07 13:06:00|1| |1|2021-09-07 17:03:06|1| |4|2021-09-07 04:03:05|5| |1|2021-09-07 15:03:17|4| |1|2021-09-07 19:03:27|1| |2|2021-09-06 21:03:31|3| |1|2021-09-06 11:03:56|9| |1|2021-09-06 07:03:19|9| I need to get the active users for days, the active users are those who made at least one reproduction, if a user made many reproductions, it still counts as 1. A correct answer would be: | Total | Date | | :----: | :----------: | |3|2021-09-07| |2|2021-09-06| First I make an annotation a Truncate of StartTime to keep only the Date and then I make Group By for this annotation, so far everything without problems. The problem is when I try to count the Users since they have repetitions. I have tried to count the User_id with Distinct = True, but the numbers still give me bad, also by a very big difference. I also tried grouping by user_id and period (annotation of Truncate StartTime) but it didn't work for me either -
how can i replicate admin.TabularInline outside of the admin (on the user side?)
Given a mode A and a model B that has a field with a many to many relationship with model A, I am trying to allow users creating an object of model B to also create an object of model A inline/on-the-fly just like TabularInline allows you to do on the admin. -
React Django Auth
I'm trying to login thru ReactJS app and here is the error I get: Access to XMLHttpRequest at 'http://localhost:8000/auth/login/' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute. even though I added CORS_ALLOW_CREDENTIALS: True to the settings.py: """ Django settings for config project. Generated by 'django-admin startproject' using Django 3.2.6. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] CORS_ALLOWED_ORIGINS = ["http://localhost:3000"] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "corsheaders", 'rest_framework', 'service_get_data', 'background_task', 'service_append_data', ] MIDDLEWARE = [ … -
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 …