Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Error: __init__() takes 1 positional argument but 2 were given
I am new to Django and I'm trying to create my first project following a tutorial from Udemy, but I encounter this error. My project has the following folder structure: -demo __ init__.py admin.py apps.py models.py tests.py urls.py -views.py -first __ init__.py asgi.py settings.py urls.py wsgi.py views.py: from django.shortcuts import render from django.http import HttpRequest def first(request): return HttpRequest('1st message from views') demo/urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.first), ] first/urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('demo/', include('demo.urls')), path('admin/', admin.site.urls), ] Both __ init__.py files are empty error: TypeError at /demo/ __init__() takes 1 positional argument but 2 were given Request Method: GET Request URL: http://127.0.0.1:8000/demo/ Django Version: 3.2.16 Exception Type: TypeError Exception Value: __init__() takes 1 positional argument but 2 were given Exception Location: D:\Python\DJANGO\first-project\demo\views.py, line 6, in first Python Executable: D:\Python\DJANGO\first-project\venv\Scripts\python.exe Python Version: 3.7.6 Python Path: ['D:\\Python\\DJANGO\\first-project', 'D:\\Python\\DJANGO\\first-project', 'C:\\Users\\biavu\\AppData\\Local\\Programs\\Python\\Python37\\python37.zip', 'C:\\Users\\biavu\\AppData\\Local\\Programs\\Python\\Python37\\DLLs', 'C:\\Users\\biavu\\AppData\\Local\\Programs\\Python\\Python37\\lib', 'C:\\Users\\biavu\\AppData\\Local\\Programs\\Python\\Python37', 'D:\\Python\\DJANGO\\first-project\\venv', 'D:\\Python\\DJANGO\\first-project\\venv\\lib\\site-packages'] Server time: Thu, 06 Oct 2022 12:34:45 +0000 -
Im getting error 'str' object has no attribute 'status_code' [closed]
I've seen every thread i could find for that problem and there a acutally quite a lot but i cant figure out the problem. Im trying some unit testing on one of my django views. It used to pass the test but now it breaks and prints: AttributeError: 'str' object has no attribute 'status_code' unit test: def test_delete_flight(self): self.client.force_login(self.user) response = self.client.get('/agriculture/delete_flight/' + str(self.flight)) self.assertEqual(response.status_code, 302) self.assertRedirects(response.url, '/agriculture/flights') The error occurs on assertEqual for some reason. I tried printing out response.status_code, 302 and everything seems normal, its basically (302, 302) so i cant figure out where it is breaking. error ERROR: test_delete_field Traceback (most recent call last): File "/home/dukis/Documents/agrominds/src/agriculture/tests/test_views.py", line 329, in test_delete_flight self.assertRedirects(response.url, '/agriculture/flights') File "/home/dukis/Documents/venv-agrominds/lib/python3.10/site-packages/django/test/testcases.py", line 358, in assertRedirects response.status_code, status_code, AttributeError: 'str' object has no attribute 'status_code' -
Heroku : (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)"
I am trying to deploy my django app on heroku. While deploying I am getting this error. I am not sure if there is something wrong with my settings file or heroku setup. Python 3.10, Django 4.1.2 Here is the database settings I am using import dj_database_url DATABASES = { 'default': dj_database_url.config(conn_max_age=500) } This is the database url from heroku config DATABASE_URL: postgres://ewdtekjzxnzuuo:b16a983b5c9cfb7fe1f9aaab58f1ac21bea073fdb059c0fa7356600c4a19030b@ec2-34-200-205-45.compute-1.amazonaws.com:5432/da0ttf53ppludi Error message -> MySQLdb.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/app/manage.py", line 22, in <module> main() File "/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 448, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 96, in wrapped res = handle_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/commands/migrate.py", line 97, in handle self.check(databases=[database]) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 475, in check all_issues = checks.run_checks( File "/app/.heroku/python/lib/python3.10/site-packages/django/core/checks/registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/checks/model_checks.py", line 36, in check_all_models errors.extend(model.check(**kwargs)) File "/app/.heroku/python/lib/python3.10/site-packages/django/db/models/base.py", line 1533, in check *cls._check_indexes(databases), File "/app/.heroku/python/lib/python3.10/site-packages/django/db/models/base.py", line 1952, in _check_indexes connection.features.supports_expression_indexes File "/app/.heroku/python/lib/python3.10/site-packages/django/utils/functional.py", line … -
How to delete virtual environment completely on Docker?
I am trying to make a Django and Postgre container using docker-compose. I followed this tutorial: https://docs.docker.com/samples/django/. I am using Windows and executed the following command: docker-compose run web django-admin startproject composeexample . After that, I modified my Dockerfile to include some apt-get update # syntax=docker/dockerfile:1 FROM python:3 RUN apt-get update RUN apt-get install -y libgdal-dev ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 WORKDIR /usr/src/app COPY requirements.txt /usr/src/app/ RUN pip install -r requirements.txt COPY . /usr/src/app/ I deleted the created composeexample folder and data folder, and run the command again. docker-compose run web django-admin startproject composeexample . This time. I get the following error: CommandError: /usr/src/app/manage.py already exists. Overlaying a project into an existing directory won't replace conflicting files. ERROR: 1 Somehow Docker thinks the files still exist from the 1st execution. Even if I change the name of the parent directory to change the container name, I still get the error. How can I remove the environment completely from my 1st execution? -
Django RetrieveAPIView where is the rights place to do some small db update
I'm using Django REST framework, and still quite new to it.. I Want to retrieve a message from db with generics.RetrieveAPIView method, which I did.. But I want to also set the read field to true at the database. Where is the place to do it (maybe in the serializer)? This is the idea: class MessageDetail(generics.RetrieveAPIView): serializer_class = MessageSerializer permission_classes = [IsAuthenticated] queryset = AppUserMessage.objects.all() AfterTheRequst(self) # This is what I want to do obj.read_at = time.now() -
Django, no module named 'polls' - Django reusable apps
I am at the end of the getting started of the Django project, I built the package as described in the Advanced tutorial: How to write reusable apps. I got a tar.gz file that I installed not in a virtual environment using the command python.exe -m pip install --user C:\Users\[PRIVACY AMEND]\Documents\python\mysite\django-polls\dist\django-polls-0.1.tar.gz. The module is installed as shown in the output of python.exe -m pip list below. Package Version ------------ ------- asgiref 3.5.2 Django 4.1.1 django-polls 0.1 lxml 4.9.1 sqlparse 0.4.2 tzdata 2022.2 But when I migrate, I get the error no module named polls... I have done all steps of the tutorial on Windows and Debian (on WSL), using explicitly python.exe -m pip when interacting with pip, checked the logs for any other error, and checked the PYTHONPATH and where the package is installed given by python.exe -m pip show django-polls, the output is just below. Name: django-polls Version: 0.1 Summary: A Django app to conduct web-based polls. Home-page: https://www.example.com/ Author: Your Name Author-email: yourname@example.com License: BSD-3-Clause # Example license Location: c:\users\[PRIVACY AMEND]\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages Requires: Django Required-by: Does anyone have a hint ? -
encrypt and decrypt Django rest framework field as superuser?
I read the answers here: plaintext API secret and have read about encryption and decryption of API keys and secrets. In django Rest Framework, 1- store the API key and Secret in plain text in Django REST framework DB. 2- An endpoint, only accessible by superuser(I could limit this further to IP address), gives all users API keys and secrets to be used in another script. TLS communication. I am not sure if this is the best approach. -
CKEditor 5 open image in full screen
I am using CKEditor 5 in a Django project, where I display the created content on a front end page. My content wrapper is quite narrow, and therefore any images that I add via the CKEditor are small. I need a way to make them clickable and either open the image URL in a new tab or have a full screen Bootstrap Modal that shows the 100% width image. Would this be achievable without altering the CKeditor JS files? Can I create a JS script that replaces CKEditor image tags with my own HTML code on every page load in the front end? Or can it be done so that the needed HTML code is directly saved to the database? (then can the CKEditor understand that new code when I edit the content?). I hope you can help with some tips. No code needed. Thank you! -
Django how to create a dynamic field
I don’t understand the principle of a dynamic field. In my case I have 3 classes on my models: 1- Product : name, ref, description and availability (availability should not be coded in the database and be define dynamicly. It should return available or out of stock). 2- Location : name of the location. 3- Stock : foreign key for Product and foreign key for Location and number a product(INT). The idea is : if in Stock there is 1 or more of a product, the products endpoint shows available. If 0 it shows out of stock. Is that even possible ? How ? Thank you for all the help. -
Getting error when using custom manytomany field when save in django admin
i have a problem in django admin. When i submit my forms in django admin i'm getting Cannot assign "<QuerySet [<ProductAttributeValue: color : red>, <ProductAttributeValue: size : L>]>": "StockJoinProductAttributeValue.prod_att_value" must be a "ProductAttributeValue" instance. I know the problem. Here i have to pass object not queryset. But i don't know how to do it. models.py class Stock(models.Model): #Implement dynamic select options sku = models.ForeignKey(SubProduct, on_delete=models.PROTECT, related_name="sub_product", default=1) product_attribute_value_id = models.ManyToManyField(ProductAttributeValue, blank=True, related_name="product_attribute_value", through="StockJoinProductAttributeValue" ) is_default = models.BooleanField(default=False, verbose_name=_("Default selection"), help_text=_("format: true=stock visible") ) units = models.IntegerField( default=1, unique=False, null=False, blank=False, verbose_name=_("units/ qty of stock"), help_text=_("format: required, default=0") ) units_sold = models.IntegerField( default=0, unique=False, null=False, blank=False, verbose_name=_("units/ qty of sold products"), help_text=_("format: required, default=0") ) def __str__(self): return '{}'.format(self.sku) class ProductAttributeValue(models.Model): product_attribute = models.ForeignKey( ProductAttribute, on_delete=models.PROTECT, related_name="product_attribute") attribute_value = models.CharField( max_length=255, unique=True, null=False, blank=False, verbose_name=_("attribute value"), help_text=_("format: required, max-255") ) class Meta: ordering = ['product_attribute'] def save(self, *args, **kwargs): self.attribute_value = self.attribute_value.lower() return super().save(*args, **kwargs) def __str__(self): return '{} : {}'.format(self.product_attribute.name, self.attribute_value) class StockJoinProductAttributeValue(models.Model): stock_id = models.ForeignKey(Stock, models.PROTECT) prod_att_value = models.ForeignKey(ProductAttributeValue, on_delete=models.PROTECT) class Meta: unique_together = ['prod_att_value', 'stock_id'] admin.py class StockJoinProductAttributeValueForm(forms.ModelForm): class Meta: model = StockJoinProductAttributeValue fields = ['stock_id','prod_att_value'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['prod_att_value'] = forms.ModelMultipleChoiceField( queryset=ProductAttributeValue.objects.all(), ) class … -
how to convert tree query set into dictionary?
book_category_list=[] for book_category in BookCategory.objects.filter(parent__isnull = True): book_category_list.append(book_category.get_family())** now the book_category_list in tree query set format. I need to list categories in a tree structure.so I need to convert this book_category_list into dictionary format. BookCategory is a MPTT Model? -
Django ORM: possible to annotate a QuerySet with a field across a normal AND a reverse foreign key relation?
Assume the following model classes: class Person(models.Model): # ...irrelevant fields... class PersonEmailLogin(AbstractBaseUser): email = models.EmailField() person = models.ForeignKey(Person) # ...more irrelevant fields... class SomeModel(models.Model): person = models.ForeignKey(Person) # ...more irrelevant fields... Note: these are all unmanaged models—we're developing against an existing database that is not managed by us. While not expressed in the code above, it's guaranteed outside Django that for each Person, 0–1 PersonEmailLogins will point to it. I want to retrieve SomeModel objects, but annotate each row with the email field from PersonEmailLogin. This has to be done with an outer join, since not all Persons have PersonEmailLogins. SomeModel doesn't have a direct foreign key to PersonEmailLogin, but as they both point to Person, it is possible to associate a SomeModel instance to a single PersonEmailLogin instance, or NULL where a given Person doesn't have any PersonEmailLogins pointing to it. When using SomeModel.objects.raw(), the currently functioning query looks like this: SELECT sm.*, pel.email FROM somemodel sm LEFT OUTER JOIN personemaillogin pel ON sm.person_id = pel.person_id; I would prefer to use normal QuerySets instead of RawQuerySets, since it would be more convenient to do more filtering operations down the line, but I haven't found a way to express this … -
Django - Get latest related object for each object in queryset using one database query
I have a Django app where I collect data from sensors which are divided into areas. class Area(models.Model): name = models.CharField(max_length=50) code = models.IntegerField(unique=True, primary_key=True) class Sensor(models.Model): name = models.CharField(max_length=30) area = models.ForeignKey(Area, on_delete=models.CASCADE) class Observation(models.Model): date_time = models.DateTimeField() sensor = models.ForeignKey(Sensor, on_delete=models.CASCADE) value = models.DecimalField(max_digits=4, decimal_places=1) What I need for each area is a list of the latest observations in that area, that is, one per sensor. So far, I solved it like this: class Sensor(models.Model) ... def latest_observation(self): return self.observation_set.latest('date_time') Now, I can loop through my sensors to get the latest observation for each sensor. class Area(models.Model): ... def latest_observations_per_sensor(self): return [s.latest_observation() for s in self.sensor_set.all()] This returns a list of what I want, but it is not very efficient since it makes a database query for each individual sensor. Ideally, I would do this in one database query for all areas, but I don't know if this is possible in Django. -
how to sort django templates folder
i made my first blog templates in order blog/templates/sth.html becuz it didnt find in this order blog/templates/blog/sth.html but now i made a new app and made it in order users/templates/registiration/login.html and got this error Using engine django: django.template.loaders.app_directories.Loader: C:\Users\NDarksoul\.virtualenvs\blog-PCvr0qFP\lib\site-packages\django\contrib\admin\templates\blog\base.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\NDarksoul\.virtualenvs\blog-PCvr0qFP\lib\site-packages\django\contrib\auth\templates\blog\base.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\projects\rightnow\blog\blog\templates\blog\base.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\projects\rightnow\blog\users\templates\blog\base.html (Source does not exist) can u hlp me pls how to fix this mess -
djangosaml2 metadata and django settings
I am trying to change my login into SAML2 for a Django project. I just have a metadata URL where can I see the settings and the certificate for that. In that metadata, there is just one certificate content and ds:SignatureValue which is generating uniquely on every request. Do I also need a certificate key? And is there any way to get those settings directly from METADATA? https://login.entry.com/login/saml/idp/metadata <?xml version="1.0" encoding="UTF-8"?> <md:EntityDescriptor xmlns:md="urn:oasis:names:tc:SAML:2.0:metadata" ID="_895c6e0e-1111-1111-1111-4eb316fa43cc" entityID="entity.com" validUntil="2026-12-29T09:54:08.000Z"> <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#"> <ds:SignedInfo> <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/> <ds:SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"/> <ds:Reference URI="#_895c6e0e-2920-4a24-839f-4eb316fa43cc"> <ds:Transforms> <ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/> <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/> </ds:Transforms> <ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/> <ds:DigestValue>RfLCex+sdsafdsfddsFDS+U=</ds:DigestValue> </ds:Reference> </ds:SignedInfo> <ds:SignatureValue>FSdfsdFDSfds...==</ds:SignatureValue> </ds:Signature> <md:IDPSSODescriptor WantAuthnRequestsSigned="true" protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol"> <md:KeyDescriptor use="signing"> <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#"> <ds:X509Data> <ds:X509Certificate>MIIDezCCAmOgAwIBAgIEdKfywTANBgkqhkiG9w0Bx...==</ds:X509Certificate> </ds:X509Data> </ds:KeyInfo> </md:KeyDescriptor> <md:NameIDFormat>urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress</md:NameIDFormat> <md:SingleSignOnService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect" Location="https://login.entity.com/login/saml/idp"/> <md:SingleSignOnService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" Location="https://login.entity.com/login/saml/idp"/> </md:IDPSSODescriptor> </md:EntityDescriptor> -
How to fetch the data in react after redirecting django backend to react page with redirect function having data in it
I am working on an application with two parts as frontend and backend in react and django , I am using server side flow and using token authentication for login and authentication system with OAuth . When user clicks on the frontend on LOGIN WITH GOOGLE it is allowed to choose the email and login with the react server with port 3000 and the redirect url or callback url is my django backend with port 8080 and after i get the access token, get data from access token , and then I try to redirect to the frontend , that is also working , but how do i get the data in the frontend which i have passed from backend from redirect function , the data is passed but how do i access it in the front end . my views.py "http://localhost:8080/api/callback/" @api_view(["GET"]) def getCallBack(request , *args , **kwargs): if request.method == "GET" : data = { "scope" : request.GET.get("scope").strip().lstrip().rstrip() , "authuser" : request.GET.get("authuser").strip().lstrip().rstrip() , "prompt": request.GET.get("prompt").strip().lstrip().rstrip() , "code" : request.GET.get("code").strip().lstrip().rstrip() , "client_id" :"", "client_secret" : "", "redirect_uri" :"http://localhost:8080/api/callback/", "grant_type" :"authorization_code" } response = requests.post("https://accounts.google.com/o/oauth2/token" , data = data) token = response.json()["access_token"] payload = { "access_token" : token , } … -
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