Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Add Object associated to another
I tried customizing a Django poll tutorial. I gave options so that users can add questions and options themselves. 'Choice' object from my models.py seems to be tricky. from django.db import models # Create your models here. class Question(models.Model): question = models.CharField(max_length=200) def __str__(self): return self.question class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='choices') option = models.CharField(max_length=100) vote = models.IntegerField(default=0) def __str__(self): return self.option Choice object is one-to-one relation with the Question. When I end values through the below HTML page, it doesn't create a new Choice. {% extends 'base.html' %} {% block content %} <h1>Add Member</h1> <form action = 'addoptrecord/' method='post'> {% csrf_token %} Choice: <br> <input name='ch'> <br> Vote: <br> <input name='vo'> <br> <label for="optquestions">Choose a Question:</label><br> <select name="optquestions" id="optquestions"> {% for question in questions %} <option value={{question.id}}>{{question}}</option> {%endfor%} </select><br><br> <input type='submit' value='Submit'> </form> {% endblock %} Not sure about the right syntax/method to associate the Choice data with Question while adding through views.py def addoptrecord(request,optquestions): ch = request.POST.get('ch') vo = request.POST.get('vo') que = Question.objects.get(id=optquestions) pollopt = Choice(que,option=ch,vote=vo) pollopt.save() return HttpResponseRedirect(reverse('index')) The above operation throughs me an Integrity Error. IntegrityError at /addopt/addoptrecord/ NOT NULL constraint failed: pollsapp_question.question -
Django - generic relation in django admin - is there any way to prefetch data, instead of making db query for every field in every row and column?
I have a following models (everything is simplified): class Car(models.Model): field_int = models.IntegerField(_('field_int'), null=True) field_datetime= models.DateTimeField(_('field_datetime')) field_boolean = models.BooleanField(_('field_boolean'), default=False) class Bus(models.Model): field_int = models.IntegerField(_('field_int'), null=False) field_datetime= models.DateTimeField(_('field_datetime')) field_boolean = models.BooleanField(_('field_boolean'), default=True) and I have something like vehicle report model with generic relation so I can "concatinate/merge" and show both models data simultaneously in django admin panel list_display class VehiclesReport(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') class Meta: indexes = [ models.Index(fields=["content_type", "object_id"]), ] def field_int_generic(self): return self.content_object.field_int def field_datetime_generic(self): return self.content_object.field_datetime def field_boolean_generic(self): return self.content_object.field_boolean I am creating objects in script like this (this is example for Car but same for Bus class): VehiclesReport.objects.create( content_type=ContentType.objects.get_for_model(Car), object_id=car.object_id, ) and with all this models and data I created Admin panel so I can display everything at the same time: class VehiclesReportAdmin(ModelAdmin): list_display = ( 'field_int_generic', 'field_datetime_generic', 'field_boolean_generic', ) ordering = ('content_type',) admin_site.register(VehiclesReport, VehiclesReportAdmin) Everything work like charm but django instead of prefetching all data, it makes request for every field_int_generic, field_datetime_generic, field_boolean_generic execution, even when it is still the same "row". Lets say I have 'VehiclesReportAdmin' but with 10 columns like field_int_generic and 20 page limit... I have 200 database queries for just 20 rows of … -
Advice on Django Roadmap
my first post here. I'm 43 and took learning web development this year. I've been doing a lot of studying and practicing HTML CSS and started on JS. I've taken a few python courses in the past and really love the language. should I learn js fundamentals and a framework before moving to Django because it is the basis of the internet? and I can't seem to find anything on if there's a possibility to do simple front-end stuff with django. Any advice would be greatly appreciated. Ty in advance. -
how to not let staff or admin users edit superusers
I'm working on permission distribution and according to my user model structure, staff and admin users are allowed to edit is_staff and is_admin for other users, not themselves. But with such power, they are able to edit those booleans for superusers too, which I don't them to have permission for! so, how do I let staff and admin users edit those booleans for others except superusers and themselves? or to not let staff and admin users get permission to tamper with any superuser attributes admin def get_form(self, request, obj=None, **kwargs): form = super().get_form(request, obj, **kwargs) is_superuser = request.user.is_superuser is_admin = request.user.is_admin disabled_fields = set() if ( not is_superuser and obj is not None and obj == request.user ): disabled_fields |= { 'staff', 'admin', 'user_permissions', } for f in disabled_fields: if f in form.base_fields: form.base_fields[f].disabled = True return form -
Django Rest Framework - Serialize nested objects
I have this JSON input which I'd like to express properly in the Django Model in order to be correctly serialized by Django Rest Framework. the MainObject has name property and a list of conditions; each Condition is composed exactly by 2 blocks: left and right; each Block is composed by 1 field title and a list of user_params. { "name": "The Main Object Name", "conditions": [ { "left": { "title": "Title1", "user_params": [ { "name": "name_param_X", "value": "100" } ] }, "right": { "title": "Title2", "user_params": [ { "name": "name_param_Y", "value": "200" } ] } } ] } And here my models: class MainObject(models.Model): main_object_id = models.UUIDField(primary_key=True, default=uuid.uuid4) name = models.CharField(max_length=64) class Condition(models.Model): condition_id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False, unique=True) main_object = models.ForeignKey(MainObject, related_name="conditions", on_delete=models.CASCADE) left = models.OneToOneField(Block, on_delete=models.CASCADE, null=True, related_name='left') right = models.OneToOneField(Block, on_delete=models.CASCADE, null=True, related_name='right') class Block(models.Model): title = models.CharField(max_length=16, primary_key=True) class BlockParam(models.Model): name = models.CharField(max_length=32) value = models.IntegerField() block_title = models.ForeignKey(Block, related_name="user_params", on_delete=models.CASCADE) My serializers: class ConditionSerializer(serializers.ModelSerializer): condition_id = serializers.UUIDField(required=False) class Meta: model = Condition fields = ('condition_id', 'left', 'right') class MainObjectSerializer(serializers.ModelSerializer): conditions = ConditionSerializer(many=True) def create(self, validated_data): conditions_data = validated_data.pop("conditions") main_object = MainObject.objects.create(**validated_data) for condition_data in conditions_data: Condition.objects.create(main_object=main_object, **condition_data) return main_object The issue: when I … -
Connect javascript file with django in static file
I attach a js file to my Django but have problem bcz JS don't works on website view, when CSS file style Django see. I try looks some toturial but still the same problem. Arrow etc don;t react on any click. Terminal: [06/Oct/2022 11:11:50] "GET /home/ HTTP/1.1" 200 3381 [06/Oct/2022 11:11:50] "GET /static/css/style.css HTTP/1.1" 200 773 [06/Oct/2022 11:11:50] "GET /static/image/arrow-left.png HTTP/1.1" 200 375 [06/Oct/2022 11:11:50] "GET /static/image/arrow-right.png HTTP/1.1" 200 306 [06/Oct/2022 11:11:50] "GET /static/image/about-us.png HTTP/1.1" 200 276423 [06/Oct/2022 11:11:50] "GET /static/image/calculate-power.png HTTP/1.1" 200 359596 [06/Oct/2022 11:11:50] "GET /static/image/turbine-models.png HTTP/1.1" 200 730280 [06/Oct/2022 11:11:50] "GET /static/js/home_page.js HTTP/1.1" 200 1167 Home-page template: {% extends 'turbineweb/turbineweb_extends.html' %} {% load static %} {% block section_one %} <main> <div id="slider"> <div id="top-row"> <img class="arrow left-class" id="arrow-left" src="{% static 'image/arrow-left.png' %}" /> <div id="slides-container"> <img class="slide active" src="{% static 'image/about-us.png' %}"> <img class="slide" src="{% static 'image/turbine-models.png' %}"> <img class="slide" src="{% static 'image/calculate-power.png' %}"> </div> <img class="arrow right-class" id="arrow-right" src="{% static 'image/arrow-right.png' %}" /> </div> <div id="bottom-row"> <div id="dots"> <div class="dot"></div> <div class="dot"></div> <div class="dot"></div> </div> </div> </div> <script src="{% static 'js/home_page.js' %}"></script> </main> {% endblock %} JS: let activeSlideNumber = 1; let arrowLeft = document.querySelector('.arrow-left') let arrowRight = document.querySelector('.arrow-right') let hideActiveSlide = () => { let … -
Is it possible to add a constraint on datetime field in Postgressql using Django?
When I try to add a constraint on closed_at field, I got a migration error django.db.utils.ProgrammingError: functions in index predicate must be marked IMMUTABLE. Is it any possible way to do it? from django.db.models.functions import Now class ModelName(): # Other fields closed_at = models.DateTimeField() class Meta: constraints = [ models.UniqueConstraint( fields=['field_1'], condition=Q(closed_at__gt=Now()), name='unique_field_1_constraint', ), ] Migration: class Migration(migrations.Migration): dependencies = [ ('_____', '__________'), ] operations = [ migrations.AddConstraint( model_name='model_name', constraint=models.UniqueConstraint(condition=models.Q( ('closed_at__gt', django.db.models.functions.datetime.Now()) ), fields=('field_1',), name='unique_field_1_constraint'), ), ] -
MultiValueDictKeyError at /profiles/ uploading file
I am using the django framework. And I just want to upload an image. So I have this: views.py: # Create your views here. def store_file(file): with open("temp/mensschappy.png", "wb+") as dest: for chunk in file.chunks(): dest.write(chunk) class CreateProfileView(View): def get(self, request): form = ProfileForm() return render(request, "profiles/create_profile.html", { "form": form }) def post(self, request): submitted_form = ProfileForm(request.POST, request.FILES) if submitted_form.is_valid(): store_file(request.FILES["image"]) return HttpResponseRedirect("/profiles") return render(request, "profiles/create_profile.html", { "form": submitted_form }) and the html: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Create a Profile</title> <link rel="stylesheet" href="{% static "profiles/styles.css" %}"> </head> <body> <form action="/profiles/" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form }} <button>Upload!</button> </form> </body> </html> but if I try to upload an image. I get this error: MultiValueDictKeyError at /profiles/ 'image' Request Method: POST Request URL: http://127.0.0.1:8000/profiles/ Django Version: 4.1.1 Exception Type: MultiValueDictKeyError Exception Value: 'image' Exception Location: C:\Python310\lib\site-packages\django\utils\datastructures.py, line 86, in __getitem__ Raised during: profiles.views.CreateProfileView Python Executable: C:\Python310\python.exe Python Version: 3.10.6 Python Path: ['C:\\Users\\engel\\Documents\\NVWA\\software\\blockchainfruit\\schoolfruitnvwa', 'C:\\Python310\\python310.zip', 'C:\\Python310\\DLLs', 'C:\\Python310\\lib', 'C:\\Python310', 'C:\\Python310\\lib\\site-packages'] Server time: Thu, 06 Oct 2022 08:38:50 +0000 So my question is: how to tackle this? Thank you -
Django: How to add object date (or any other field) within a TextField of the same object on Django Template?
info - TextField: The Wednesday six weeks before Easter Sunday – , is a Christian holy day of fasting Date: February 22, 2023 Both fields are being fetched from database and same object. I am trying to get the following on my django template: The Wednesday six weeks before Easter Sunday – February 22, 2023, is a Christian holy day of fasting Basically injecting date into info field of the same object., How should I implement this? I have already tried RichTextUploadingField with: info - RichTextUploadingField : The Wednesday six weeks before Easter Sunday – {{ obj.date }}, is a Christian holy day of fasting Template: {{ object.info|safe }} However this is not working for me. Thanks -
Query Paramter is not filtering tag with name that includes ++ or + sign
Currently i am having a weird issue where when i try to search query a tag for example tag = Python, then it show all of the articles related to python, { "id": 1, "headline": "Article 1", "abstract": "Abstract 1", "content": "Content 1", "published": "2022-10-05", "isDraft": true, "isFavourite": [ 2 ], "tags": [ "Python" ], but if i try to query search with k++ or c++ or any word that contains +, then it gives response of empty like this { "count": 0, "next": null, "previous": null, "results": [] } I dont understand why it does not show the result although i have a article that contains k++ in tags this is my tags models: class Tags(models.Model): id=models.AutoField(primary_key=True, auto_created=True, verbose_name="TAG_ID") tag=models.CharField(max_length=25) def get_id(self): return self.tag + ' belongs to ' + 'id ' + str(self.id) class Meta: verbose_name_plural="Tags" ordering= ("id", "tag") def __str__(self): return f'{self.tag}' this is my articles model where tags is coming as m2m field article model class Article(models.Model): id=models.AutoField(primary_key=True, auto_created=True, verbose_name="ARTICLE_ID") headline=models.CharField(max_length=250) abstract=models.TextField(max_length=1500, blank=True) content=models.TextField(max_length=2500, blank=True) files=models.ManyToManyField('DocumentModel', related_name='file_documents',related_query_name='select_files', blank=True) published=models.DateField(auto_now_add=True, null=True) tags=models.ManyToManyField('Tags', related_name='tags', blank=True) isDraft=models.BooleanField(blank=True, default=False) isFavourite=models.ManyToManyField(User, related_name="favourite", blank=True) created_by=models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name="articles") def get_id(self): return self.headline + ' belongs to ' + 'id ' + … -
Heroku: ModuleNotFoundError :No module named 'six'
I am deploying a Django app on Heroku. The application runs successfully on my local machine, which uses Python 3.6.3.rc1. But it failed to deploy (heroku activity). remote: ModuleNotFoundError: No module named 'six' Actually, It was always successful to build and deploy before August 17 2022. $ git push heroku master remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-18 stack remote: -----> Using buildpack: heroku/python remote: -----> Python app detected remote: -----> Using Python version specified in Pipfile.lock remote: -----> No change in requirements detected, installing from cache remote: -----> Using cached install of python-3.7.14 remote: -----> Installing pip 22.2.2, setuptools 63.4.3 and wheel 0.37.1 remote: Skipping installation, as Pipfile.lock has not changed since last deploy. remote: -----> Installing SQLite3 remote: -----> Skipping Django collectstatic since the env var DISABLE_COLLECTSTATIC is set. remote: -----> Discovering process types remote: Procfile declares types -> release, web remote: remote: -----> Compressing... remote: Done: 74.2M remote: -----> Launching... remote: ! Release command declared: this new release will not be available until the command succeeds. remote: Released v492 remote: https://license-web-test.herokuapp.com/ deployed to Heroku remote: Verifying deploy... done. remote: Running release command... remote: remote: Traceback (most recent call last): … -
Django Datatable.net with filters, CRUD and pagination
I am trying to build a fully functional datatable with a lot of entries so I need to use pagination. I tried to find tutorials or examples on the internet but I couldn't find any. I managed to develop a datatable with JSON but when I try to add some filters or CRUD modal forms nothing works. Please help, is there any tutorial/example of a Django datatable with server-side processing with all of its functionalities? Thank you! -
Djang+PostgreSQL: Use random of no order is given (in CI)
In CI I want PostgreSQL to order results, if no explicit "ORDER BY" is given. We use Django, but a pure PG-based solution, would be fine, too. Background: All tests where fine because PG always used the same order. But in production we had a nasty bug. I want to catch this in CI (not in production) -
How to show continuous serial number in pagination using django
I have a blog list layout. Now i am using {{forloop.counter}} in my template to generate serial numbers and it is working perfectly. Page 1 shows 1 - 20 serial number, then page 2 shows again 1 - 20 serial numbers. but i want to show serial number from 21 - 40 in page 2 and so on.. instead of 1 - 20 again and again in every page. How to do this using django -
fix long running filter task in django views
input_df = pd.read_excel(uploadedfile) variable_column = code search_type = 'icontains' filter = variable_column + '__' + search_type li = [] for i in input_df["KT_DB"]: qset=KT_DB.objects.filter(**{ filter: i}) df = pd.DataFrame.from_records(qset.values()) li.append(df) frame = pd.concat(li, axis=0, ignore_index=True) with BytesIO() as b: # Use the StringIO object as the filehandle. writer = pd.ExcelWriter(b, engine='xlsxwriter') frame.to_excel(writer, sheet_name = 'Sheet1', index = False) writer.save() filename = 'KW' content_type = 'application/vnd.ms-excel' response = HttpResponse(b.getvalue(), content_type=content_type) response['Content-Disposition'] = 'attachment; filename="' + filename + '.xlsx"' return response here, filter multiple keywords from the database table, it takes more time to execute. getting request time out before function executes. -
Django OneToOneField - Insert Record in another model
I am having the following models. The ItemSettings model has no records inserted initially. I have a html table with a link Rules to insert settings data for each item number in the ItemMaster. While adding ItemSettings details. The ItemSettings model will have its own view to edit the settings details, once inserted. I dont want the ItemNumber to displayed as a select dropdown. There can be only one record in the ItemSettings model. I am unable to achieve adding the record in the ItemSettings models with the below code. What am I doing wrong? Models.py: class ItemMaster(models.Model): project_name = models.ForeignKey(ProjectMaster, null=True, on_delete=models.SET_NULL) item_number = models.CharField(max_length=15, unique=True, error_messages={ 'unique': "This Item Number Already Exists!"}) item_type = models.ForeignKey(ItemType, null=True, on_delete=models.SET_NULL) item_description = models.CharField(max_length=255, blank=True, null=True) def __str__(self): return self.item_number class ItemSettings(models.Model): item_number = models.OneToOneField(ItemMaster, on_delete=models.CASCADE) low_at = models.FloatField(default=0) minimum_value = models.FloatField(default=0) maximum_value = models.FloatField(default=0) def __str__(self): return str(self.item_number) Views.py: def itemsettings_edit(request, pkey): item_master_data = ItemMaster.objects.get(id=pkey) item_no = item_master_data.item_number form = ItemSettingsForm() if request.method == "GET": return render(request, 'masters/edit.html', {'item_no': item_no}) elif request.method == 'POST': try: item_number = request.POST['item_no'] low_at = request.POST['low_at'] minimum_value = request.POST['minimum_value'] maximum_value = request.POST['maximum_value'] form = ItemSettingsForm(request.POST) ItemSettings(item_number=item_number, low_at=low_at, minimum_value=minimum_value, maximum_value=maximum_value).save() messages.SUCCESS(request, 'Data Saved') except Exception as e: … -
An error occurred (NoSuchBucket) when calling the PutObject operation
I'm trying to upload the images of my django project to s3 bucket. I have the following in my settings DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_S3_ACCESS_KEY_ID = 'my_key_id' AWS_S3_SECRET_ACCESS_KEY = 'my_secret_key' AWS_STORAGE_BUCKET_NAME = 'app_name' AWS_QUERYSTRING_AUTH = False i have this in my aws permisions { "Version": "2012-10-17", "Id": "Policy1665038511106", "Statement": [ { "Sid": "Stmt1665038504281", "Effect": "Allow", "Principal": "*", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::novacreditbank/*" } ] } I keep getting this error NoSuchBucket at /admin/Novaapp/data/1/change/ An error occurred (NoSuchBucket) when calling the PutObject operation: The specified bucket does not exist -
In django project how can i use Jwt's without using django rest framework. Also in need to use a decorator so that i can apply to my whole project [closed]
I am new to django and want to build a website where I can use jwt's without django rest framework... Please let me know if can use pure django and not drf to implement security -
reading .mxd file without need of arcMap software or any others ones
i have many .mxd file need to convert to shapefile (.shp) or JsonObject i want to find a way to do this process by code Not by useing those softwares manually. is there any way? i am using vanilla js for frontend and django-python backed -
Convert flat structure into a hierarchical JSON
I have a complicated database structure with a lot of one-to-many relations. For example. Models: poll qustions One-to-many relation between them. For the fromtend I want to prepare an accurate json. But I want to execute only one request to the database. Therefore from the database I'll extract a flat structure: Poll ID Poll name Candidate ID Candidate name 1 Election 1 Billy the Labourist 1 Election 2 John the Communist 1 Election 3 Peter the Baptist But for the frontend I need an accurate JSON reflecting: Poll: [1, Election [Candidates: [[1, Billy the Labourist], [2, John the Communist], [3, Peter the Baptist]]]] The only possible solution that crosses my mind is to run a loop and just prepare the json "manually". I don't think it is the best solution. Could you tell me what is the most elegant achieve the goal? Some libraries or ready made apps are higly welcome? -
How to implement dependent/chained dropdown in django admin?
I want to implement a dependent/chained dropdown to get showcased in the django admin page, but unfortunately i am not able to get any close to the solution. I have made 3 models namely, State, District and Block with foreign key dependency on each other and also added them to the main Model, which will be displayed in the django admin. I have tried using solutions posted online but none of them helped. Models.py view Django Admin view -
While creating react app getting NPM errors why
When i try to install the new react app, it shows NPM errors where I already installed npm package -
How to create combobox with django model?
i want to create something like a combo box with django model, but i don't find any field type to do that. something like this: enter image description here -
How to extract data in sentiment analysis due to which the sentiment is calculated? (Words which are responsible for sentiment)
For example: I love icecreame -----> here due to love word the data becomes positive sentiment. In the same way how to find the exact words which are responsible for the resulting sentiment. I have written some basic code in python (django framework) related to sentiment analysis in the below way data="Love the new update. It's super fast!" sid_obj=SentimentIntensityAnalyzer() sentiment_dict=sid_obj.polarity_scores(data) negative=sentiment_dict['neg'] neutral=sentiment_dict['neu'] positive=sentiment_dict['pos'] compound=sentiment_dict['compound'] if sentiment_dict['compound']>=0.05: overall_sentiment='Positive' elif sentiment_dict['compound'] <= -0.05: overall_sentiment='Negative' else: overall_sentiment='Neutral' Note: I have imported the packages which are required for the execution of above code and it works. Can anyone pleas help me in adding the important code which extracts the words responsible for the resulting sentiment. -
How to Send Mail Asynchronously Using Django's Async View
I am building a project, and I want to send a notifying e-mail when User takes a specific action. I did some search and managed to achieve this using threading.Thread. Since Django now fully supports async view, I want to do it with async function. Here is what I tried: from asgiref.sync import sync_to_async from django.core.mail import send_mail from django.shortcuts import render from myproj.settings import EMAIL_HOST_USER import asyncio asend_mail = sync_to_async(send_mail) async def index(request): asyncio.create_task( asend_mail( subject='Test', message='Lorem ipsum', from_email=EMAIL_HOST_USER, recipient_list=['ezon@stackoverflow.dummy'] ) ) return render(request, 'myapp/index.html', {}) However, when I request this index page, I still get response AFTER asend_mail coroutine complete. I have tried the following simple async function (from a tutorial), and everything works as expected. async def async_print(): for num in range(1, 6): await asyncio.sleep(1) print(num) async def index(request): asyncio.create_task(async_print()) return render(request, 'myapp/index.html', {}) I wander what is the key difference between the above two scenarios. I am using python 3.10.7, django 4.1.2, daphne 3.0.2 (as the server, NOT django's development server). I am new to async/await feature. I will be appreciate it if someone can give a comprehensive explanation Thanks in advance.