Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django model form applying user viewing data as the user from form
I have a model form which adds fields (email, latitude etc) and then my views.py attaches the user to the form before it saves. However, when I look at the data in the admin panel, it just assigns my username to all of the entries. If I log in as a different user, I get the same form entries but all with the new username attached. Views.py form = SafezoneForm() if request.method == 'POST': form = SafezoneForm(request.POST) if form.is_valid(): instance = form.save(commit=False) Safezone.userid = request.user #### gets username here and assigns to model instance.save() return redirect('loadingsafezone') context = {'form':form} return render(request, 'V2maparonno_create_safe_zoneV2.html', context) models.py class Safezone(models.Model): userid = models.ForeignKey(User, on_delete=models.CASCADE, null=True) useremail = models.EmailField(max_length=100) name = models.CharField(max_length=100, null=True) latitudecentre = models.FloatField(null=True) longitudecentre = models.FloatField(null=True) latcorner1 = models.FloatField(null=True) latcorner2 = models.FloatField(null=True) latcorner3 = models.FloatField(null=True) latcorner4 = models.FloatField(null=True) longcorner1 = models.FloatField(null=True) longcorner2 = models.FloatField(null=True) longcorner3 = models.FloatField(null=True) longcorner4 = models.FloatField(null=True) def save(self, *args, **kwargs): self.longcorner1 = self.longitudecentre - 0.6 self.longcorner2 = self.longitudecentre + 0.6 self.longcorner3 = self.longitudecentre + 0.6 self.longcorner4 = self.longitudecentre - 0.6 self.latcorner1 = self.latitudecentre - 0.6 self.latcorner2 = self.latitudecentre - 0.6 self.latcorner3 = self.latitudecentre + 0.6 self.latcorner4 = self.latitudecentre + 0.6 super(Safezone, self).save(*args, **kwargs) def __str__(self): return self.userid or … -
Speed up offset pagination on complex calculations in database
I am using pagination with Graphql when creating a facebook-like feed with React Native. I am using Django as Backend. I am using the approach where i send offset and limit as parameters to my backend and the response is just the data from that given interval. But what i do not really understand about this type of pagination is that, will i need to run my functions and calculations in the backend on every request or is django caching it? What i mean is, suppose i would like to get all my followers posts, and then sort them by date. After i have done that i would just return an interval of this data to the frontend. But when the frontend ask the backend for a new interval after 20 seconds, it just feels really unnecessary that the backend will be needed to find and sort the posts again. Is there a way where i would be able to cache the sorted list of posts and then return intervals without the need to sort them everytime? -
Change some default words for a specific language code in django
I'm trying to change some words that are poorly translated into Persian. I've searched this issue but I couldn't find any article about it. I've only changed the LANGUAGE_CODE, and I don't want a website for both languages -
Getting "Server Error (500)" on Django Heroku website
I tried following this guide to publish my website using Heroku, and it partly works but not entirely. For some reason, I keep on getting a Server Error (500) on part of my website. Some pages work, including the homepage, but the main page does not. (Everything works on local, but for some reason I think I got a session data corrupted, but it still worked fine.) When I got the error log email, it says: "Internal Server Error: /results/NYC AttributeError at /results/NYC 'NoneType' object has no attribute 'has_header'" I tried doing many things, nothing worked. Here's my settings.py: """ Django settings for finalproject project. Generated by 'django-admin startproject' using Django 3.0.8. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os import environ # https://devcenter.heroku.com/articles/django-app-configuration # https://devcenter.heroku.com/articles/deploying-python import django_heroku # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # For environment variable (for secret key) # https://djangocentral.com/environment-variables-in-django/ env = environ.Env() # reading .env file environ.Env.read_env() # SECURITY WARNING: keep the secret key used in production secret! # PRODUCTION: # https://stackoverflow.com/questions/47949022/git-heroku-how-to-hide-my-secret-key # https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Deployment#getting_your_website_ready_to_publish … -
I am cloning a django project from git but it is showing the following error
[this is the project I need to run][1] [enter image description here][2] I tried running the command python manage.py migrate [1]: https://github.com/anuj-glitch/Disease-Prediction-using-Django-and-machine-learning [2]: https://i.stack.imgur.com/e1Bwl.png -
Sign in with Apple ID in react + django rest framework project
I'm working on the project setup with react + Django rest framework. The error I'm getting now is invalid client. In react, I used 2 packages react-social-login-buttons and react-apple-login button. I used 2 packages to succeed to get code and id_token. Then I sent code and id_token like this: {"code": code_value, "id_token": id_token_value}. But when I call this API, I'm getting the following error. It would be great if anyone could help me. Thanks -
Best practices about serving media efficiently with Nginx + Django in NAS
Having read a bunch of other topics similar to this one, I'm still not sure what would be best. Let's say I have a load balancer with 2 servers which have Nginx + Django, and then a separate database server and 3 storage servers with images and videos. How do I best serve the media files from the 3 storage servers ? What I currently plan to do is keeping my 2 entry points for all the requests. A request for a media file would be authenticated there by Django and then I would use X-accel direct to proxy pass the media request to the storage servers. However, the Nginx docs state this: When NGINX proxies a request, it sends the request to a specified proxied server, fetches the response, and sends it back to the client. Does this mean that the load would be the same for the 2 entry point servers ? This is how I would understand it, which is not very efficient. What I would like to achieve is something like this: Is this possible? I guess the most efficient way performance wise to serve media files would be to remove the app server step, like … -
How to get a count of a value in a ManyToMany field
I have a model called Recipe that is simplified to have a title and category. The category is a ManyToMany field. title = models.CharField(max_length=100) category = models.ManyToManyField(Category, help_text='Select a category') I have another model called Category name = models.CharField(max_length=200, help_text='Enter a baking category') def __str__(self): return self.name There are several categories but for simplicity, let's say we have two: Bread and Cake. How would I query the DB to figure out how many Recipes I have of each category? I've been trying something like this: But that isn't working. I also don't want to explicitly define all the categories I'm looking for since in the future I would add more categories. -
Dango3: problems with onetoone relationship and '...' object has no attribute '...'
I am getting this error, but I don't understand why. I created the Pipeline object and Config object together in the admin view. However, when I go to the list view: 'Pipeline' object has no attribute 'args' I have pretty much the same setup working with other models, so I am not sure why it is not working in this case. It complains that 'Pipeline' has no args model.py: class Pipeline(models.Model): config= models.OneToOneField('Config', on_delete=models.SET_NULL, null=True, parent_link=True) class Config(models.Model): args = models.CharField(max_length=256, null=True, default='-p -q -x -u -l -m -r') pipeline = models.OneToOneField('Pipeline', on_delete=models.CASCADE, null=True, parent_link=False) admin.py: class ConfigInline(admin.StackedInline): model = Config class PipelineAdmin(admin.ModelAdmin): inlines = [ConfigInline] I did the database migrations. -
How to pass arguments when redirecting to another view in Django 3 (Python)
I want to pass variables to my views in django but I get errors... The code is simply attempting to pass text into a view while redirecting. Basically the user will fill out a form, and the content of that form will be displayed on another page. However, if I run the following code, I come across this error: django.urls.exceptions.NoReverseMatch: Reverse for 'view2' with arguments '('hi',)' not found. 1 pattern(s) tried: ['view2$'] views.py from django.shortcuts import render, redirect def index(request): if request.method == 'POST': form = MyForm(request.POST) if form.is_valid(): submit_form(request) else: form = MyForm() return render(request, 'index.html', {'form':form}) def view2(request, text): return render(request, 'page2.html', {'my_text':text}) def submit_form(request): # Just using 'hi' for simplicity return redirect(view2, 'hi') page2.html {% extends "base.html" %} {% block body_block %} {{ my_text }} {% endblock %} urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('view2', views.view2, name='view2'), ] I suspect the error is from me doing something wrong in the views.py, but I have not been able to find anything that will work... I've also tried these two lines in the submit_form function, but got the same error return redirect(view2, pn='hi') return HttpResponseRedirect(reverse('view2', args=('hi', ))) -
django not rendering custom 403 page, displays browser default instead
I am trying to apply a custom 403 template to display instead of the browser default. I have a Middelware that looks something like this: from django.http import HttpResponseForbidden class CheckUserTypeMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if request.user.is_authenticated: allowed_types = ['a', 'b', 'c', 'd', 'e'] user_data = get_some_AD_values if user_data.get('a_key') not in allowed_types: return HttpResponseForbidden() response = self.get_response(request) return response views.py def error_403(request, exception): return render(request, 'my_app/403.html') # I have a 404.html in the same folder as the 403 and that renders fine. urls.py handler403 = 'my_app.views.error_403' settings.py DEBUG = False MIDDLEWARE = [ # Default Django middlewares untouched 'my_app.middleware.my_middleware.CheckUserTypeMiddleware', ] The same process I have above worked for 404 errors, but for some reason, I cant get it to work with 403 errors. -
Hey! actually i want to clear my database (postgres - pgadmin) because it is not working correctly so please help me out to delete the database
Hey actually i want to just delete everything from database and I want to just start the fresh database so please help me out to delete all the database and just start new one in postgres -
Update django page from firebase without page refresh
I wanted to make a django page that reads information from firebase, and print it out to my output.html page without having to reload or refresh the page. The data in firebase will be updated while the output.html loads (after a button click), and it will take a few minutes before rendering and redirect to the next page. I have read online that i will have to use AJAX requests in an interval to get the updated data from firebase and display it in the html page. Are there any other suggestions for me to get this done? -
Django models class object is not iterable
In a django project i have created a model class having a foreign key. model class When i tried to get objects in a variable by classname.objects.get(parameters=value). assigning objects into a variable Now when to display the object's attributes html by django template. iterating through objects now when i run the program i am getting error of 'Bid' object is not iterable. how to correct this code to working? thankyou -
How to return the instance of object when using __str__
Currently the objects in my model is displayed like this model_name object(1). Is it possible to use__str__ to change it into something like string(1) and string(2) etc. for each object added. -
Where to perform database operations on django class based views
I have a django ListView that gets items from my database. In addition to perform this task, I need to insert a record in my database indicating each time that a given user accessed this view. In order to do this, I could override any method that gets called when accessing the view, for example: class MyListView(ListView): def get_context_data(self, **kwargs): insert_record_to_db(self.request.user) return super().get_context_data(**kwargs) Or: class MyListView(ListView): def dispatch(self, request, *args, **kwargs): insert_record_to_db(self.request.user) return super().dispatch(request, *args, **kwargs) My question is: is there a best method to override when performing such actions? Why is it so? -
Get Authenticated User in Django Template with JWT Authentication
I am using Django Rest Framework and in it using JWT Authentication to authenticate users. I can see the data as the user IsAuthenticated, but when I do following: <h1>{{request.user}}</h1> in templates it return AnonymousUser. Is there any way that i can get object of logged user in template while using the JWT Authentication. Thanks -
Django / DRF unit testing CI pipeline without PostgreSQL running
Improving my bad testing habits with this new Django / DRF project I'm working on. Reading through the Django testing documentation, the DRF testing documentation, and various other blogs I've come across to figure out how I should be approaching this. One issue I'm trying to resolve is when it comes to running unit tests in the CI pipeline. Locally, I have PostgreSQL running, so testing models, serializers, responses, etc. will work fine. However, in the CI pipeline, I don't. PostgreSQL won't be running until E2E testing which is two stages after my unit tests. It seems like I should still be able to test views, serializers, and models without having a database running. Is there a data faker of some kind that I should be using? Is there a different method for testing this? -
How to display user based on role in Another Model
models.py class Employee(models.Model): ROLE = ( ('Courier', 'Courier'), ('Receptionist', 'Receptionist'), ('Admin', 'Admin') ) user = models.OneToOneField(User,null=True, on_delete=models.CASCADE) fullname = models.CharField(max_length=400, null=True) role = models.CharField(max_length=200, null=True, choices=ROLE) active = models.BooleanField(default=False, blank=True, null=True) def __str__(self): return self.fullname class OutgoingMail(models.Model): mail_ref = models.CharField(max_length=250, null=True) mail_to = models.CharField(max_length=250, null=True) courier = models.ForeignKey(Employee, null=True, on_delete=models.SET_NULL) def __str__(self): return self.mail_to So, my question is : How to display courier name in Outgoing mail, based on courier role in Employee model. Only display courier where role is 'Courier' ? -
Looping through a list of 5 elements only get result for 1 element
Sorry to ask this seemly simple question. I encountered a strange behavoir where looping through a list of 5 elements only gets result for 1 element. The code is: print("Size of npa_util is %i" % len(npa_util)) print("nap_util is %s" % npa_util) for (ac, util) in npa_util: print("util.id is %s" % util.id) print("ac.category is %s" % ac.category) print("util.limit is %s" % util.limit) the output is: Size of npa_util is 5 nap_util is [(<AssetClassRestriction: DRV_248_LE_BNS:r>, <IntradayNPARecord: DRV_248_LE_BNS:req_SDC223_1611329111171109:2017/12/01>), (<AssetClassRestriction: DRV_248_LE_BNS:t>, <IntradayNPARecord: DRV_248_LE_BNS:req_SDC223_1611329111171109:2017/12/01>), (<AssetClassRestriction: DRV_248_LE_BNS:e>, <IntradayNPARecord: DRV_248_LE_BNS:req_SDC223_1611329111171109:2017/12/01>), (<AssetClassRestriction: DRV_248_LE_BNS:c>, <IntradayNPARecord: DRV_248_LE_BNS:req_SDC223_1611329111171109:2017/12/01>), (<AssetClassRestriction: DRV_248_LE_BNS:I>, <IntradayNPARecord: DRV_248_LE_BNS:req_SDC223_1611329111171109:2017/12/01>)] util.id is 150 ac.category is r util.limit is [[14691, 999999999999999.0, 4819920.0]] since the number of elements of the list is 5, I expect the lines 3,4,5 output will report 5 times. However, it seemed the loop only went through one element. -
Webpack not updating page when I refresh to reflect new code
So I am doing a project using Django and React. I was working on it yesterday and it worked fine, but today after I run the command 'py ./manage.py runserver' along with 'npm run dev', my project loads but whenever I make changes to my code, these changes are not reflected when I update the page. I tried fixing this but couldn't do it so far. Here are my files: webpack.config.js: const path = require("path"); const webpack = require("webpack"); module.exports = { entry: "./src/index.js", output: { path: path.resolve(__dirname, "./static/frontend"), filename: "[name].js", }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: "babel-loader", }, }, ], }, optimization: { minimize: true, }, plugins: [ new webpack.DefinePlugin({ 'process.env.NODE_ENV' : JSON.stringify('development') // This has effect on the react lib size }), ], }; package.json: { "name": "frontend", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "dev": "webpack --mode development --watch", "start": "react-scripts start", "build": "webpack --mode production" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "@babel/core": "^7.13.15", "@babel/preset-env": "^7.13.15", "@babel/preset-react": "^7.13.13", "babel-loader": "^8.2.2", "webpack": "^5.34.0", "webpack-cli": "^4.6.0" }, "dependencies": { "@babel/plugin-proposal-class-properties": "^7.13.0", "react": "^17.0.2", "react-dom": "^17.0.2", "react-icons": "^4.2.0", "react-router-dom": "^5.2.0" } } -
Django Channels 2.4 ... do WebSocket messages always arrive in order
Given a single client with a WebSocket connection to Daphne/Channels 2.4, are messages guaranteed to arrive in order that they are sent from the client? -
Filter Product by category using CBVs
hello im trying to filter my products using cbv views but the filter functions are not working. The process flow is to click on the category name then bring the products associated with the category. thanks my models.py: class Category(models.Model): Category_name = models.CharField(max_length=248, primary_key=True) Sub_category =models.CharField(max_length=248, null=True, blank=True) slug = models.SlugField(unique=True, blank=True) #find out about get_absolute_url def save(self, *args, **kwargs): self.slug = slugify(self.Category_name) super(Category, self).save(*args, **kwargs) def get_absolute_url(self): return reverse ('store:cat', kwargs={'slug':self.slug}) def __str__(self): return self.Category_name class Meta: verbose_name = 'Category' verbose_name_plural = 'Categories' class Product(models.Model): Product_id = models.IntegerField(primary_key=True) Product_name = models.CharField(max_length=100) Product_image = models.ImageField(null=True,blank=True) Price = models.DecimalField(max_digits=12, decimal_places=2) discount_price = models.DecimalField(null=True, max_digits=12, decimal_places=2) Quantity = models.PositiveIntegerField() description = models.TextField(null=True) category = models.ManyToManyField(Category) def get_absolute_url(self): return reverse('store:prod',kwargs={'pk':self.Product_id}) def __str__(self): return self.Product_name Views.py:(the filter function is not working) class ProductListView(ListView): model= models.Product context_object_name = 'product_list' template_name = 'store/product_list.html' def get_context_data(self, **kwargs): context=super().get_context_data(**kwargs) context['cat'] = Category.objects.all() return context class CategoryList(DetailView): model=models.Category context_object_name = 'categ' template_name = 'store/categlist.html' def get_queryset(self): result=Product.objects.filter(category__Category_name=Category_name) return result -
django test method mock persists with command
first_app/tests/test_file.py from unittest.mock import patch from django.core.management import call_command from django.test import TestCase class TestWierdo(TestCase): @patch('first_app.class_a.method_to_import') def test_b(self, mock_obj2): call_command('this_is_command', item='abcd') print(mock_obj2.call_args) # prints "i should be called for test_b, call('abcd')", this is good so far # will have issue here later. self.assertTrue(False) first_app/management/commands/this_is_command.py from django.core.management import BaseCommand from first_app.class_a import method_to_call_from_command class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument( '--char', action='store', dest='item', ) def handle(self, *args, **options): char = options['item'] method_to_call_from_command(str(char)) first_app/class_a.py from first_app.class_b import method_to_import def method_to_call_from_command(a): print('i should be called for test_b') generated = method_to_import(a) return generated first_app/class_b.py def method_to_import(a): return All is good, but let's add another test in TestWierdo class with a mistake: class TestWierdo(TestCase): @patch('first_app.class_a.method_to_call_from_command') <- Notice wrong mock path here. # @patch('first_app.management.commands.this_is_command.method_to_call_from_command') <- correct one def test_a(self, mock_obj): call_command('this_is_command', item='test') # commenting this line also fixes the issue print(mock_obj.call_args) # print 'test' self.assertTrue(False) @patch('first_app.class_a.method_to_import') def test_b(self, mock_obj2): call_command('this_is_command', item='abcd') print(mock_obj2.call_args) <----- # print None !!!!, does not print i should be called for test_b self.assertTrue(False) What is going on here? It seems like the mock persists from test_a. Commenting out call_command('this_is_command', item='test') or wrong mock patch decorator fixes the issue. But why does wrong mock from the test_a affect test_b? -
how to get self.id in django classview
When using class view(ListView) in django, is there a way to get self.id with def get_qeuryset and then use this id in def get_context_data? I need self.id in def_get_context. However,'Queryset object has no attribute'id' error is displayed. If this is the case, I would like to use context[''] to get self.id.