Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to access subcclass attributes in super class methods, without passing them in
How does one access a derived class'es property (static variable in other languages), in its base classes method? I.e. class Base: @classmethod def set_foo(cls): return [1, 2, cls.x] class Derived(Base): x = 3 foo = Base.set_foo() Derived.foo # Hope to have it set to [1, 2, 3] I wish to not pass x directly to the base class, i.e. foo = Base.set_foo(x) because I have a lot of methods to be called with the same variables. EDIT The comments have asked for context. I tried to make a minimum reproducible example to spare you guys the details. Here's the full context: So its actually todo with Django Admin. I have a abstract model. Then I have various admin interfaces for the various concrete implementation of the abstract model. As you can guess I created an asbtract admin model to handle the common logic. A part of handling the common admin logic, e.g. generating properties on the dervived admin model. So for example the list display, heres the logic to create the list display: class FactAdmin(admin.ModelAdmin): @classmethod def build_list_display(cls, *custom): return ( 'created_utc', *custom, 'foo__bar__abbreviation', 'foo__baz__name', 'foo__caz__name', 'foo__daz__description', 'foo__eaz__code', ) @admin.register(FooEntry) class FoopEntryAdmin(FactAdmin): fieldsets = FactAdmin.build_list_display('cannon_ball', 'pogo_stick') So in the base … -
which is best choose for online game back-end (Laravel vs django)?
I want to create a database for a popular online game. Which is better for server-side code between Laravel and django frameworks? -
How to Authenticate Django REST API with HTTP only cookie?
i use django rest framework and react js environment for my project, to store jwt token local-storage, cookie is unsafe so i decided to save httponly cookie, how do i achieve authenticate how pass token in http header -
JSONDecodeError Exception Value Expecting value: line 1 column 1 (char 0)
I am trying to add products in to the cart but whenever I try to add to the cart product added in the cart successfully but whenever I try to see json data I get this error Here is my Views.py for Cart: def updateCart(request): data = json.loads(request.body) productId = data['productId'] action = data['action'] print('Action:', action) print('productId:', productId) customer = request.user.customer_name product = ProductModel.objects.get(pk= productId) order, created = OrderModel.objects.get_or_create(customer=customer, complete=False) return JsonResponse('Item 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 === 'AnonymousUser'){ 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 am really new here so please help me I am wrong. And I am stuck here don't know what to do ? :( -
Django Retrive data after a specific number or index
i have two rendered contexts in my view: def PostHomeView(request): RecentPost = Post.objects.order_by("-date").all()[:5] AllOtherPosts = Post.objects.order_by("-date").all() template_name = 'lista_post.html' context = {**strong text** 'recentposts' : RecentPost, 'allposts' : AllOtherPosts } return render(request,template_name,context) in the second one ('allposts') i would like to get all objcects without the first fve how can i do it? -
Huey task not running from django view but works from shell
I am running into a problem and wondering what might be wrong. Problem Huey task is not running when called from web view. But when called from shell command from same VM it runs fine. The task is registering fine with huey. The task in question is handshake. VM: Web, Using View: Not working VM: Web, Using Shell: Working VM: Worker, Using Shell: Working Setup I am running an application in docker. Running two instances of same image with exactly same settings connecting to same redis and same postgres. I have verified that both instances are connected to same Redis. The two instances are: web.1: Running gunicorn web application in normal thread mode. worker.1: Running python manage.py run_huey Settings INSTALLED_APPS += ['huey.contrib.djhuey'] HUEY = { 'name': 'myapp', # Use db name for huey. 'results': True, # Store return values of tasks. 'store_none': False, # If a task returns None, do not save to results. 'utc': True, # Use UTC for all times internally. 'blocking': True, # Perform blocking pop rather than poll Redis. 'consumer': { 'workers': 2, 'worker_type': 'thread', 'initial_delay': 0.1, # Smallest polling interval, same as -d. 'backoff': 1.15, # Exponential backoff using this rate, -b. 'max_delay': 10.0, # … -
How to manually turn off a condition thru frontend javascript
I have a function on my django app that automatically executes when certain conditions are met. Now I want to happen is, the user have the ability to turn on/off that automatic feature on a toggle button. @views.py def auto_sms(request): responses = Rainfall.objects.filter( level='Torrential' or 'Intense', created_gt=now() - timedelta(days=3), sms_sent=False, ) if responses.count() >= 50: send_sms() responses.update(sms_sent=True) @urls.py urlpatterns = [ path('send_sms/', send_sms, name='send_sms'), ## To execute this, call the API endpoint from vue path('auto_sms/', auto_sms, name='auto_sms'), ## There must be a toggle button for on & off. ] How to do it? I mean what logic or condition. I'm using DRF-VueJS Thanks! -
how to compare uploaded file in already exist in django model
I am getting a file from the user and filter data from the model if the user uploaded file exists or not, but I am getting "None" while filtering. from .models import SomeModel uploaded_file = request.FILES.get('upload_file') model_data = SomeModel.objects.filter(my_file=uploaded_file) if model_data == None: someModel.objects.create(my_file=uploaded_file) else: print('file already exist.') print(model_data) # prints None I have uploaded the same file too many times but it always creates new data in the model. I know every time when uploaded file Django creates a new file in the media folder. how can I filter if uploaded_file already exists in the model? -
multiple inline formset in django
Hi everyone this is Dilip here, i am an intermediate to django. I want multiple form to be saved at the same time. where one table is independent and other two tables are linked as ForeignKey to first one. I want to add data to all three tables at the same time and I should get an option to open and close new fields. like django default admin panel TabulorInline form. Here i am able to do with single table which is having ForeignKey with another, but what if there are two foreignkey associated a single table? -
Make a field required based on choice of other field
I want to make joined_date required only if status = Closed or else joined_date should not be enabled. how to do this? STATUS_CHOICES = ( ("Identified", "Identified"), ("Closed", "Closed") ) status = models.CharField(max_length=60,choices = STATUS_CHOICES, default = 'Identified') joined_date = models.DateField(blank = True, null = True, default = '') -
Issues while serving django admin and react application together
I have hosted React app to be served as default application on "/" and it works fine. But when I am trying to access admin panel, I am getting following error. Page not found (404) Request Method: GET Request URL: http://localhost:8000/admin Raised by: django.views.static.serve Please let me know how I can approach it. -
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)