Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ApartmentFilterSet resolved field 'geom' with 'exact' lookup to an unrecognized field type PointField
I have a filters.py file that uses django-filter app. But when I try to filter apartments by subcity, it throws an exception ApartmentFilterSet resolved field 'geom' with 'exact' lookup to an unrecognized field type PointField. I used a filterset override, this error won't go away. import django_filters from django.contrib.gis.db import models as geo_models from .models import Apartment class ApartmentFilter(django_filters.FilterSet): ADKT = 'Addis Ketema' AKLT = 'Akaki-Kality' ARDA = 'Arada' BOLE = 'Bole' GLLE = 'Gulele' KLFE = 'Kolfe-Keranio' KIRK = 'Kirkos' LDTA = 'Lideta' YEKA = 'Yeka' NFSL = 'Nefas Silk-Lafto' SUBCITY_CHOICES = [ (ADKT, 'Addis Ketema'), (AKLT, 'Akaki-Kality'), (ARDA, 'Arada'), (BOLE, 'Bole'), (GLLE, 'Gulele'), (KLFE, 'Kolfe-Keranio'), (KIRK, 'Kirkos'), (LDTA, 'Lideta'), (NFSL, 'Nefas Silk-Lafto'), (YEKA, 'Yeka')] class Meta: model = Apartment fields = ['apt_subcity', 'apt_cost','geom'] filter_overrides = { geo_models.PointField: { 'filter_class': django_filters.CharFilter, 'extra': lambda f: { 'lookup_expr': 'exact', }, } } ordering = django_filters.ChoiceFilter(label='Ordering',subcity_choices=SUBCITY_CHOICES, method='filter_by_ordering') -
ImportError: Couldn't import Django inside virtual environment?
I created a django project, set up a virtual environment, and added django with poetry add. inside pyproject.toml: [tool.poetry.dependencies] python = "^3.9" psycopg2-binary = "^2.9.3" Django = "^4.0.1" When I run command to create an app: p manage.py startapp users apps/users I get this error: Traceback (most recent call last): File "/graphql/graphenee/manage.py", line 22, in <module> main() File "/graphql/graphenee/manage.py", line 13, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? venv is set, activated, django is installed but I am still getting this error. Inside virtual envrionment I start python shell and i get this error: Python 3.9.7 (default, Sep 16 2021, 13:09:58) [GCC 7.5.0] :: Anaconda, Inc. on linux Type "help", "copyright", "credits" or "license" for more information. >>> import django Traceback (most recent call last): File "<stdin>", line 1, in <module> ModuleNotFoundError: No module named 'django' Django is also globally installed and when I start the python shell in global environment, I can import django: Python 3.9.7 (default, Sep 16 2021, 13:09:58) [GCC 7.5.0] :: Anaconda, Inc. on linux Type "help", "copyright", "credits" or "license" for more information. >>> … -
How to access requested user object from jwt token in django serializers?
After user-registration, user wants to post data into Client model ( OnetoOne relationship with User model ). So, I want to access the requested user object inside the serializer-class to create a new row in Client model associated with the requested user. models.py class Client(models.Model): user= models.OneToOneField(User, on_delete=models.CASCADE, null=False, blank=False) sex = models.CharField(max_length = 6, blank=False, null=False) location = models.CharField(max_length = 30, null = False, blank = False) views.py class ClientRegister(GenericAPIView): def post(self, request): user = request.user serializer = ClientSerializer(data= request.data) if serializer.is_valid(): serializer.save() return Response(status= status.HTTP_201_CREATED) else: return Response(data= 'Invalid Form', status= status.HTTP_400_BAD_REQUEST) serializers.py class ClientSerializer(serializers.ModelSerializer): class Meta: model = Client fields = ['sex', 'location'] def create(self, validated_data): sex = validated_data.get('sex') location = validated_data.get('location') user = #------ Want requested user object here ------# if user.is_client: client = Client(user=user, sex=sex, location=location, company=company, experience=experience) client.save() return client I have manually added user oject into the data in serializer = CientSerializer(data=request.data). But, It didn't work. Please, tell me how to pass it from views.py or how to access it in serializers.py. -
Django Make a Left Join with new col or empity field
i need print all items but also i need know if current user request.user have that item in list with SQL is just something like select * from item as i Left JOIN UserItems as ui ON ui.item=i.id left Join user as u ON ui.user=u.id so i just need check if u.id is not null, how i have to do with django for get all item list? class User(AbstractUser): email = models.EmailField(unique=True) birthday = models.DateField(blank=True, null=True) class UserItems(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) class Item(models.Model): name = models.CharField(max_length=250 ) created = models.DateTimeField(default=timezone.now) obviously UserItems.objects.filter(useritem__user=request.user) dosen't get all items -
Django how hide empty category
I have a hoodie category and two gender divisions male and female. How can I hide a category hoodie for a gender that does not have this product? {% get_genders as genders %} {% for gender in genders %} <li> <!-- First Tier Drop Down --> <label for="drop-2" class="toggle">Категории <span class="fa fa-angle-down" aria-hidden="true"></span> </label> <a href="/">{{ gender }} <span class="fa fa-angle-down" aria-hidden="true"></span></a> <input type="checkbox" id="drop-2"> <ul> {% get_category as categories %} {% for category in categories %} <li><a href="{% url 'category' gender_slug=gender.slug category_slug=category.slug %}">{{category.name}}</a> </li> {% endfor %} </ul> </li> {% endfor %} I'm try make many to many field gender for category, but I don't know how to write in html models.py class Gender(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(max_length=200, unique=True) class Meta: verbose_name = 'Гендер' verbose_name_plural = 'Гендеры' def __str__(self): return self.name def get_absolute_url(self): return reverse('gender', kwargs={'gender_slug': self.slug}) class Category(models.Model): name = models.CharField(max_length=100) gender = models.ManyToManyField(Gender) slug = models.SlugField(max_length=200, unique=True) class Meta: verbose_name = 'Категория' verbose_name_plural = 'Категории' def __str__(self): return self.name def get_absolute_url(self): return reverse('category', kwargs={'category_slug': self.slug}) -
Django Aggregation: highest sum in categories
Hy Guys I was wondering how I can get the highest sum of one category. So i have a model with my categories and a model with my costs which contains a cost category. My models.py from django.db import models class CostCat(models.Model): name = models.CharField(max_length=50, default=None, null=True, blank=True) class Cost(models.Model): name = models.CharField(max_length=50, default=None, null=True, blank=True) cost_category = models.ForeignKey(CostCat, on_delete=models.CASCADE) amount = models.DecimalField(max_digits=12, decimal_places=2,null=True, blank=True) The result should be that I can show the category with the highest sum of costs. I have been stuck on that for hours now. The closest i got was with my tests as shown below. I can print out all the sums and its respective category but now I now need to find out how to get the category and the value of the highest sum. And i'm really in a spiral right now. views.py def metrics(request): tests = CostCat.objects.annotate(sum=Sum('cost__amount')) for test in tests: print(test, test.sum) return render(request, 'metrics.html', "topcostcat":test, "topcostcatsum":test.sum ) Much appreciated if you could me a bit out! Thanks in advance -
What is easiest UPDATE ImageField in Django Rest Framework and delete old image?
I want to update my image field and delete the old one using the Django-rest framework. this is my model class GroupPostsModel(models.Model): post_text = models.CharField(max_length=1000) post_type = models.CharField(max_length=20) image = models.ImageField(blank=True, null=True, upload_to='post_images/') document = models.FileField(blank=True,null=True, upload_to='post_documents/') likes = models.IntegerField(default=0) time_stamp = models.DateTimeField(auto_now=True) group = models.ForeignKey(GroupsModel, on_delete=models.CASCADE) user = models.ForeignKey(UserModel, on_delete=models.CASCADE) class Meta: db_table = 'group_posts' My views.py is as follow @api_view(['PATCH']) def save_edited_post_image(request): image = request.data.get('image') print('image == ') print(request.data.get('image')) post_id = request.data.get('post_id') print('post id = '+str(post_id)) try: GroupPostsModel.objects.filter(id=post_id).update(image=image) resp = { 'resp' : 'Post image updated...!' } except Exception as e: print(e) resp = { 'resp': 'Error: Post image update failed...!' } return Response(resp) Code doesn't throw errors but does not work as expected. In the database it stores the value as image_name.jpeg; Expected value to be stored: post_images/1640341471608.jpeg -
In django how to get the all the data from table one with the related data from the table two in a single context
I have two classes in my models.py which are item and batch. I need to get all the data of item also the appropriate batch_id from the class batch. How should I write my views.py to get all the data to a single context class item(models.Model): item_name=models.CharField(max_length=100) item_code=models.IntegerField() min_stock=models.IntegerField() current_stock=models.IntegerField() def __str__(self): return self.item_name class batch(models.Model): batch_id=models.IntegerField() item_name=models.CharField(max_length=100) item_code=models.IntegerField() def __str__(self): return self.item_name -
how to had more 50000 urls in django sitemap
path( 'sitemap.xml', sitemap, { 'sitemaps': sitemaps }, name='django.contrib.sitemaps.views.sitemap' ), this above example is my sitemap config in Project level urls.py from django.contrib.sitemaps import Sitemap from .models import Post class PostSitemap(Sitemap): changefreq = 'always' priority = 0.9 protocol = 'https' limit = 5 def items(self): return Post.aupm.all() def lastmod(self, obj): return obj.updated this above code is for sitemaps.py in application level which generating this code <urlset> <url> <loc> https://localhost:8000/en/kavi/lobaan-ke-5-laabh-aur-upyog-aur-7-mithk-0x76/ </loc> <lastmod>2022-01-28</lastmod> <changefreq>always</changefreq> <priority>0.9</priority> </url> <url> What I want is : what to do if i have much more element in more than 50,000 (fifty thousand) element in that application, If i want to add more element(ie sitemap) from diffrent application -
How do I assign incrementing variable names from form data
I am relatively new to Django and have created my first live project. I am currently going through my code to refactor it and was wondering if there's a way to assign these variables to the form data in a way that uses more lines and is clearer. Since my variable names for the form all start with "specific_variable", I was thinking of having a for loop for the form data that assigns incrementing variable names such as "specific_variable1" and "specific_variable2". Would this work or is the way I currently assign variable names to form data fine? views.py # destination results view def get_ranking(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = RankingForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required specific_variable1 = form.cleaned_data['specific_variable1'] specific_variable2 = form.cleaned_data['specific_variable2'] specific_variable3 = form.cleaned_data['specific_variable3'] specific_variable4 = form.cleaned_data['specific_variable4'] specific_variable5 = form.cleaned_data['specific_variable5'] -
Setting monthly usage limit - Django API
I am going through Django rest framework documentation and other questions here trying to figure if there is a way to customize it for monthly rate limit by user-group. logic: User A - Group 1 User B - Group 2 Group 1 - allowed 10 calls per month to endpoint Group 2 - allowed 100 calls per montg any help is much appreciated, I am new to Django and fascinated by DRF -
How to dynamically import Django settings variables?
I want to import Django settings dynamically. something like this: from django.conf import settings settings.get('TIMEOUT_CONFIG', 10) but this thing doesn't work. I also tried this settings.__dict__.get('TIMEOUT_CONFIG') but this thing also won't work before I call it like this settings.TIMEOUT_CONFIG -
Django group by month with possible zeros
Am creating an chart for data analytics. So i need to group the count by month for the whole year. My model: Class Application: reference, created_at From the above, i need count of applications for each month for the current year. And with the current query i get all the data but i am not getting data for the months which no data is available: My query: queryset = Application.objects.filter(user=user).annotate(month=TruncMonth('created_at')).values('month').annotate(_applications=Count('id')).order_by('month') For example, If i have data for month Jan and Feb the above query gives data of those only but i need the data to contain "0" for all non data available months: If March doesnt have data means, the result should be "0" for that month. How to do this ? -
My images are created in base dirrectory tell me how to display images from this base dirrectory in django
Dear Django developer I need your kind help. I'm new to Django, guide me on how to display images by setting the base directory path. I did not know what to write in views, URLs, HTML page to display an image using Django. or also guide me on how to download PNG, JPG, and PDF images. -
Django query returning empty result
This is my model class MenuItem(models.Model): name = models.CharField(max_length=500, null=False) description = models.CharField(max_length=500, null=True) image_url = models.CharField(max_length=1000, null=True) menu_category = models.ForeignKey(MenuCategory, on_delete=models.CASCADE) def __str__(self): return f'{self.name}' class Venue(models.Model): name = models.CharField(max_length=500, null=False) def __str__(self): return f'{self.name}' class VenueMenu(models.Model): venue = models.ForeignKey(Venue, null=False, on_delete=models.CASCADE) menu_item = models.ManyToManyField(MenuItem, null=False) This is my serializer class MenuItemSerializer(serializers.ModelSerializer): menu_category = MenuCategorySerializer() class Meta: model = MenuItem fields = '__all__' class VenueMenuSerializer(serializers.ModelSerializer): menu_item = MenuItemSerializer(many=True) class Meta: model = VenueMenu fields = '__all__' and this is my view @api_view(['GET']) def venue_menu_response_detail(request): if request.GET.get('venue'): venue_menu_list = VenueMenu.objects.filter(venue__name=request.GET.get('venue')) serializer = VenueMenuSerializer(venue_menu_list, many=True) return Response(serializer.data) this is my request http://127.0.0.1:8000/venue_menu_response_list?venue=venu_name I want to get the details of menu items associated with a single venue this query has the response of 200 OK but it is returning empty. When am querying on the basis of venue id am getting the desired result but I want to get the result on the basis of the name -
Django Database Design Problem - Multiple App Single Database
I have two django applications using the same database. These applications have their own models. Since both applications use the same database, I can authorize with common users, I can use User model as foreign key for models. Let's call these two django apps A and B. Because A and B use the same database, a user can be associated with models in both applications. If a user is associated with a model in both applications, the user I deleted from application A cannot be deleted because it is associated with a model in application B. I think I made a wrong design. How can I overcome this problem? -
Sum of averages raw query
I have the following code that I have to optimize: These are the models: class Question(models.Model): label = models.CharField(max_length=255, verbose_name='Question') class Response(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) submit_date = models.DateTimeField() int_val = models.IntegerField(null=True, blank=True, verbose_name='Int Response') class Plan(models.Model): name = models.CharField(max_length=100) questions = models.ManyToManyField(Question, through='PlanQuestion') start_date = models.DateField(null=True) completion_date = models.DateField(null=True) class PlanQuestion(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) plan = models.ForeignKey(Plan, on_delete=models.CASCADE) target_score = models.FloatField() target_percentage = models.FloatField() And here is the unoptimized code: plans = Plan.objects.filter(start_date__isnull=False, completion_date__isnull=False) sum_of_averages = 0 total_plans = 0 for plan in plans: plan_questions = plan.questions.through.objects.filter(plan=plan) sum_of_scores = 0 total_plan_questions = 0 for plan_question in plan_questions: cur_date = datetime.now().date() start_date = plan.completion_date end_date = start_date if start_date and (cur_date > plan.completion_date) else cur_date query = """ SELECT id, COUNT(*) AS count, AVG(int_val) AS int_average FROM Response WHERE question_id=%(question_id)s AND DATE(submit_date) >= %(stard_date)s AND DATE(submit_date) <= %(end_date)s """ score = Response.objects.raw(query,params={'question_id': plan.question.id, 'start_date': plan.plan.start_date if plan.plan.start_date else end_date, 'end_date': end_date }) sum_of_scores += score[0].int_average total_plan_questions += 1 question_avg = sum_of_scores / total_plan_questions if total_plan_questions else 0 sum_of_averages += question_avg total_plans += 1 return sum_of_averages / total_plans if total_plans else 0 As you can see in the above code for every question of the plan, a score is calculated, … -
Need help to make a query from django model
I have a CustomUser model, working fine . It stores a value in otp table everytime on save instance. but i want to send this pre saved otp value through email . email function is working good but i don't how to make query here for that specific user who wants get the otp. as every user would have a random value. here is the code. #models.py class CustomUser(AbstractUser): username = None phone_regex = RegexValidator( regex=r'^\+?1?\d{9,14}$', message="Phone number must be entered in the form of +129999999999.") phone_number = models.CharField(validators=[phone_regex], max_length=17, unique=True, verbose_name='Phone Number', blank=False) email = models.EmailField(_('email address'), unique=True) isPhoneVerified = models.BooleanField( verbose_name='Is Phone Number Verified?', default=False) isEmailVerified = models.BooleanField( verbose_name='Is Email Verified?', default=False) otp = models.CharField(max_length=6) USERNAME_FIELD = 'phone_number' REQUIRED_FIELDS = ['email'] objects = CustomUserManager() def __str__(self): return self.phone_number + " | " + self.email # Method to Put a Random OTP in the CustomerUser table to get verified for the next time after save. def save(self, *args, **kwargs): number_list = [x for x in range(10)] # list comprehension code_items = [] for i in range(6): num = random.choice(number_list) code_items.append(num) code_string = "".join(str(item) for item in code_items) # list comprehension again # A six digit random number from the … -
How to arrange forms fields vertically?
I am creating a login form by using the Forms class. Unfortunately, when I run the page I found the arrangement of the fields is horizontal. Can you help me to make it vertically, please? In the bellow the forms.py code: from django import forms class LoginForm(forms.Form): username = forms.CharField(label='Your name', max_length = 50) password = forms.CharField(max_length = 50, widget=forms.PasswordInput) And here is the views.py code: from django.shortcuts import render from .models import Login from .forms import LoginForm # Create your views here. def login_function(request): try: username = request.POST.get('username') password = request.POST.get('password') data = Login(username = username, password = password) data.save() except: x = 'error' return render(request,'pages/login.html', {'loginform':LoginForm}) And here is login.html code: {% block content %} <form method="POST"> {% csrf_token %} {{loginform}} <input type="submit" value="Save"> </form> {% endblock content %} -
Invalid block tag on line 5149: 'endif'. Did you forget to register or load this tag? Where am I wrong?
I'm not sure where I am going wrong here. I believe I have followed every rule here. Please point out if I missed something. I'd appreciate your help. (% if tot86|floatformat > 0 %) <div class="row"> <div class="col-8 text-start fs2 border-bottom border-end border-start border-dark"><b>Income</b></div> <div class="col-2 text-center fs2 border-bottom border-end border-dark"><b>{{tot86|floatformat}}</b></div> <div class="col-2 text-center fs2 border-bottom border-end border-dark"><b>{{tot86|floatformat}}</b></div> </div> <div class="row"> <div class="col-8 text-start fs2 border-bottom border-end border-start border-dark"><b>AMOUNT PAYABLE</b></div> <div class="col-2 text-center fs2 border-bottom border-end border-dark"><b>{{tot90|floatformat}}</b></div> <div class="col-2 text-center fs2 border-bottom border-end border-dark"><b>{{tot91|floatformat}}</b></div> </div> {% endif %} -
i got an error in my forms.py file of project
` from django import forms from django.core import validators from matplotlib import widgets from .models import * class Userregistration(forms.ModelForm): class Meta: model=User fields=['username','password','name','email_id','contact','address'] widgets={ 'username':forms.CharField(attrs={'class':'form-control'}), 'password':forms.PasswordInput(attrs={'class':'form-control'}), 'name':forms.CharField(attrs={'class':'form-control'}), 'email_id':forms.EmailField(attrs={'class':'form-control'}), 'contact':forms.CharField(attrs={'class':'form-control'}), 'address':forms.CharField(attrs={'class':'form-control'}), } ` it is showing me typeerror:'__init()'got an unexpected keyword argument 'attrs' -
List field names of a model as choices in the field of another model
Unfortunately, I cant find exactly what I need but I know it requires get_fields() Id am guessing I would need a method call to create the list of field names : class ModelA(models.Model): field_a = models.CharField(max_length=100) field_a = models.CharField(max_length=100) field_a = models.CharField(max_length=100) field_a = models.CharField(max_length=100) class ModelB(models.Model): fields = models.CharField(max_length=100, null=True, blank=True, choices=field_names_of_modela()) def field_names_of_modela(): return [field.name for field in ModelA._meta.get_fields()] The above code wont work... Is there a way to get field names of another model as a list in this model? Thanks -
why django admin template doesn't load
Since I had started Django, I'm tackling some ridiculous problems. Recently, when I start a new project and I run it on the server, Django's admin CSS is not loaded. The last project I ran on the server, after a while it was okay, and the real Django admin template was there and the CSS was loaded and it was working. But this time again the same problem happened and I don't know how to solve it cause the projecthere is the photo is raw, with no special code. I would be glad if you can help me -
Django queryset evaluation and bulk_update with dependencies
Suppose I have the following model (vastly simplified, for the sake of the question): class DailyMetric(models.Model): value_1 = models.FloatField() value_2 = models.FloatField() ratio = models.FloatField() As the name suggests, there will be an entry for each day. However, value_1 and value_2 depend on the values from the previous day. Let's say, the calculation is as follows: def update_values(instance, previous_instance): if previous_instance: instance.value_1 = previous_instance.value_1 + 5 instance.value_2 = previous_instance.value_2 - 15 instance.ratio = instance.value_1 / instance.value_2 Naturally, if I update the value for the first of the previous month, I have to update all following instance. For performance reasons, I want to make use of 'bulk_update': # member method of the model class def update_following(self): following_entries = self.get_following_entries() if not following_entries.exists(): return for i in range(following_entries.count()): if i == 0: update_values(following_entries[i], self) else: update_values(following_entries[i], following_entries[i-1]) DailyMetric.objects.bulk_update(following_entries, ['value_1', 'value_2', 'ratio']) However, it seems, that update_values always gets the instance with the values stored in the database, even though its "python" representation has been modified in the previous iteration. If I cast the queryset to a list beforehand, it works as expected. But in my understanding a queryset is evaluated lazy, and by accessing one value, the query has to be executed … -
Gunicorn failes because ModuleNotFoundError: No module named celery
I have moved my django app from my local environment to a server. I installed all the dependencies that my local environment has. However, gunicorn is failing because it says: from celery import Celery "ModuleNotFoundError: No module named celery I have already installed Celery via pip (pip install celery). Run celery, celery-beat, and flower run in terminals successfully. Also, from the Python shell, I get the following: >>> from celery import Celery >>> Celery <class 'celery.app.base.Celery'> So it seems like Celery is installed and even working, but for some reason my app is failing to due celery not being recognized. Any help identifying the problem would be appreciated.