Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django annotate by foreign key
This is my models.py: class Category(models.Model): category_des = models.CharField(max_length=250) class Type(models.Model): type_des = models.CharField(max_length=250) class Product(models.Model): category_id = models.ForeignKey(Category, on_delete=models.CASCADE) type_id = models.ForeignKey(Type, on_delete=models.CASCADE) product_name = models.CharField(max_length=250) product_price = models.FloatField() What I want to do is to divide products into menus list and extras list and group them by category like this: Category 1: extra 1.a extra 1.b menu 1.c menu 1.d Category 2: extra 2.e extra 2.f menu 2.g menu 2.h and this is what I did in views.py: class MenuList(generics.ListCreateAPIView): queryset = models.Product.objects.filter(type_id=1).annotate("category_id") serializer_class = serializers.ProductSerializer class MenuDetail(generics.RetrieveUpdateDestroyAPIView): queryset = models.Product.objects.filter(type_id=1).annotate("category_id") serializer_class = serializers.ProductSerializer class ExtraList(generics.ListCreateAPIView): queryset = models.Product.objects.filter(type_id=2).annotate("category_id") serializer_class = serializers.ProductSerializer class ExtraDetail(generics.RetrieveUpdateDestroyAPIView): queryset = models.Product.objects.filter(type_id=2).annotate("category_id") serializer_class = serializers.ProductSerializer I got this error: TypeError: QuerySet.annotate() received non-expression(s): category_id. -
Can't make Codemirror config works
I followed the guidelines from the official website of mirrorcode and for some reason I am able to make only some of the configuration options work. In the example below you can see that the "firstlinenumber" config works fine but the others don't seem to be taken into consideration (value, theme etc). Note that I'm using django framework. Code: <link rel="stylesheet" href="{% static 'polls/codemirror/codemirror.css' %}"> <div> <textarea id="codemirrorTextArea"" cols="80" rows="24"></textarea> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script type="text/javascript" src="{% static 'polls/codemirror/codemirror.js' %}"></script> <script type="text/javascript"> $(document).ready(function(){ var codeEditor = CodeMirror.fromTextArea(document.getElementById('codemirrorTextArea'),{ lineNumbers: true, theme:"dracula", tabsize:2, value:"15", mode:"python", firstLineNumber:5, }); }); </script> Output: -
How to display MultiSelectField in Template Django
I have a MultiSelectField in my models. I want to display MultiSelectField forms in my template like checkboxes below and I want the user to be able to check them and save the form. Feature_1 : [ ] Feature_2 : [ ] Feature_3 : [ ] {{ form.feature_1 }} doesn't display anything. The name of the form is AddCarForm models.py feature_1 = MultiSelectField(choices=feature_1_choice, max_length=100, default='', blank=True) feature_2 = MultiSelectField(choices=feature_2_choice, max_length=100, default='', blank=True) feature_3 = MultiSelectField(choices=feature_3_choice, max_length=100, default='', blank=True) feature_4 = MultiSelectField(choices=feature_4_choice, max_length=100, default='', blank=True) feature_5 = MultiSelectField(choices=feature_5_choice, max_length=100, default='', blank=True) feature_6 = MultiSelectField(choices=feature_6_choice, max_length=100, default='', blank=True) -
Unique constraint for many-to-many field
I have the following models from django.db import models class Man(models.Model): class = models.ManyToManyField(Class) class Classifier(models.Model): name = models.CharField() class Class(models.Model): classifier = models.ForeignKey(Classifier, on_delete=models.CASCADE) name = models.CharField() I.e. a man can have multiple classes, but only one per a classifier. How to implement this constraint in Django? There is UniqueConstraint, but it looks that it doesn't support nested fields, and I can't write: constraints = [ models.UniqueConstraint(fields=['class.classifier'], name='unique class per classifier') ] -
AttributeError: module 'django.db.models' has no attribute 'permalink'
@models.permalink AttributeError: module 'django.db.models' has no attribute 'permalink' please help me solve this it's a bit urgent -
Django - Update a value in database on another table
I have two tables class Payment(models.Model): payment_id = models.CharField(max_length=100) status = models.CharField(max_length=100) class Order(models.Model): payment = models.ForeignKey(Payment, on_delete=models.SET_NULL, blank=True, null=True) is_ordered = models.BooleanField(default=False) An incoming value (data) is coming from a webhook payment_confirmation(event.data.object.id) containing the payment_id. I want this value to be matched with Payment.payment_id (Payment table) and then update Order.is_ordered=True (Order table). How i can do that? I tried below with no success: Order.objects.filter(payment__payment_id=data).update(is_ordered=True) I can update Payment.status successfully by running: Payment.objects.filter(payment_id=data).update(status='COMPLETED') Thank you -
'list indices must be integers or slices, not dict' when using loop index
i always get this error. the statement which i commented out works. but i want to make a list of all elements of "categories", so i can choose later in the html which one to display. def home(request): response = requests.get('http://XXX.XX.XX.XXX:XXXX/api/categories/') categories = response.json() #return render(request, 'home.html', # { # 'id': categories[0]['id'], # 'name': categories[0]['name'], # 'colour': categories[0]['colour']} #) liste = [] for i in categories: liste.append({ 'id': categories[i]['id'], 'name': categories[i]['name'], 'colour': categories[i]['colour'] }) return render(request, 'home.html', liste) -
how to get an object after saving it to the database
i am trying to use django allauth to send confirmation emails on sign-up,after successfully sending the email i need top have a way to identify if the user has confirmed his email,dajngo allauth provides somthing for that from allauth.account.signals import email_confirmed @receiver(email_confirmed) def email_confirmed_(request, email_address, **kwargs): user = email_address.user user.email_verified = True user.save() what i can't figure out how to do is access the user.email_verified that i saved @api_view(['GET']) def current_user(request,user): current_user = request.user return Response({ 'id': current_user.id, 'verified': user.email_verified #??????? }) -
div inside another div is not taking 100% of its size. It is letting some equal space on the right and left
I want to make a responsive website and when I used columns and rows in bootstrap, I am having this problem where the inner div will not take the whole space in another div. The div inside div having class profile_left will leave a space on each side. Can you tell me what is wrong please? Here is my code snippet: div .profile_left{ border: 1px solid black; border-top-left-radius: 5px; border-top-right-radius: 5px; } div .profile_picture{ padding:20px; overflow: hidden; } <div class="container"> {% block content %} <div class="row"> <div class="profile_left col-lg-8 col-md-8 col-sm-8 col-xs-12" style="width: 30%;"> <div style="background-color: #01226c; text-align:center; padding:20px;"> <h3 style="color: white;"><strong>PROFILE</strong></h3> </div> <div style="background-color: white;"> <div class="profile_picture"> <figure> <img src="{{ student.profile_picture.url }}"> </figure> {% if student.profile_picture == 'default.png' %} <a href="">Add a picture</a> {% endif %} </div> </div> </div> </div> {% endblock content %} </div> -
Why am I getting this error when I run loaddata?
I am trying to run heroku python manage.py loaddata db.json but I keep getting this error UnicodeDecodeError: 'utf-8' codec can't decode byte 0x97 in position 2446: invalid start byte. What I did: python manage.py makemigrations locally git pushed to repo to update changes heroku python manage.py migrate heroku python manage.py loaddata db.json I keep getting this problem where I make changes to the database locally, the changes will not be reflected when I deploy on heroku. I added new rows locally, these rows do not get added to postgres when I deploy on heroku. No table or data on postgres when I deploy on heroku. I deployed the app through connecting to github. -
Inserting pandas dataframe into django model
I am having an issue writing a dataframe to my django models.py. The file is long, but is quite simple in its methodology: -import modules -create django database -requests.get necessary data -alter data some to fit my goals, save as df -connect to django db and insert df My models.py is the following: from django.db import models import requests import pandas as pd from datetime import timezone from datetime import datetime from datetime import date from datetime import timedelta import time from django.conf import settings from sqlalchemy.engine import create_engine class cryptoData(models.Model): coin = models.CharField(max_length=10) asset_id = models.SmallIntegerField() time = models.DateTimeField() close = models.FloatField() volume = models.BigIntegerField() market_cap = models.FloatField() reddit_posts = models.IntegerField() reddit_comments = models.IntegerField() tweets = models.IntegerField() tweet_favorites = models.IntegerField() social_volume = models.IntegerField() lunarcrush_key = 'fakekey1234' def top_coins(): lc_market = requests.get( url = 'https://api.lunarcrush.com/v2?data=market&', params = { 'key': lunarcrush_key, } ) all_coins = [] for entry in lc_market.json().get('data'): coin = [] coin.append(entry.get('s')) coin.append(entry.get('mc')) all_coins.append(coin) all_coins.sort(key = lambda x : x[1], reverse = True) top_ten_coins = all_coins[:10] return(top_ten_coins) top_coins_lst = top_coins() top_coin_names_lst = [x[0] for x in top_coins_lst] def get_coin_data(key, coin, date_diff, start_date, end_date): lc = requests.get( url = 'https://api.lunarcrush.com/v2?data=assets&', params = { 'key': lunarcrush_key, 'symbol': coin, 'interval': 'day', 'data_points': … -
How to pass a Count field to export field
I'm working on an export resource but I can't figure out how to pass this field from the view as a column in my export. issues = Student.objects.annotate(Count('issue')) def view_student(request): issues = Student.objects.annotate(Count('issue')) students = Student.objects.filter(school = request.user.school).order_by('year') return render(request, 'view_student.html', {'students': students,'issues':issues}) This is how I tried it in the resoucrces.py but it shows no result class ExportStudentsResource(resources.ModelResource): books = fields.Field(attribute = 'books',column_name='books',widget= ForeignKeyWidget(Student, 'issue_count')) class Meta: model = Student fields = ('student_id','name','year','klass','stream','books') This field is not from any model so I just thought Student model could be habouring it. How can I make it work -
Views.py ,Incrementing score by one for each correct option
I am making a quiz application, for result calculation I have written logic ..If the value of answer stored in question model is equal to the answer chosen by user then , when user submits each question , score is incrementing by one, but I've failed to build this logic as am a new user to django please help. Models.py : question along with its 4 options and the correct answer is in question model(These fields are entered by the user who creates a quiz by filling a form). Answer submitted by user is in answer model(This field is entered by user who takes quiz). score is stored in result model. from django.db import models from django.contrib.auth.models import User from django.conf import settings class quiztitle(models.Model): Quiz_id = models.AutoField(primary_key=True) Quiz_title = models.CharField(max_length=600) User = settings.AUTH_USER_MODEL User_id= models.ForeignKey(User, on_delete=models.CASCADE) class question(models.Model): Qid = models.AutoField(primary_key=True) User = settings.AUTH_USER_MODEL User_id = models.ForeignKey(User,on_delete=models.CASCADE) Quiz_id = models.ForeignKey(quiztitle,on_delete=models.CASCADE) Qques = models.TextField() Qoption1 = models.TextField() Qoption2 = models.TextField() Qoption3 = models.TextField() Qoption4 = models.TextField() QAnswer = models.TextField() class answer(models.Model): Ansid = models.AutoField(primary_key=True) Qid = models.ForeignKey(question,on_delete=models.CASCADE) Quiz_id = models.ForeignKey(quiztitle, on_delete=models.CASCADE) User = settings.AUTH_USER_MODEL User_id = models.ForeignKey(User, on_delete=models.CASCADE) Answer = models.TextField() class result(models.Model): result = models.AutoField(primary_key=True) Quiz_id = models.ForeignKey(quiztitle, on_delete=models.CASCADE) … -
How do I host paid videos on my django website
I have a django website currently hosted on pythonanywhere. It operate just like Udemy, how do I uppload my videos to a secure server? -
How to associate data sent by a user to his own account in Django
I have a model called KeyFormModel which has 2 fields "secret_key" and "primary_key", I pointed this model towards a form and called this form to a view and template. each user has exactly one primary_key and one secret_key, when I send this to model they are mixing with other keysets this is my model class KeyFormModel(models.Model): username = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) primary_key = models.CharField(max_length=200) secret_key = models.CharField(max_length=200) def __str__(self): return username+"_keys" class Meta: verbose_name_plural = 'Keys' this is my form from ..models import KeyFormModel from django import forms from django.conf import settings class KeyForm(forms.ModelForm): primary_key = forms.CharField(required=True) secret_key = forms.CharField(required=True,widget = forms.PasswordInput) class Meta: model = KeyFormModel fields = ("username","primary_key","secret_key") this is my view @cache_control(no_cache=True, must_revalidate=True) @login_required(login_url='../login') def AccountView(request): if(request.method == 'POST'): form =KeyForm(request.POST) if(form.is_valid()): form.save() else: for msg in form.error_messages: messages.error(request,f"{msg}") form = KeyForm return(render(request, 'accountView.html',context={"form":form})) as you can see I am trying to add username from AUTH_USER_MODEL after logging into that account but failing miserably. please hlp -
Is transaction atomic will cover all my queries in my function / is this a safe and correct way?
I'm working on a small project using Django and I would like to know if the way that I'm using, transaction atomic is correct and save for the queries? this is my code : def create(first_name, last_name, username): try: with transaction.atomic(): # Create Tenant / Set domain name for the tenant in question / Create User with schema_context('public'): tenant = Client( schema_name=str(username), name=first_name + '_' + last_name, paid_until='2014-12-05', on_trial=True) tenant.save() domain = Domain() domain.domain = str(userInQuestion.username) + settings.BASE_URL # tx.domain.com domain.tenant = tenant domain.is_primary = False domain.save() user = CustomUser() user.first_name = first_name user.last_name = last_name user.username = username user.password = set_password('admin') user.save() with schema_context(current_schema): addUserInTeam = Team.objects.create(user = CustomUser.objects.get(pk=userid)) except: transaction.set_rollback(True) -
How to get sum of the production_volume in a seasion of a particular fiscal_year using Django ORM
Here, I'm trying to get the sum of the production_volume different seasons in particular production_year: here is my models: class FiscalYear(BaseModel, models.Model): year = models.CharField(max_length=256) class Season(BaseModel, models.Model): name = models.CharField(max_length=256) season_month = models.ManyToManyField(Month) class Product(BaseModel, models.Model): name = models.CharField(max_length=256) category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.SET_NULL, related_name='product_category') description = models.CharField(max_length=1000) hs_code = models.CharField(max_length=256, unique=True) photo = models.ImageField(upload_to='media/product/%Y/%M/', null=True, blank=True) production_unit = models.ForeignKey(MeasurementUnit, related_name='product_unit', null=True, blank=True, on_delete=models.SET_NULL) class Production(BaseModel, models.Model): product = models.ForeignKey(Product, related_name='production_product', on_delete=models.CASCADE) district = models.ForeignKey(DistrictLevel, related_name='production_district', on_delete=models.CASCADE) production_volume = models.FloatField() production_year = models.ForeignKey(FiscalYear, related_name='production_year', null=True, blank=True, on_delete=models.SET_NULL) seasons = models.ManyToManyField(Season, related_name='product_season') I'm getting result by using for loop, aggregate but I think this is not appropriate. Which is below: fiscal_year = FiscalYear.objects.all().first() # for test for i in Season.objects.all(): production_year = Production.objects.filter(production_year = fiscal_year).filter(seasons=i).aggregate(total_production = Sum('production_volume')) print(production_year ,909090) How can i get result by ORM methods. I tried by using related_name with aggregate and annotate but it didn't work. Below what I want exactly: -
django-admin command not regonized
I have installed django on my computer but when i try to run any django-admin command on my terminal i get this error: django-admin : The term 'django-admin' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + django-admin startproject app + CategoryInfo : ObjectNotFound: (django-admin:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException I am using powershell and visual studio code Is there any way i can fix this? -
PyCharm Django Project: Changes in CSS stylesheet do not update
In a Django project on PyCharm changes to the main.css file do not work. Chache should not be a problem, as I deleted it and also tried it on a newly downloaded browser. Also the exact same code works on another computer. It seems like the problem is with my PyCharm somehow. Did anyone encounter the same problem? Thanks! -
In Django I cant retrieve the values for Upload cv, Status, gender in the edit.html form from the database but I can retrieve the other field values
enter image description hereThis is my edit.html code and during retrieving the values from database it shows only the text fields like value={{ i.full_name}} but when I am writing value={{ i.cv}}, value={{ i.status}}, value={{ i.gender}} it does not shows the value which needs to bed edited I have two choice fields and one file field and also when I am uploading a pdf file it is getting stored in media folder and I am showing that file in a table but if a file name which which I have uploaded name java.pdf after uploading it changes to some random name after original name like java_hjh45.pdf why this is happening I don't know this is my edit.html <section class="site-section"> <div class="container"> <div class="row"> <div class="col-lg-12 mb-5"> <h2 class="mb-4 text-center">Update Candidate Details</h2> <form method="POST" action="/update/ {{i.id}}/" enctype="multipart/form-data" class="p-4 border rounded" onsubmit="myFunction()" > {% csrf_token %} {% comment %} <input type="hidden" name="csrfmiddlewaretoken" value="UabxqpD8HGPOu1ZSFnIHAPbMtRgWBAnVHEs8bLDx0HnxN6uhG3LyYvZShvcx1ekn"> {% endcomment %} <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black" for="full_name">Full Name :</label> <input type="text" class="form-control" value ={{ i.full_name}} name="full_name" id="id_full_name" placeholder="Enter First Name"> </div> </div> <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black" for="recruiter_name">Recruiter Name :</label> <input type="text" class="form-control" value ={{ i.recruiter_name }} name="recruiter_name" id="id_recruiter_name" placeholder="Enter … -
Why django throws an integrityError?
I have a very weird exception I have no idea how to handle it. Until now, everything worked fine, but after I did some changes(not on database per se), out of 16 objects listed on my website, 2 throw to me this error when I want to delete one from Admin Pannel: FOREIGN KEY constraint failed models.py class Products(models.Model): name = models.CharField(max_length=50, blank=True, null=True) price = models.FloatField(blank=True, null=True) description = models.TextField(max_length=300, blank=True, null=True) resealed = models.BooleanField(blank=True, null=True) category = models.ForeignKey(to=SubCategories, on_delete=models.CASCADE, blank=True, null=True) image = models.ImageField(upload_to='gallery', blank=True, null=True) quantity = models.IntegerField(default=1) class SubCategories(models.Model): name = models.CharField(max_length=50, blank=True, null=True) description = models.TextField(max_length=500, blank=True, null=True) image = models.ImageField(upload_to='gallery', blank=True, null=True) par_category = models.ForeignKey(to=Categories, on_delete=models.CASCADE, blank=True, null=True, related_name="Category") class Categories(models.Model): name = models.CharField(max_length=50, blank=True, null=True) description = models.TextField(max_length=300, blank=True, null=True) I set on_delete=models.CASCADE. 3 days ago, I did some changes in the database in the sense that I renamed the old Category table to SubCategories and I created a new table Categories. With this move, I have created par_category constraint to the newly created table. After I did some refractors, two out of 16 elements throw me that error when I am trying to delete them. Can somebody help me with this issue? … -
How to add index_together when iexact is used
I am creating a index on 2 columns index_together = [["name", "value"]] but I also want it to be case insensitive, because one of my filters will use iexact. Any idea how this can be achieved? Using Django and Python. I am open to adding raw SQL to migration as well, if someone can also help with that -
django view does not catch an exception occurred by signal
I am a newbie of Django and have a question about exception handling. In my Django view file, I have a function like below. def timeTest(request): try: result = longTimeFunction() return HttpResponse(json.dumps(result)) except: raise Exception() I want to use the signal so that if the function longTimeFunction() takes more than 3 seconds, it will raise an exception as below. from functools import wraps import errno import os import signal class TimeoutError(Exception): pass def timeout(seconds=10, error_message=os.strerror(errno.ETIME)): def decorator(func): def _handle_timeout(signum, frame): raise TimeoutError(error_message) def wrapper(*args, **kwargs): signal.signal(signal.SIGALRM, _handle_timeout) signal.alarm(seconds) try: result = func(*args, **kwargs) finally: signal.alarm(0) return result return wraps(func)(wrapper) return decorator and the function longTimeFunction() looks like below. @timeout(3) def longTimeFunction(): do some computations here ... So, what I want is to raise an exception when the longTimeFunction takes more than 3 seconds. and the exception will be handled in the middleware. However, instead of catching the exception in the view so that it can be handled in the middleware, the signal raise exception and shows it directly to the browser. I do not know, but an exception occurred by the signal is not caught? -
Django Reset Loop in Template
How to reset loop (e.g. if a category change, reset the counter for sub category) in Django template? Game 1.1. Cricket 1.2. Football 1.3. Base Ball Pets 2.1. Dog 2.2. Cat 2.3. Fish NB: forloop.counter can't reset. -
Django Exclude Model Objects from query using a list
Having trouble with my query excluding results from a different query. I have a table - Segment that I have already gotten entries from. It is related to another table - Program, and I want to also run the same query on it but I want to exclude any of the programs that were already found during the segment query. When I try to do it, the list isn't allowed to be used in the comparison... See below: query = "My Query String" segment_results = Segment.objects.filter( Q(title__icontains=query)| Q(author__icontains=query)| Q(voice__icontains=query)| Q(library__icontains=query)| Q(summary__icontains=query) ).distinct() # There can be multiple segments in the same program unique_programs = [] for segs in segment_results: if segs.program.pk not in unique_programs: unique_programs.append(segs.program.pk) program_results = ( (Program.objects.filter( Q(title__icontains=query) | Q(library__icontains=query) | Q(mc__icontains=query) | Q(producer__icontains=query) | Q(editor__icontains=query) | Q(remarks__icontains=query) ).distinct()) & (Program.objects.exclude(id__in=[unique_programs]))) I can run: for x in unique_programs: p = Program.objects.filter(id=x) print("p = %s" % p) And I get a list of Programs...which works Just not sure how to incorporate this type of logic into the results query...and have it exclude at the same time. I tried exclude keyword, but the main problem is it doesn't like the list being in the query - I get an error: …