Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - No Model matches the given query
I'm displaying a catalog with products, which are filtered by categories, but when attempting to call the ListView from a link in the template, it returns that No Category matches the given query. The view: class CategoryProductList(ListView): template_name = 'catalog/product/product_list.html' def get_queryset(self): self.category = get_object_or_404(Category, name=self.kwargs['category_slug']) return Product.objects.filter(category=self.category) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['categories'] = Category.objects.all() context['category'] = self.category context['category_slug'] = self.category.slug return context The url pattern: path('catalog/<slug:category_slug>/list/', views.CategoryProductList.as_view(), name='category_product_list_table'), The button that calls the ListView: <li class="nav-item"> <a href="{% if category %}{% url 'catalog:category_product_list_table' category.slug %}{% else %}{% url 'catalog:product_list_table' %}{% endif %}" class="btn btn-secondary btn-sm"> <i class="uil-list-ul"></i> View as table </a> </li> What am I doing wrong? -
Images not being displayed in django
I have this product model: class Product(models.Model): category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE) name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True) description = models.TextField(blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) available = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ('name',) index_together = (('id', 'slug'),) def __str__(self): return self.name def get_absolute_url(self): return reverse('shop:product_detail', args=[self.id, self.slug]) And this product_list view, where all the products should be displayed: def product_list(request, category_slug=None): category = None categories = Category.objects.all() products = Product.objects.filter(available=True) if category_slug: category = get_object_or_404(Category, slug=category_slug) products = products.filter(category=category) return render(request, 'shop/product/list.html',{ 'category':category, 'categories':categories, 'products':products }) And this is the list.html template: {% extends "shop/base.html" %} {% load static %} {% block title %} {% if category %}{{ category.name }}{% else %}Products{% endif %} {% endblock %} {% block content %} <div id="sidebar"> <h3>Categories</h3> <ul> <li {% if not category %}class="selected" {% endif %}> <a href="{% url "shop:product_list" %}">All</a> </li> {% for c in categories %} <li {% if category.slug == c.slug %}class="selected" {% endif %}> <a href="{{ c.get_absolute_url }}">{{ c.name }}</a> </li> {% endfor %} </ul> </div> <div id="main" class="product-list"> <h1>{% if category %}{{ category.name }}{% else %}Products {% endif %}</h1> {% for product in products %} … -
Django - prevent duplicate POST requests when user clicking submit button multiple times?
What is most effective way to prevent multiple POST requests from happening if the user is clicking on the "Send Message" button multiple times. <!-- message.html --> <form action="{% url 'send_message' %}" enctype="multipart/form-data" method="POST"> {% csrf_token %} <input type="text" id="messagename" name="messagename" maxlength="50" required> <textarea id="messagecopy" name="messagecopy" required></textarea> <input type="submit" class="btn" value="Send Message"> </form> And my views.py def send_message(request): if request.method == "POST": campaign = Campaign() campaign.name = request.POST["messagename"] campaign_message = request.POST["messagecopy"] campaign.messagecopy = campaign_message campaign.save() send_message(campaign_message) redirect('home') -
How to push the data from Javascript to Django backend
I am new to how javascript works, so I am trying to push the time spent on a page using Javascript to Django backend but I do not know how to do it, need some help to know how to do it. Here is the javascript that is placed in the template: $(document).ready(function() { var startDate = new Date(); $(window).unload(function() { var endDate = new Date(); $.ajax({ type: POST, url: "/backendurl", data: {'timeSpent': endDate - startDate}, }) }); }); I am not sure what to do to push the data to Django backend using above Jquery POST. -
Gunicorn Connection Timeout
I'm new to Gunicorn and I have a question about timeouts. Currently I have a client server making a request to an api server. The api server is on AWS EC2 with docker containers, no elb. The container in question is run with Django, WSGI, Gunicorn. I currently have workers = multiprocessing.cpu_count() + 1 reload = True timeout = 1200 keepalive = 1200 graceful_timeout = 1200 in my gunicorn.conf. When I make a request that finishes in under 5 minutes, it returns successfully. If I try for something over 5 minutes, the client receives RemoteDisconnected('Remote end closed connection without response') even though the timeout is set to 1200. If I change timeout in gunicorn.conf to 10s, the client receives RemoteDisconnected('Remote end closed connection without response') after 10~ seconds. Is there an upper bound to the timeout setting or could something else be setting a limit from a default perspective? I thought maybe something else in Django or WSGI might be setting some timeout as well but then when I looked, the django settings and wsgi.py have almost nothing set. I changed TIMEOUT = 1200 in Django settings.py. Currently I am the only one using both servers. While they are using … -
Javascript not being loaded in Django, but css and img do
well, as the title suggests, I have a carousel I want in my index page, so I originally went for owl-carousel, but it wasn't working, so I decided to use the bootstrap carousel and I'm having exactly the same issue. It can't be that I didn't declare correctly the root, because I use a link (https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js), so I really don't know what the problem is, let me show you... What it should look like views.py: from django.shortcuts import render from django.views.generic.base import TemplateView class HomePageView(TemplateView): template_name = "core/index.html" Owl-carousel: The code: The result: Bootstrap carousel Here the issue is that the buttons in the result are not working. The code: The result: Any idea how I can solve this? Thank you. -
deploying single page application with Django REST framework
I would like to know what's the best way to deploy a single page application and Django REST framework. Here are the techniques I am aware of: Deploy the Django App and the single page application on seperate domains (this will require CORRS headers) Deploy Django and the single page application on the same domain and used Nginx reverse proxy to route traffic sent to '/api' to the Django App. Serve the single page application using Django views (I am not entirely sure how this works) -
combine response with file download and redirect
I have a view, that upn called, starts a download: class PrintView(TemplateView): template_name = "proj/listview.html" def get(self, request, *args, **kwargs): try: filepath = TMP.IMG() if os.path.exists(filepath): with open(filepath, 'rb') as fh: response = HttpResponse(fh.read(), content_type="application/force-download") response['Content-Disposition'] = 'inline; filename=' + os.path.basename(filepath) messages.success(request, "image download started ...") return response messages.error(request, "something went wrong!") return redirect("index") except Exception as e: messages.error(request, e) return redirect("index") in my template I call a modal window with a download button, similar to: <button id="dl_modal_submit" type="submit"</button> which has some javascript on top: let somvar = null; $('#dlModal').on('show.bs.modal', function (event) { var button = $(event.relatedTarget); var modal = $(this); }); document.querySelector('#dl_modal_submit').addEventListener('click', event => { const params = { somevar, } const paramStr = new URLSearchParams(params).toString(); const dl= `/dl/${somevar}`; window.open(dl, "_self"); }); Thing is, when I click on the button I want: close the modal start the image download redirect to index it is suggested here that I do that using two views, but surely there must be another way to do this in the javascript part? -
Why is this python syntax incorrect?
I am trying to check the website I just made for a project and for some reason it is saying that I have an error I don't understand, any way that I have tried to correct the error has seen no solution. I tried to use the VS code debug to see what the issue is but it just tells me a syntax error and it doesn't really make any sense I have attatched a picture for Where python is seeing an error I also attempted to run the server just to see if itll let me see what it looks like or give me the link to the page but it sends me a lot that i have never seen before nor do i understand. Here is my attempt to runserver. Any help is appreciated! -
ModelViewSet @action decorator gives NameError
I am trying to use Django REST Framework's ModelViewSet extra routing actions using the @action decorator. The idea is to get a url such as /events/pinned to return a filtered list of events that the user is a creator of and have pinned as noteworthy. My class from views.py will not compile, but gives an error: File ".../views.py", line 46, in EventViewSet @action(detail=False, methods=['get'], url_path='pinned') NameError: name 'action' is not defined The problematic code: class EventViewSet(viewsets.ModelViewSet): queryset = Event.objects.all() serializer_class = EventSerializer permission_classes = [permissions.IsAuthenticated] @action(detail=True, methods=['get'], url_path='pinned') def pinned(self, request, pk=None): pinned_events = Event.objects.filter(creator=self.get_object()).filter(is_pinned=True) serializer = self.get_serializer(pinned_events, many=True) return Response(serializer.data) -
Deleting items in Django Admin Panel with get request
I have 2 models as follows. In these models, I changed the delete function for myself. When I want to delete a comment on the admin panel, I go into the comment and click the delete button, and when the comment is deleted, this delete function works. However, when I select and delete the comments or comments with the checkbox on the page where the comments are listed in front of me, the delete function does not work and django does this with the get request. I'm not interested in whether this request is get or post, I just want this delete function to work either way. class Comment(models.Model): owner = models.ForeignKey('user.User', blank=False, null=False, on_delete=models.CASCADE) content = models.TextField(validators=[min_length], verbose_name='Yorum') topic = models.ForeignKey(Topic, on_delete=models.CASCADE) created_date = models.DateTimeField(auto_now_add=True) updated_date = models.DateTimeField(auto_now=True) def save(self, *args, **kwargs): self.topic.forum.comment_count += 1 self.topic.forum.save() super(Comment, self).save(*args,**kwargs) def delete(self, *args, **kwargs): self.topic.forum.comment_count -= 1 self.topic.forum.save() super(Comment, self).delete(*args,**kwargs) -
spinner not show after submit the button
when i will submit the form data without any error than spinner showing... but when the form have some error (like username is required) and after submit the form than spinner not showing... <script type="text/javascript"> var spinner = $('#loader'); $(document).on('submit', '#payment-form', function(e){ e.preventDefault(); spinner.show(); $.ajax({ type: 'POST', url: "{% url 'post_create' %}", data: { title: $('#id_title').val(), ages: $('#id_ages').val(), zip_codes: $('#id_zip_codes').val(), address_user: $('#id_address_user').val(), phone: $('#id_phone').val(), state: $('#id_state').val(), city: $('#id_city').val(), category: $('#id_category').val(), description: $('#id_description').val(), photo_main: $('#id_photo_main').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, error:function('#card-element'){ spinner.fadeOut(); }, success:function(data){ spinner.fadeOut(); } }); }); </script> -
Django: Comment Section under each post? Two models, one template
I am trying to make a Social Media Platform as a way to better understand Django, and am stuck on the commenting section. I would like to have a comment section, under each post that a user creates. However, I am struggling with handling multiple models on one template. I am not sure where to go from here, and any direction/advice would be appreciated. #views.py class Text_List(LoginRequiredMixin, ListView): model = Text_Post template_name = 'main1/includes/h_post.html' context_object_name = "posts" def get_context_data(self,**kwargs): data = super().get_context_data(**kwargs) return data class Text_Post_P(LoginRequiredMixin, CreateView): model = Text_Post fields = ['T_Post_content'] template_name = 'main1/h_platform.html' def form_valid(self,form): form data has be stated form.instance.T_Post_author = self.request.user return super().form_valid(form) class Commenting_P(CreateView): model = Commenting fields = ['Comment_content'] template_name = 'main1/includes/comment.html' #Not sure what to put here. #models class Text_Post(models.Model): T_Post_content = models.CharField(max_length = 200,verbose_name = "") T_Post_published = models.DateTimeField(default = datetime.now) T_Post_author = models.ForeignKey(User, on_delete = models.CASCADE, default = None, null = True) T_Post_likes = models.IntegerField(default=0) def __str__(self): return self.T_Post_content[:10] class Meta: ordering = ('-T_Post_published',) class Commenting(models.Model): Comment = models.ForeignKey(Text_Post, on_delete = models.CASCADE,related_name="comments", blank = True, null = True) Comment_author = models.CharField(max_length = 100, default = None, null = True, blank = True) Comment_content = models.TextField(default = None) Comment_published = models.DateTimeField(default … -
Django Admin Change List Queryset
I'm adding a total row to django admin following the response here: SO answer. I'm not allowed to show the individual costs on a column, so I can't use django admin totals library or django totalsum, because they require the column to be on list_display. The problem I'm having is that I need to filter or exclude by pay_type but when I try to write the query I get: assert not self.query.is_sliced, AssertionError: Cannot filter a query once a slice has been taken. How can I make this work with a filter? Admin.py - I tried: class MyChangeList(ChangeList): def get_results(self, *args, **kwargs): super(MyChangeList, self).get_results(*args, **kwargs) b_queryset = self.result_list.exclude(cost__paytype_id = 3) b = b_queryset.annotate(total_executed_hours= Sum('cost__bill_hours')) self.executed_hours = b['total_executed_hours'] Also tried: b = self.result_list.exclude(cost__paytype__id = 3)\ .aggregate(total_executed_hours=Sum('cost__bill_hours')) I tried a bunch of other combinations. How can I make this work? Thanks! -
Search bar no content is returned
Hey i am new to Django and I am trying to make a search bar to my first site. My problem here is when I search for any value that I/user entered and on the site, the site only refreshes and doesn't give me anything back but the empty option that i gave the site to display when there is no content to match the search. (That's not all of the Topic model) model.py class Topic(models.Model): content = models.CharField(max_length=200) views.py def search(request): query = request.GET.get('q') if query: result = Topic.objects.filter(content__icontains=query) context = { 'query': query, 'result': result} return render(request, 'learning_logs/topics.html', context) ( That's not all of the topics.html if it help to show all the page i can also put all of the code) topics.html {% block content %} <form method="GET" action="{% url 'learning_logs:search' %}"> {% csrf_token %} <input name="q" value="{{ request.GET.q }}" placeholder="search.."> <button class="btn btn-primary" type="submit"> Search</button> </form> {% for topic in topics %} ...... {% empty %} <h3><li>No topics have been added yet.</li></h3> {% endfor %} {% endblock content %} -
How can I remove folder's name and add www to domain on my .htaccess using .fcgi file?
I'm having trouble figuring out my .htaccess in a shared host for days now because I must keep the index.fcgi, otherwise my django project doesn't work. I'm trying to remove a folder named app from my URL and also make sure that when someone types www.domain.com it goes to my page. I already checked the CNAMEs from my domain and www.domain.com is there, but it doesn't go through with the pages inside my project, only if I type domain.com My .htaccess file: (I must keep the index.fcgi) AddHandler fcgid-script .fcgi RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ index.fcgi/$1 [QSA,L] My index.fcgi file: #!/usr/bin/scl enable rh-python35 -- /home/CONTA/.virtualenv/bin/python import os, sys from flup.server.fcgi import WSGIServer from django.core.wsgi import get_wsgi_application sys.path.insert(0, "/home/CONTA/mydjangoproject") os.environ['DJANGO_SETTINGS_MODULE'] = "mydjangoproject.settings" WSGIServer(get_wsgi_application()).run() Thanks a lot in advance! -
Validating access_token against Azure AD coming from ReactJS
The crux of all the below is this: how do I validate an Azure AD access_token from the Django/DRF API sent to it from the ReactJS FE? My web application is a microservice setup, so completely distinct services between the FE and API. The Django/DRF API serves no static assets and should only be accessible via the FE and the data it is authenticated to consume from it. I have the ReactJS FE successfully getting an access_token from Azure AD and my tenant using react-aad. (Note: This based on msal v1.0 which will be replaced by @azure/msal-react using msal v2.0 hopefully this month at some point). Now I just need to send it to the API where it is validated against Azure AD. This has been a real struggle finding something that works or that is documented well enough. I've tried the following, but ultimately hit this issue with all of them that I can't seem to figure out: social-auth-app-django django-rest-framework-social-oauth2 drf-social-oauth2 This article At any rate, can't get those working properly so now I'm playing with libraries developed by Microsoft: azure-activedirectory-library-for-python... I guess this is deprecated and the next one should be used. Not sure how this correlates to … -
question about "attributes" attribute of a class
This is probably a simple question but I'm wondering why it seems attribute names and values are reversed in the following example: >>> class SelectOne(DjangoChoices): ... cola = ChoiceItem("c", "Coca Cola") ... beer = ChoiceItem("b", "Heineken") ... >>> SelectOne <class 'SelectOne'> >>> SelectOne.attributes OrderedDict([('c', 'cola'), ('b', 'beer')]) >>> for k, v in SelectOne.attributes.items(): ... print (k, v) ... c cola b beer Common understanding should be that "cola" is the key and "c" is the value. where can I find the documentation of "attributes" attribute of a class? -
Configure gunicorn.service with Docker and Django
For the context of my project Currently I am trying to containerize my django app with docker. What goes well are: different services: db, web, nginx can be built and up in my local. The error is The django app seems like cannot find my gunicorn socket file. Here is the exact error: nginx_1 | 2020/11/06 21:07:40 [crit] 6#6: *2 connect() to unix:/run/gunicorn.sock failed (2: No such file or directory) while connecting to upstream, client: 172.27.0.1, server: , request: "GET / HTTP/1.1", upstream: "http://unix:/run/gunicorn.sock:/", host: "0.0.0.0:1337" nginx_1 | 172.27.0.1 - - [06/Nov/2020:21:07:40 +0000] "GET / HTTP/1.1" 502 576 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.183 Safari/537.36" "-" This is my nginx config file: # define the web service server as upstream upstream web-service { # should use web:8000 rather than the localhost:8000 etc server web:8000; } # for db #0.0.0.0 localhost 157.230.227.115 qmrealestate.co www.qmrealestate.co; server { listen 80; #server_name 127.0.0.1; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /app/Django-RealEstate; } location /media/ { root /app/Django-RealEstate; } location / { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://unix:/run/gunicorn.sock; } } This is my docker-compose.prod.yml … -
object_id in ContentType
I can't seem to find some explanation how to set the field object_id in either the documentation here or this very helpful post here. Since this field is compulsory, how is it set by Django during runtime? If I want to set it from within admin, what caution, if any, should I be taking? Is it supposed to be related to the pk of the related model somehow or is it purely a unique integer that I can just set? Thanks. -
Django Custom Permission method or decorator
I am many views and more than one user type. I want some views that can be seen by specific user types and other users cant see this. For example, only company see this views and for this i did that like this below: @login_required def only_company_can_view(request): if not Company.objects.filter(owner_id=request.user.id).exists(): return HttpResponse('Permission Denied. Only Company can see this') # > rest of the logic return render(request, 'template.html') and above this working very well and solves my problem but i don't like this. coz, i don't want to write every time for the rest of the views for the company related views. So i am finding a solution so that i can use decorator or something else that are best practice Can anyone help me in this case? -
Django OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect
I am trying to run an opensource project in my computer. But I am getting this error. Please experienced a person share your thought. I don't understand how I can solve this issue. I am using python 3.6 and django 2.X version. Traceback (most recent call last): File "C:/Users/Asus/Desktop/Fiverr/vulunteer/manage.py", line 37, in <module> execute_from_command_line(sys.argv) File "C:\Python37\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Python37\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python37\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Python37\lib\site-packages\django\core\management\commands\runserver.py", line 60, in execute super().execute(*args, **options) File "C:\Python37\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "C:\Python37\lib\site-packages\django\core\management\commands\runserver.py", line 95, in handle self.run(**options) File "C:\Python37\lib\site-packages\django\core\management\commands\runserver.py", line 102, in run autoreload.run_with_reloader(self.inner_run, **options) File "C:\Python37\lib\site-packages\django\utils\autoreload.py", line 598, in run_with_reloader start_django(reloader, main_func, *args, **kwargs) File "C:\Python37\lib\site-packages\django\utils\autoreload.py", line 583, in start_django reloader.run(django_main_thread) File "C:\Python37\lib\site-packages\django\utils\autoreload.py", line 301, in run self.run_loop() File "C:\Python37\lib\site-packages\django\utils\autoreload.py", line 307, in run_loop next(ticker) File "C:\Python37\lib\site-packages\django\utils\autoreload.py", line 347, in tick for filepath, mtime in self.snapshot_files(): File "C:\Python37\lib\site-packages\django\utils\autoreload.py", line 363, in snapshot_files for file in self.watched_files(): File "C:\Python37\lib\site-packages\django\utils\autoreload.py", line 262, in watched_files yield from iter_all_python_module_files() File "C:\Python37\lib\site-packages\django\utils\autoreload.py", line 103, in iter_all_python_module_files return iter_modules_and_files(modules, frozenset(_error_files)) File "C:\Python37\lib\site-packages\django\utils\autoreload.py", line 139, in iter_modules_and_files if not path.exists(): File "C:\Python37\lib\pathlib.py", line 1346, in exists self.stat() File "C:\Python37\lib\pathlib.py", line 1168, in … -
Can I dynamically do a bulk update on a JSON field while referencing a model field?
I am caching some data on my model and this is essentially what I'd like to achieve. Person.objects.all().update(my_links={first_link='https://first_url/{id}'.format(id=F('id'))}) The result I get is: { "first_link": "https://first_url/F('id')" } -
Modeling favorites in Django from two different models
I have a Netflix clone app that I am creating and I am having difficulty with the models. I have a Movie model that has fields for the movie such as a title, duration, rating, etc. I am not sure how I should model my database but what I believe I should be doing is a ManyToMany relationship, such as, a user can favorite many movies and a movie can be favorited by many users. However, if I do it like this I feel that I would end up with a Favorites table that would have many users and movies and possible see this as an issue having to go through each row to find the current user rather than doing maybe a OneToMany relationship, such as, a user can favorite many movies and a movie can be favorited by a user. So first, I am not sure what the proper way of modeling this would be. I also do not know how to add this relationship to my user model because I am using the User model that I brought in from django.contrib.auth.models I am having a lot of trouble trying to think of a solution for this and … -
css + xhtml2pdf : force only one table per page
trying to output one table per page in a pdf document generated with xhtml2pdf. Nothing in the doc really explains how to achieve this and front end stuff is not my strong suit here is what I got so far: {% load static %} <!DOCTYPE html> <html> <head> <style> @page { @frame header_frame { /* Static Frame */ -pdf-frame-content: header_content; left: 50pt; width: 512pt; top: 50pt; height: 200pt; } size: a4 portrait; @frame content_frame {/* Content Frame */ left: 50pt; width: 512pt; top: 230pt; height: 700pt; } } table { width:100%; } table.print-friendly tr td, table.print-friendly tr th { page-break-inside: avoid; } table, th, td { border: 1px solid black; border-collapse: collapse; } th, td { padding: 2px; text-align: left; } table#t01 tr:nth-child(even) { background-color: #eee; } table#t01 tr:nth-child(odd) { background-color: #fff; } /* table#t01 th { background-color: black; color: white; } */ body{ font-size: 12px; } h1,h2,h3,h4,h5,h6,p{ padding: 0; margin: 0; } img{ float: left; } </style> </head> <body> <div id="header_content"> <th colspan="5" style="text-align: center;"> <div style="text-align: left"> <h3></h3> <p style="padding-bottom: 2px; margin: 0; font-size: 20px;">{{ my_company.name }}</p> <p style="padding-bottom: 2px; margin: 0; font-size: 10px;">{{ my_company.address }}</p> <p style="padding-bottom: 2px; margin: 0; font-size: 10px;">{{ my_company.city }}, {{ my_company.zip_code }}</p> …