Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Setting field values for M2M object in djnago
I have two models in my application and I am trying to update a M2M field . Django documentation says that it can be done using set() method . But I guess by dealt set() accepts pk of the objects as arguments and what I want to do is set it using the actual values . For e.g. I have a client in Clients models named "adam" and I want to set the value for its corresponding M2M field "items_onsale" to ["ac" , "book"] Below is my code for the models :- from django.db import models class Client(models.Model): SEX_CHOICES = [('M', 'Male'), ('F', 'Female')] fname = models.CharField(max_length=100) lname = models.CharField(max_length=100) mailid = models.EmailField(max_length=100) sex = models.CharField(max_length=1, choices=SEX_CHOICES, blank=True) age = models.IntegerField() items_onsale = models.ManyToManyField('Sinfo', blank=True) def __str__(self): # for displaying the variable correctly. return self.fname , self.lname , self.mailid , self.sex , self.age , self.items_onsale class Sinfo(models.Model): # data of items put on sale by clients iname = models.CharField(max_length=100) idesc = models.TextField(max_length=300, null=True) def __str__(self): # for displaying the variable correctly. return self.iname What I have tried till now is :- c = Client.objects.get(pk=17) list=["ac","book"] c.items_onsale_set(list) And I am getting below error :- ValueError: Field 'id' expected a number but … -
Getting wrong Output from PostgreSQL Procedure/Function in Django API
I have my database and all its procedures ready in PostgreSQL. I previously used Laravel as backend of my API and all the procedures were working correctly and giving the correct output. My Laravel controller function for one of the API call is as follow: public function retrieve(){ $data = DB::select(DB::raw("SELECT * FROM showallmenuitem()")); $status = count($data); return $status ? response(['message'=>'Menu item retrieved successfully','data' =>$data],200):response(['message'=>'Failed to retrieve menu item.']); } This method calls showallmenuitem() procedure and the output stored in the $data variable is as follow: { "message": "Menu item retrieved successfully", "data": [ { "meniuid": 1, "menuitemsname": "User" }, { "meniuid": 2, "menuitemsname": "Payment" } ] } But recently I changed my backend from Laravel to Django because I need some AI functionality in my app and AI models I need are written in python. So I created a simple view to call the same procedure from Django. I was expecting the same output as Laravel but Django is giving me Null output. I'm using psycopg2 as database drivers. Here is my Django view code: @csrf_exempt def retrieve(request): if request.method == 'GET': with connection.cursor() as cursor: cursor.callproc("showallmenuitem") results = cursor.fetchall() response = { 'message' : 'Menu Items retireved Successfully', … -
Django cannot locate a template
I am trying to make a customer and employee login and register page...however whenever I try to go to localhost:8000/customer register, I get a page not found error not found error. this is my urls.py file: from django.contrib import admin from django.urls import path from accounts import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.register, name = 'register'), path('customer_resgister', views.customer_register.as_view(), name = 'customer_register'), ] views.py: from django.shortcuts import render from django.views.generic import CreateView from .models import User, Customer, Employee from .forms import CustomerSignupForm, EmployeeSignupForm # Create your views here. def register(request): return render(request, 'accounts/register.html') class customer_register(CreateView): model = User form_class = CustomerSignupForm template_name = 'accounts/customer_register.html' #def customer_register(request): models.py: from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class User(AbstractUser): is_customer = models.BooleanField(default=False) is_employee = models.BooleanField(default=False) first_name = models.CharField(max_length = 150) last_name = models.CharField(max_length = 150) class Customer(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, primary_key = True) Phone_no = models.CharField(max_length = 10) location = models.CharField(max_length = 150) class Employee(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, primary_key = True) Phone_no = models.CharField(max_length = 10) designation = models.CharField(max_length = 150) forms.py: from django.contrib.auth.forms import UserCreationForm from django.db import transaction from .models import Customer, Employee, User from django import forms … -
cart not working when i clicked in add to cart
I am trying to build a cart system in my project.I ama using django and javascript for this.but when I click add to cart products are not adding to cart Here is my views.py def updateCart(request): data = json.loads(request.body) productId = data['productId'] action = data['action'] print('productId:',productId) print('Action:',action) customer = request.user.customer_name product = ProductModel.objects.get(product_id=productId) order, created = OrderModel.objects.get_or_create(customer=customer, complete=False) orderItem, created = orderItem.objects.get_or_create(order=order, product=product) if action == 'add': orderItem.quantity = (orderItem.quantity + 1) elif action == 'remove': orderItem.quantity = (orderItem.quantity - 1) orderItem.save() if oderItem.quantity <= 0: orderItem.delete() return JsonResponse('Item has been added to cart', safe=False) Here is my cart.js var updateBtn = document.getElementsByClassName('update-cart') for(var i = 0; i < updateBtn.length; i++){ updateBtn[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action console.log('productId:',productId, 'action:',action) console.log('USER:',user) if(user === 'AnonymouseUser'){ console.log('Please Login to Order!') } else { updateUserOrder(productId, action) } }) } function updateUserOrder(productId, action){ console.log('Product added to cart!') var url = '/update_item/' fetch(url, { method: 'POST', headers: { 'content-Type': 'application/json', 'X-CSRFToken': csrftoken }, body: JSON.stringify({'productId': productId, 'action':action}) }) .then((response) => { return response.json() }) .then((data) => { console.log('data:',data) // location.reload() }) } I already added csrf token but still getting this errors.I revised my code a lot of time but couldn't find … -
How can i fetch EMAIL_HOST,EMAIL_PORT,EMAIL_USE_TLS,EMAIL_HOST_USER,EMAIL_HOST_PASSWORD,DEFAULT_FROM_EMAIL from my database
EMAIL_HOST,EMAIL_PORT,EMAIL_USE_TLS,EMAIL_HOST_USER,EMAIL_HOST_PASSWORD,DEFAULT_FROM_EMAIL these all already saved in my database. How can i fetch in settings.py EMAIL_HOST,EMAIL_PORT,EMAIL_USE_TLS,EMAIL_HOST_USER,EMAIL_HOST_PASSWORD,DEFAULT_FROM_EMAIL from my database for sending email to users email account like in contact us form. -
Can I embed join table resources with a ModelViewSet?
Brand new to Django and DRF as of this week so very much a babe in the woods with all this stuff but quick rundown - my bootcamp course is having us use the DRF ViewSet as a base class for our resource-based views, and then having us ModelSerializers for each part of what we want to add to a returned Response instance. In the lesson for embedding resources from a join table (e.g., two different models as the bases for each ForeignKey field on a join model like so: #importing Model and ForeignKey fields from models module class EventGamer(Model): event = ForeignKey('Event', related_name='registration') gamer = ForeignKey('Gamer', related_name='registration') ), in our list() method for a view in which we want to embed all the Events for a certain Gamer, our ORM call was as follows: gamer = Gamer.objects.get(user=request.auth.user) events = Event.objects.filter(registration__gamer=gamer) So then we could call an EventSerializer based on the ModelSerializer parent class on that QuerySet: class EventSerializer(ModelSerializer): class Meta: model = Event fields = (#fields from that model I want embedded) and then attach the resulting list from the data attribute of that result to what we sent back in the Response object. Now - I stumbled across … -
background images not render in django templates
display: flex; background: url("{% static '..static/images/banner.jpg' %}") no-repeat center; height: 100vh; color: #fff; [![my static folder dir][1]][1] [1]: https://i.stack.imgur.com/dUzXS.png Why I can't render yesterday it render but not now -
CreatePdf with xhtml2pdf from template and upload to S3
I tried to generate Pdf file from html using xhtml2pdf, after that I want to upload to S3. I had no idea how to do it, after trying a few ways but still stuck. Thank you so much for your help in advance. def upload_pdf_S3(pdf): client = boto3.client( 's3', aws_access_key_id, aws_secret_access_key ) try: client.upload_fileobj(pdf, 'test', 'test111.pdf') return True except ClientError as e: print(e) return False def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) upload_pdf_S3(pdf) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None -
Django app hangs in production, but works in development
I have developed a django app that is working well in development, and I get zero issues when I run python manage.py runserver I am attempting to deploy to production, and when I do so and visit localhost, the browser hangs for multiple minutes and ultimately, the browser stops trying and simply maintains whatever page it was displaying before (in both firefox and chrome). My production environment is: Windows server 2016 VM (same results with windows 10 VM) Python 3.7.9 Django 3.0 (using postgresql 13) Apache lounge 2.4.46 mod_wsgi 4.7.1 Additionally, using this environment, I started a fresh django project using a new postgresql database and it works when I deploy it and visit localhost, so I believe the environment/stack is not the problem. In an attempt to isolate the problem I built out the new django project by copying and pasting code from the original project in sections and restarting the apache server to check if I could reproduce the problem. I iteratively copied all the relevant settings in settings.py to the new project, I ran the startapp command so that I have one app in each project named 'metadata' and I copied admin.py, apps.py, forms.py, models.py and views.py … -
Django REST Framework - is there a better way to create a user with additional profile fields at the same time?
This works, but is the result of many hours googling and voodoo programming. It is a serializer that creates a user and at the same time accepts an additional field (personname) that is stored in the user's connected Profile. Although I have managed to make it work, it feels like I have hacked to make it work - a nasty solution. For some reason I had to add the get_personname method to the class - without it I got an error saying this method was missing. I also had to get the value for the personname field out of self.initial_data['personname'] which also seems hacky. Is there a better, cleaner, more idiomatic way to create a user and at the same time add fields to their profile? I'm using Django REST framework 3.11 class UserCreateSerializer(serializers.ModelSerializer): email = serializers.EmailField() personname = serializers.SerializerMethodField(method_name=None) def get_personname(self, value): return self.initial_data['personname'] def validate_email(self, value): lower_email = value.lower() if User.objects.filter(email__iexact=lower_email).exists(): raise serializers.ValidationError("An account exists with that email") return lower_email def validate_username(self, value): username_lower = value.lower() if User.objects.filter(username__iexact=username_lower).exists(): raise serializers.ValidationError("That username is taken") return username_lower class Meta(dj_UserCreateSerializer.Meta): model = User fields = ('email', 'username', 'password', 'personname') def create(self, validated_data): user = User.objects.create( username=validated_data.get('username'), email=validated_data.get('email'), password=validated_data.get('password') ) user.set_password(validated_data.get('password')) user.save() … -
Javascript - Cannot read property 'style' of null - Problem when using onclick to post text to a table
When I click on a list item 'Add' button, I'm using button.onclick to send that item's text to fill out a table on the same html page. However, I keep getting a "Cannot read property 'style' of null" in the console whenever I click an item. This was working fine until recently. Something changed...somewhere, but I can't figure out why it's returning this error suddenly. Here's the Javascript function showPage(page) { document.querySelectorAll('div').forEach(div => { div.style.display = 'none'; }) document.querySelector(`#${page}`).style.display = 'block'; } document.addEventListener('DOMContentLoaded', function() { document.querySelectorAll('button').forEach(button => { button.onclick = function() { showPage(this.dataset.page); } }); }); function myFunction(txt) { var myTxt = txt; console.log(myTxt) if (txt.includes('QB')) { document.getElementById("id_QB").value = myTxt; } else if (txt.includes('RB')) { document.getElementById("id_RB1").value = myTxt; } else if (txt.includes('WR')) { document.getElementById("id_WR").value = myTxt; } else if (txt.includes('TE')) { document.getElementById("id_TE").value = myTxt; } else if (txt.includes('K')) { document.getElementById("id_K").value = myTxt; } } </script> Here's the html page which is displaying a django template (I've deleted the on-page script tags containing the Javascript above). {% load static %} {% block body %} <form method="POST"> {% csrf_token %} <table id="playerName"> {{ form.as_table }} </table> <input type="submit" value="Submit" > </form> <br> {% for player_data in player_data %} <li><p>Player ID: {{ player_data.player_id … -
Why is this syntax incorrect for python?
I am working on a wiki look-a-like page and it is saying that this is incorrect but there is nothing seemingly incorrect about it. here is the 'error' when attempting to run the server I got this response from the terminal terminal response I am trying to figure out all of my issues so that I am able to run the server and look at the website. Can anyone help me understand why there is an issue? Any help is appreciate and any clarification can be provided upon request. this is the code straight from the editor(below) from django.shortcuts import render from django.http import HttpResponseRedirect from django.urls import reverse import random import re from . import util from markdown2 import Markdown -
How to use COALESCE with a Value(0) in Django with Postgresql?
I have the following in my views: Timesheet.objects.annotate( total_time=ExpressionWrapper( ExpressionWrapper(F('out') - F('entry'), output_field=IntegerField()) - Coalesce(ExpressionWrapper(F('lunch_end') - F('lunch'), output_field=IntegerField()), Value(0)), output_field=DurationField() ) ) But when I started using Postgresql, I got an error caused by the Value(0). If I change it to None, I no longer get an error, but the final math returns as None, instead of the calculation. How can I solve this? -
Nothing happens when I run "$ python manage.py shell"
I have been following this tutorial from djangoproject as an assignement and I can't understand what's happening when I try to run $ python manage.py shell. In the tutorial, after running this line we're able to explore the API once we're in the shell, but all I get is: Python 3.9.0 (tags/v3.9.0:9cf6752, Oct 5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) -
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)