Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-filter: error: Enter a list of values when using the LinkWidget
Perhaps one of you could help me out with “Django-filter”. In my template an error shows up 'Enter a list of values’ when I want to use the LinkWidget. When I use the LinkWidget with django_filters.AllValuesMultipleFilter then in my template it shows the word "all" and the ID’s of te field categories When I use it with the Django Form widget “widget=forms.CheckboxSelectMultiple)” then I’m able to filter the data. What’s wrong with my code? Thanks. Krgds. # file: filters.py from portfolio.models import Project,Category,Client import django_filters from django_filters.widgets import LinkWidget from django import forms # error: Enter a list of values. class ProjectFilter(django_filters.FilterSet): categories = django_filters.ModelMultipleChoiceFilter(queryset=Category.objects.all(),# this a ManyToManyField widget=django_filters.widgets.LinkWidget) class Meta: model = Project fields = ['categories' ] # shows "all" and the ID’s of te field categories class ProjectFilter(django_filters.FilterSet): categories = django_filters.AllValuesMultipleFilter(widget=django_filters.widgets.LinkWidget) class Meta: model = Project fields = ['categories' ] -
not able to understand Django pagination code
related to pagination it is running fine i have mentioned my problem below <nav aria-label="Page navigation example"> <ul class="pagination-sm"> <ul class="pagination"> <li class="page-item"> {% if users.has_previous %} <a class="page-link" href="?page={{ users.previous_page_number }}" aria-label="Previous"> <span aria-hidden="true">&laquo;</span> {% endif %} </a> </li> {% for i in users.paginator.page_range %} {% if users.number == i %} <li class="page-item active"><a class="page-link">{{ i }}</a></li> {% elif i > users.number|add:'-4' and i < users.number|add:'4' %} <li class="page-item"><a class="page-link" href="?page={{ i }}">{{ i }}</a></li> {% endif %} {% endfor %} <li class="page-item"> {% if users.has_next %} <a class="page-link" href="?page={{ users.next_page_number }}" aria-label="Next"> <span aria-hidden="true">&raquo;</span> {% endif %} </a> </li> </ul> i do not understand this line given below....how it can be possible that this condition will true for any value of "i" or for any value of "user.number" please i request to explain this line in detail {% elif i > users.number|add:'-4' and i < users.number|add:'4' %} -
Django tables2, select row and get selected values
I Have a class based view, where I display crispy form and table, so i can use the form, and see the model object in the table. My problem its that i want to select one or more items from the table, and then pass the values of the row to the crispy form. tables.py class ResultCenterTable(tables.Table): selection = tables.CheckBoxColumn(accessor='pk') class Meta: model = ResultCenter row_attrs = { "data-id": lambda record: record.name } fields = [ 'code', 'name', 'year', 'company', ] In my table I use selection to have a checkbox column so I can select, but it don't get the data of the row HTML Template <div class="container-fluid mt-5 align-items-center w-85"> <div class="card shadow align-items-center"> <div class="card-header" style="width: 100%;"> <h2>Centro de resultados</h2> </div> <div class="card-body w-100" > {% crispy form %} </div> </div> <br> <form method='GET'> {{ filter.form }} <input type='submit' value='Buscar' /> <a href='{{ request.path }}' >Limpiar</a> </form> <form method="get"> {% csrf_token %} {% render_table table %} <input type="submit" value="Importar"/> </form> </div> Views.py class ResultCenterList(ListView, FormView): model = ResultCenter form_class = ResultCenterForm success_url = reverse_lazy('maintainers:result_center') success_message = 'Centro importado correctamente' template_name = 'maintainers/user/result_center_list.html' def get_context_data(self, **kwargs): context = super(ResultCenterList, self).get_context_data(**kwargs) filter = CompanyFilter(self.request.GET, queryset=self.object_list) table = ResultCenterTable(filter.qs) django_tables2.RequestConfig(self.request, … -
Django how to set (return) default values for values_list if an object not exists?
I want to set an empty string for each field in specified values_list if the object not exists. Example code 1: data = list(MyClass.objects\ .values( "field_1", "field_2", "field_3")\ .filter(id__in=(1, 2,))\ .values_list( "field_1", "field_2", "field_3")) Example output 1: [('obj_1_val_1', 'obj_1_val_2', 'obj_1_val_3'), ('obj_2_val_1', 'obj_2_val_2', 'obj_2_val_3')] In case 1: The objects with id 1 and 2, both exists. Then we'll to have a list with 2 tuples. Example code 2: data = list(MyClass.objects\ .values( "field_1", "field_2", "field_3")\ .filter(id__in=(1, 3,))\ .values_list( "field_1", "field_2", "field_3")) Example output 2: [('obj_1_val_1', 'obj_1_val_2', 'obj_1_val_3')] In case 2: Just the object with id 1 exists. The object with id 3, NOT exists. Then we'll to have a list with 1 tuple. Then if some object(s) not exists, I want to return like this: [('obj_1_val_1', 'obj_1_val_2', 'obj_1_val_3'), ('', '', '')] -
Reload django variable with ajax
I would like to change the value of a django variable with Ajax from template. View.py def myview(request): myvariable = 'initial' if request.POST: myvariable = 'success' return JsonResponse('OK', safe=False) return render(request, 'template.html') template.html: <div id="variable">{{myvariable}}</div> <input id="button" type="submit" value="click here"/> <script> $("#button").submit(function () { $.ajax({ method:'POST' success: function () { $("#variable").load(location.href+" #variable>*",""); } }); } </script> the POST request is well received by django and the value is change successfully however the value in the template don't change. Any idea ? Strange things, I noticed after the POST request there is two GET request at the same time [05/Feb/2021 18:28:16] "POST /test HTTP/1.1" 200 4 [05/Feb/2021 18:28:16] "GET /test HTTP/1.1" 200 24388 [05/Feb/2021 18:28:16] "GET /test HTTP/1.1" 200 24388 -
django delete_offer() missing 1 required positional argument: 'id'
This is my first django project where I want to implement crud functions. I have an issue when I want to implement the delete function. Any help is appreciated! error: TypeError at /dashboard/ delete_offer() missing 1 required positional argument: 'id' html: <td class="btn column2"><a href = "{% url 'delete' contact.id %}" >Del</a></td> view: def delete_offer(request, id): delete_pon = Contact.objects.get(id = id) delete_pon.delete() return redirect('dashboard') urls: path('dashboard/', delete_offer, name = 'delete'), -
How to make a block to appear on the page after 3 seconds? CSS
I am working on developing a website using Python's Django framework. At the frontend part, I am trying to make a division block to appear 3 seconds after you have accessed the page. I'll share with you my code: .computerScienceContent{ text-align: center; display: block; position: relative; margin-top: 10px; margin-bottom: 50px; width: 700px; margin-left: auto; margin-right: auto; padding: 30px; padding-left: 20px; animation-delay: 2s; animation: 1s linear 1s slideInLeft; } The above cod is used for displaying the block. This code is used to display it from left to right. @keyframes slideInLeft { 0% { transform: translateX(-100%); } 100% { transform: translateX(0); } } This is the django code from the html that I am trying to displaying with delay. <div class="computerScienceContent"> {% for cat in category %} <div class="csDivContent" id="slide"> <div id="slide"> <h4>{{ cat.name }}</h4> <img src="{{ cat.img.url }}" alt="image" class="img"> </div> </div> {% endfor %} </div> Basically, I want the block to be displayed 3 seconds after I access the website, one entry at a time, from left to right (there are only 4 entries). If anybody can help, I will be very happy! Thank you so much for your time ! -
Override Django model save method with many-to-many relations
I tryed to fill automatically field 'final_price' in model Cart but it doesn't change to nessasary value(in Admin) when I save it. But when I save created object again, it works. What should I do to save it immidiately when obj is created? class Cart(models.Model): owner = models.ForeignKey(User, verbose_name='Владелец корзины', on_delete=models.CASCADE) products = models.ManyToManyField(CartProduct, verbose_name='Продукты', blank=True, related_name='related_cart') total_products = models.PositiveIntegerField(default=0, verbose_name='Кол-во продуктов') final_price = models.DecimalField(max_digits=9, decimal_places=2, default=0, verbose_name='Общая цена корзины') def save(self,*args,**kwargs): if not self.id: super(Cart,self).save(*args,**kwargs) self.final_price = sum([fp.final_price for fp in self.products.all()]) super(Cart,self).save(*args,**kwargs) -
Method based admin filter
I would like to filter Events by a number of registered users. So I created method in EventAdmin class, which returns number of registered users. #admin.py @admin.register(Event) class EventAdmin(admin.ModelAdmin): list_display = ('name','registered_users') list_filter = ('registered_users') def registered_users(self, obj): link = reverse("event-users", args=[obj.id]) return format_html('<a href="{}">{}</a>', link, obj.user.all().count()) If I remove property “registered_users”from list_filter project works fine. But when I want to have also filter for registered users and I add “registered_users” to list_filter I get the following error: <class 'web.admin.EventAdmin'>: (admin.E116) The value of 'list_filter[1]' refers to 'registered_users', which does not refer to a Field. How can I solve this issue? -
how fetch seperate data from multiselectfield in django ORM?
I use in product model, below code : SIZE_CHOICES = ( ('4x3', '4x3'), ('2.5x3.5', '2.5x3.5'), ('2x3', '2x3'), ('1.5x2.25', '1.5x2.25'), ('1x4', '1x4'), ('1x3', '1x3'), ('1x2', '1x2'), ('1x1.5', '1x1.5'), ('50x100', '50x100'), ('50x85', '50x50'), ) and size = MultiSelectField(choices=SIZE_CHOICES, default='4x3') when I use below code : {{product.size}} the template show all size blow by blow, like this : 4x3, 2.5x3.5, 2x3, 1.5x2.25, 1x4, 1x3, 1x2, 1x1.5, 50x100, 50x50 How can I access to any data on one field in multiselectfield by django template ? -
Django ModelViewSet Method \"DELETE\" not allowed even when providing ID in the URL as required for detail views
I am using ModelViewSet for a CustomUser(AbstractBaseUser) model. Every other action is working except Destroy. This is my URL: router.register(r'profile', UserDetailView, basename='user_detail') As per the DefaultRouter() convention, I'm using this URL:127.0.0.1:8000/api/auth/profile/f7b5bcbe-7c92-494d-a3a2-a07e686b6e63/ with 127.0.0.1:8000/api/auth/ as the prefix. The authorization token is in its header. Here, I'm using UUID field as the ID field. When I'm calling the URL with DELETE method in postman, it's returning: { "detail": "Method \"DELETE\" not allowed." } I don't understand what is wrong here! Generally this message is shown if an ID is not provided in the URL for the detail view. But, here I'm providing ID. What is wrong here? -
nginx seems to be writing files in collect_static/CACHE every minute
I've a django website set up using gunicorn + nginx + memcached. Not sure when it started, but I'm finding new css and js files in .../collect_static/CACHE/css and .../collect_static/CACHE/js every minute, like output.2fde5b60eff0.css. These new files are owned by root www-data, unlike the original files that are copied from development to production after running collectstatic which are owned by the user id used to copy the files. I use django.contrib.staticfiles.storage.ManifestStaticFilesStorage. I have no clue if this is normal, or because of some misconfiguration. But in every few days, I need to clean the server because of this. Any suggestions what is going on here? -
how change django's validation error in html
When I submit a form and want the required error to appear when I submit a blank field, I get another error message, specifically "answer", how do I delete it? html is like this -> <ul class =" errorlist "> <li> answer <ul class =" errorlist "> <li> This field is required. </li> </ul> </li> </ ul>. image I found the options in google but it did not work i want only "This field is required." Thanks in advance models.py from django.db import models from django.core.exceptions import ValidationError class Question(models.Model): question=models.CharField(max_length=100) answer_question=models.CharField(max_length=100, default=None) def __str__(self): return self.question class Answer(models.Model): questin=models.ForeignKey(Question, on_delete=models.CASCADE, related_name="questions", blank=True) answer=models.CharField(max_length=100, null=True) def __str__(self): return str(self.questin) views.py from django.shortcuts import render from django.shortcuts import render, HttpResponse from django.http import HttpResponseRedirect from django.shortcuts import redirect from .forms import QuestionForm,AnswerForm from .models import Question,Answer import random from django.forms import modelformset_factory def home(request): form=QuestionForm if request.method=='POST': form=QuestionForm(request.POST) if form.is_valid(): form.save() return render(request, "question/base.html", {"form":form}) def ans(request): questions=Question.objects.all() form=AnswerForm() if request.method=="POST": form=AnswerForm(request.POST) if form.is_valid(): ques=request.POST.getlist("question_id") ans=request.POST.getlist("answer") for i in range(len(ques)): form=Answer(questin=Question.objects.get(id=ques[i]), answer=ans[i]) form.save() return redirect(request.path) return render(request, "question/ans.html", {"form":form, "questions":questions}) ans.html <!DOCTYPE html> <html> <head> <title>question</title> </head> <body> <form method="POST" novalidate> {% csrf_token %} {% for question in questions %} <input … -
error while executing python manage.py makemigrastions
My Models Are: from django.db import models Create your models here. class ExamCenter(models.Model): cname=models.CharField(max_length=70) city=models.CharField(max_length=60) class Student(ExamCenter): name=models.CharField(max_length=60,default=False) roll=models.IntegerField(default=False) when i Type python manage.py it generate an error but i cannot find it. the error is You are trying to add a non-nullable field 'examcenter_ptr' to student without a default; we can't do that (the database needs something to populate existing rows). 2.remember It is a Multitable inheritance. -
different procfile for Heroku and Aptible
I have this situation. I have a django project which is hosted in Heroku (Staging app) and Aptible( Production app) as well. My question is, is it possible to have separate procfile in a single project or something that tells when deploy to Heroku and when deploy to Aptible. I am using CircleCi for CI/CD. PS: following line only works for Aptible: web: NEW_RELIC_CONFIG_FILE=newrelic.ini newrelic-admin run-program gunicorn --access-logfile=- --error-logfile=- --bind=0.0.0.0:8000 --workers=1 --preload myapp.wsgi whenever I have to deploy to Heroku, I have to edit procfile as following, otherwise it gives Application Error: web: gunicorn myapp.wsgi Any suggestions will be appreciated. -
Why are exceptions not showing in Django Channels' AsyncHttpConsumer handler?
I'm using Django 2.2.10 with channels 2.3.0. I have a consumer.py that looks like this: from channels.generic.http import AsyncHttpConsumer import json class LongPollConsumer(AsyncHttpConsumer): async def handle(self, body): await self.send_headers(headers=[ (b"Content-Type", b"application/json"), ]) print("Raising exception...") raise Exception("ERROR") print("Exception raised") await self.send_body(json.dumps({"status": "all good"}).encode("utf-8")) When I run Django, and connect to the URL with my browser, the Django logs show "Raising exception...", and then they stop. No traceback of the actual exception. Makes development hard if I can't see any exceptions. Is there a way to make them appear? -
Django Rest Framework browsable API breaks when changing the port
I'm currently developing my first app with DRF and I'm pretty impressed by it and the browsable API it has build in. However, when I change the port where I host my application (both in manage.py aswell as in the runserver command), all the buttons stop working. I can still click on links to make sure resources where created, but that's about it. I also can't log in and the POST forms don't appear, which is really the most annoying part. Moreover, when I change the port back to the default 8000, it's still broken. Don't really know if I can post an example of this. It doesn't seem to depend on anything in the actual code. It just happens when I change the port. -
django ForeignKey in for loop
i will like to show data in table from two models with ForeignKey: i will use this models as example: class Reporter(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField() def __str__(self): return "%s %s" % (self.first_name, self.last_name) class Article(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateField() reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE) def __str__(self): return self.headline class Meta: ordering = ['headline'] and now i will like to have dataTable showing all Reporters last_name , and latest Article headline related to each Reporter -
Issue formatting a list of dictionaries to be used by javascript
I'm fairly new to Django, and I'm looking for the ideal way to handle data queried from GraphQL and creating HTML elements from the data to display on my website. I've been generating a list of dictionaries from product information, all of which have "id", "name", "price", etc. and passing them onto my template as is. On the template I can traverse the list with a for loop and the items correctly display within a element as {'id': '...', 'title': '...' } However on js what I see is a string containing [{'id':... What's the ideal way to generate a list of dictionaries usable by JS from this string? -
Django - make tasks in a Ptolty dictionary
I have a projects application, and each project has associated tasks (name, deadline and status) and I want to send this data to a Plotly dictionary to print a gantt in the template my views.py class projectdetail(DetailView): model = Project template_name = 'project_detail.html' slug_field = 'slug' def get_context_data(self, *args, **kwargs): context = super(projectdetail, self).get_context_data(**kwargs) '''Rescatar todos las tareas del pryecto''' project = self.get_object() progress_field = project.todo_set.all() print(progress_field) '''Gantt''' df = [dict(Task="Job A", Start= datetime.date.today().strftime("%Y-%m-%d"), Finish='2021-02-28', Resource='True'), dict(Task="Job B", Start= datetime.date.today().strftime("%Y-%m-%d"), Finish='2021-04-15', Resource='False'), dict(Task="Job C", Start= datetime.date.today().strftime("%Y-%m-%d"), Finish='2021-05-15', Resource='True'), ] colors = { 'True': '#00AA88', 'False': '#BB105A' } gantt = ff.create_gantt(df, colors=colors, index_col='Resource', bar_width=0.3) div = opy.plot(gantt, auto_open=False, output_type='div') context['graph'] = div return context my template.py <li> <span style="color:#bb105a">.Gantt </span> </li> {% if graph %} <div> {{ graph|safe }} </div> {% endif %} how can I convert the list of tasks that I get with progress_field = project.todo_set.all() into a dictionary in df? -
Why my images is not showing in heroku app of my django project? [closed]
I have developed an web application usig django framework and deployed it on the heroku platform. The code is on my GitHub platform. The problem which I'm facing is that, In my localhost I'm able to see the backgroung img which I have setup but when it's live on the heroku website it's on showing the background image only and rest is fine. Where should I have to do the changes. Is there any other tool where I have to save my media content?? Here is the directory i had set before deploy.Here is the setting file where I have given the root to the media file. This is my base.html My Local Server The actual website. -
Unable to provide windows authentication to Django UI using IIS
i have a django web app installed and hosted on IIS on server . Currently it is not provided with any authentication , but i want to give it windows authentication so that if anyone tries to access the url should provide windows username and password . made a small research on this topic and as am new towards this authentication using windows i want someone's help . So the first step i did was to modify settings.py file of Django project . As seen on question https://stackoverflow.com/questions/26881344/django-authenticate-using-logged-in-windows-domain-user i added MIDDLEWARE_CLASSES = ( ... 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.RemoteUserMiddleware', ... ) and AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.RemoteUserBackend', ) to settings.py . and next i migrated the app and ran server . restarted the app . and as per the answer for the above stack qustion it required changing or enabling of windows authentication on IIS . did as per the instruction from the answer provided in the above stack question but the issue is no error am getting and no login using windows . it runs as usual without any authentication Is there any other way to do this . Can anyone help me on this stuff -
Django PostgreSQL double index cleanup
We've got this table in our database with 80GB of data and 230GB of Indexes. We are constrained on our disk which is already maxed out. What bothers me is we have two indexes that look pretty darn similar CREATE INDEX tracks_trackpoint_id ON tracks_trackpoint USING btree (id) CREATE UNIQUE INDEX tracks_trackpoint_pkey ON tracks_trackpoint USING btree (id) I have no idea what's the history behind this, but the first one seems quite redundant. What could be the risk of dropping it ? This would buy us one year of storage. -
No buttons are appearing when they are supposed to appear - django template language
So it is supposed to show remove from cart when user has that item in their cart and add to cart when they don't, I am trying to use django template language for this but both buttons are not appearing, home function handles the page i am talking about, It passes all the variables to home.html. home.html <h1>Here are products</h1> <h1>{{ error }}</h1> <h1>Your cart currently costs ${{ price }}</h1> {% for book in books %} <h3>{{ book.name }}</h3> <img src= "/media/{{ book.image }}" alt=""> <p>{{ book.description }}</p> {% for usercart in cart %} {% if book == usercart.book %} <form method="POST" action="/removefromcartforhome/"> {% csrf_token %} <button type="submit" name="removeid" value="{{ book.id }}">remove item from cart</button> </form> {% elif book != usercart.book %} <form method="POST" action="/addtocartforhome/"> {% csrf_token %} <button type="submit" name="bookid" value="{{ book.id }}">Add to cart</button> </form> {% else %} <form method="POST" action="/addtocartforhome/"> {% csrf_token %} <button type="submit" name="bookid" value="{{ book.id }}">Add to cart</button> </form> {% endif %} {% endfor %} {% endfor %} views.py from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth.models import User from django.contrib.auth import login, logout, authenticate from django.db import IntegrityError from .models import Book, CartItem, OrderItem from django.contrib.auth.decorators import login_required from … -
Why does Django Channels AsgiHandler not work with path?
When using Django Channels, in my routing.py, this works: from django.conf.urls import url from channels.http import AsgiHandler from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import my_app.routing application = ProtocolTypeRouter({ 'http': AuthMiddlewareStack( URLRouter ( my_app.routing.http_urlpatterns + [ url("", AsgiHandler) ] ) ) }) But this doesn't: from django.urls import path # <--- Changed from channels.http import AsgiHandler from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import my_app.routing application = ProtocolTypeRouter({ 'http': AuthMiddlewareStack( URLRouter ( my_app.routing.http_urlpatterns + [ path("", AsgiHandler) ] # <--- Changed ) ) }) If it helps, the exception thrown is: 2021-02-05 08:34:25,879 ERROR Exception inside application: No handler for message type http.request File "/opt/my_app/venv3/lib64/python3.6/site-packages/channels/sessions.py", line 183, in __call__ return await self.inner(receive, self.send) File "/opt/my_app/venv3/lib64/python3.6/site-packages/channels/middleware.py", line 41, in await inner_instance(receive, send) File "/opt/my_app/venv3/lib64/python3.6/site-packages/channels/consumer.py", line 62, in __call__ await await_many_dispatch([receive], self.dispatch) File "/opt/my_app/venv3/lib64/python3.6/site-packages/channels/utils.py", line 52, in await dispatch(result) File "/opt/my_app/venv3/lib64/python3.6/site-packages/asgiref/sync.py", line 244, in __call__ return await asyncio.wait_for(future, timeout=None) File "/usr/lib64/python3.6/asyncio/tasks.py", line 339, in wait_for return (yield from fut) File "/usr/lib64/python3.6/concurrent/futures/thread.py", line 56, in run result = self.fn(*self.args, **self.kwargs) File "/opt/my_app/venv3/lib64/python3.6/site-packages/channels/db.py", line 14, in thread_handler return super().thread_handler(loop, *args, **kwargs) File "/opt/my_app/venv3/lib64/python3.6/site-packages/asgiref/sync.py", line 277, in thread_handler return func(*args, **kwargs) File "/opt/my_app/venv3/lib64/python3.6/site-packages/channels/consumer.py", line 107, in dispatch raise ValueError("No handler for …