Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Django custom user, cant login to django admin panel
I created my custom user which uses phone number as username. but for some reason, I can't log in to the admin panel. Note: I can create a superuser through cli successfully. custom User model: class User(AbstractBaseUser, PermissionsMixin): """ Custom user model """ phone = PhoneNumberField(unique=True) full_name = models.CharField(max_length=255) verification_code = models.CharField(default="", max_length=5) is_staff = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = "phone" def __str__(self): return self.full_name custom user Manager: class UserManager(BaseUserManager): def create_user(self, phone, full_name, password=None, **extra_fields): validate_international_phonenumber(phone) if not phone: raise ValueError("a phone number must be provided.") user = self.model( phone=phone, full_name=full_name, verification_code = generate_verification_code(), **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, phone, password): validate_international_phonenumber(phone) user = self.create_user(phone, password) user.is_staff = True user.is_superuser = True user.save(using=self._db) return user user serializer class: class UserSerializer(serializers.ModelSerializer): class Meta: model = get_user_model() fields = ["id", "phone", "full_name"] extra_kwargs = { "id": {"read_only": True} } -
Python-Django: Add permissions to specific groups after a model is created
I have this group known as "administrator" and its suposed to have permissions to create, view, change and delete any model. So the thing is that I want to, after a new model is created (not instanced) that my system automatically detect this new model and give all permissions to my group. -
I am unable to retrieve content of ace editor in django
I am working on app which runs the c++ code in webpage. For that I am trying to use Ace editor as code editor. I am able to write code in it. I used django-ace here. But how to retrieve content in my views.py file. Below is the forms.py file from .models import Snippet from django import forms from django_ace import AceWidget class SnippetForm(forms.ModelForm): class Meta: model = Snippet widgets = { "text": AceWidget(mode='c_cpp', theme='twilight',width="800px", height="600px",), } exclude = () below is views.py file : from .forms import SnippetForm from .models import Snippet from django.shortcuts import render, redirect def simple(request): if request.method == 'POST': form = SnippetForm(request.POST) print('This is form : ', form) if form.is_valid(): form.save() return render(request, "snippets.html", { "form": form, "snippets": Snippet.objects.all() }) else: form = SnippetForm() return render(request, "snippets.html", { "form": form, "snippets": Snippet.objects.all() }) below is html file: <!DOCTYPE html> <html> <head> <title>An simple example with django-ace</title> {{ form.media }} </head> <body> <form action="" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit"/> </form> </body> </html> when I am printing form in views.py file I am getting output like this: This is form : <tr><th><label for="id_text">Text:</label></th><td><div class="django-ace-editor"><div style="width: 800px" class="django-ace-toolbar"><a href="./" class="django-ace-max_min"></a></div><div class="django-ace-widget loading" data-behaviours="true" data-mode="c_cpp" … -
Django ORM query returns wrong number of items
In my application users can create lists and add influencers to them. My User and InfluencerList models have M2M relation. InfluencerList model have also M2M relation with InstagramInfluencer, YoutubeInfluencer, ... Here is my query for getting users all lists and influencer counts in it, which works finely: users_all_lists = request.user.lists.all().annotate( instagram_count=Count('influencers', distinct=True), youtube_count=Count('youtube_influencers', distinct=True), tiktok_count=Count('tiktok_influencers', distinct=True), twitch_count=Count('twitch_influencers', distinct=True), clubhouse_count=Count('clubhouse_influencers', distinct=True) ).values( 'id', 'name', 'instagram_count', 'youtube_count', 'tiktok_count', 'twitch_count', 'clubhouse_count', ).distinct().order_by('created_at') I also want to return those influencers usernames, so I added foreign key lookups to .values() function: users_all_lists = request.user.lists.all().annotate( instagram_count=Count('influencers', distinct=True), youtube_count=Count('youtube_influencers', distinct=True), tiktok_count=Count('tiktok_influencers', distinct=True), twitch_count=Count('twitch_influencers', distinct=True), clubhouse_count=Count('clubhouse_influencers', distinct=True) ).values( 'id', 'name', 'instagram_count', 'youtube_count', 'tiktok_count', 'twitch_count', 'clubhouse_count', # ADDED THIS ONE LINE BELOW 'influencers__username', 'tiktok_influencers__username', 'youtube_influencers__channel_title', 'twitch_influencers__username', 'clubhouse_influencers__username' ).distinct().order_by('created_at') When a User has one InfluencerList with 2 influencers in it, this query returns 2 items which is not what I expected. Here is my InfluencerList model if it's necessary: class InfluencerList(models.Model): name = models.CharField('Name:', unique=True, max_length=40, blank=False, null=False) created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='lists') influencers = models.ManyToManyField('Influencer', related_name='lists', blank=True) tiktok_influencers = models.ManyToManyField('TiktokInfluencer', related_name='lists', blank=True) youtube_influencers = models.ManyToManyField('YoutubeInfluencer', related_name='lists', blank=True) twitch_influencers = models.ManyToManyField('TwitchInfluencer', related_name='lists', blank=True) clubhouse_influencers = models.ManyToManyField('ClubhouseInfluencer', related_name='lists', blank=True) I have spent much time in Django … -
Serializing specific fields from another model
I was trying to serialize policy_length, coverage_amount from Policy model and use it in a serializer that was using Insuree model. I'm using Policy and Insuree models: Policy model class Policy(TimeStampedModel): policy_length = models.FloatField(max_length=2, blank=True, null=True) coverage_amount = models.FloatField(max_length=256, blank=True, null=True) Insuree model class Insuree(TimeStampedModel): user = models.OneToOneField( 'User', related_name='insuree', null=False, on_delete=models.CASCADE, primary_key=True) coverage_amount = models.ForeignKey(Policy, on_delete=models.CASCADE, max_length=256, blank=True, null=True) policy_length = models.ForeignKey(Policy, on_delete=models.CASCADE, max_length=2, blank=True, null=True) class PolicySelectionSerializer(serializers.ModelSerializer): class Meta: model = Insuree fields = ('age', 'gender', 'disposable_income') #Current fields fields = ('age','gender',disposable_income', 'policy_length', 'coverage_amount') #The field I need and want to do -
How to get a sing tweet info?
I am trying to get the information of a tweet through a Django(Django-rest) app. I mean the number of likes, number of mentions, number of retweets, and impressions. I need something like a "Get" request, and the response to this request includes the information that I need. I really appreciate any help you can provide. -
Django DRF nested serializer
I'm new to DRF and trying to write a prototype of API for storing rectangle labels on a photo. my models: class Image(models.Model): file = models.FileField(blank=False, null=False) class Label(models.Model): image = models.ForeignKey(Image, blank=True, on_delete=models.CASCADE) start_x = models.IntegerField(default=0) start_y = models.IntegerFIeld(default=0) end_x = models.IntegerField(default=0) end_y = models.IntegerField(default=0) my serializers: from rest_framework import serializers class LabelSerializer(serializers.ModelSerializer): class Meta: model = Label fields = ['id', 'image', 'start_x', 'start_y', 'end_x', 'end_y'] class ImageSerializer(serializers.ModelSerializer): labels = LabelSerializer(many=True, read_only = True) class Meta: model = Image fields = ['id', 'file', 'labels'] When creating new image object in the following view I get image object, but no Labels objects created : from .serializers import ImageSerializer class ImageView(APIView): parser_classes = (MultiPartParser, FormParser) def post(self, request, *args, **kwargs): serializer = ImageSerializer(data=request.data) if serializer.is_valid(): serializer.save() response_data = {'id': serializer.data['id']} return Response(response_data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) API call: curl -i -X POST -H "Accept: application/json" -H "Content-Type: multipart/form-data" -F "file=@~/test.jpg" --form-string 'labels={[{"start_x": 0, "start_y": 0, "end_x": 100, "end_y": 200}]}' http://127.0.0.1:8000/api/create/ How should I modify ImageSerializer for making possible to create image with labels with one API call? -
Django Rest Framework APITestCase does not use JSON datatypes for all fields
Using DRF's APITestCase, I expect the results of an API test to be serialized to JSON datatypes. An object with a property size = decimal.Decimal('20.0') is correctly sent through the API endpoint as size: 20.0 (with the COERCE_DECIMAL_TO_STRING parameter set to True). However, when testing the endpoint with the APITestCase, the original data type is kept. APIClient.get(url).response.data.get("size").__class__ = decimal.Decimal The same happens with other complex types. Why is this? And can it be changed to seeing what the API client would receive? -
Import django models to custom python script
I am trying to create a custom python script within my Django application. This script requires the use of my app models. I am unable to figure out how to import the models appropriately to be used within this script. My project directory: -my_proj(name:ais) -my_app(name:pages) -__init__.py -models.py -urls.py ... -utils -__init__.py -custom_script.py So if I wanted to access the pages.models from the custom_script.py how might I do this? I have attempted various imports such as from django.core.management import settings and from django.core.wsgi import get_wsgi_application but I still get an error stating the following: ModuleNotFoundError: No module named 'pages' -
MySQL Similar Query in Django ORM
I have following query which is written in SQL I want to know how can I write same in Django ORM SELECT target_id, parameter_id, rating, value_date, id from gsrm_paramvalue a1 inner join ( SELECT `target_id` as target, `parameter_id` as parameter, MAX(`value_date`) as maxdate from gsrm_paramvalue WHERE `parameter_id` in (900, 919, 957, 981, 1002, 1029, 1049, 1092) AND `target_id` in (20, 21, 22, 23, 25, 29, 30, 31, 55, 60, 99, 107, 109, 110, 111, 113, 115, 117, 119, 124, 127, 128, 135, 136, 162, 219, 220, 221) AND `status` = 'A' AND `value_date` <= '2019-03-31' GROUP BY `target_id`, `parameter_id` order by parameter_id, target_id ) a2 on a1.target_id = a2.target AND a1.parameter_id = a2.parameter AND a1.value_date = a2.maxdate WHERE `parameter_id` in (900, 919, 957, 981, 1002, 1029, 1049, 1092) AND `target_id` in (20, 21, 22, 23, 25, 29, 30, 31, 55, 60, 99, 107, 109, 110, 111, 113, 115, 117, 119, 124, 127, 128, 135, 136, 162, 219, 220, 221) AND `status` = 'A' AND `value_date` <= '2019-03-31' GROUP BY `target_id`, `parameter_id` order by parameter_id, target_id -
Distinct on mysql with all items returned
I used PostgreSQL with Django in a query like this: Price.objects.filter(**converted_filters) .order_by( "tyre__ean", "updated_at" ) .distinct("tyre__ean") But i need to switch to MySQL and change this query. I know you can get 1 value returned by using this query: Price.objects.values( "tyre__ean", ) .distinct() .filter(**converted_filters) This works quite much the same. But i don't want just that value i need all of them and i prefer to make 1 query instead of 2. Is that possible and how can i do that?