Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Collectstatic Code Line Changed my CSS code in Django
So I build a RESPONSIVE website on Django, and deployed it on Heroku. Here is a link https://three-d-production.herokuapp.com/ On a the full HD resolution design looks good, but when entered website on my phone, some parts of website were moved. I think that the problem in the settings.py: STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') But I have no idea how to fix it. Here is a GITHUB code: https://github.com/PHILLyaHI/ThreeDProduction PLEASE HELP ME CHROME DEV TOOLS POV IPHONE 12 POV -
Can I create an instance of AbstractUser in my model class in the model.py in django?
I am new to django and from a tutorial video, in the model.py file for the profile app, he created an instance of the User model in a one-to-one relationship with the profile model class like so: ` from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, blank=True, null=True) I understand that he created a one-to-one relationship with the profile model and the User model by creating an instance of the User model in the class. I am trying to achieve this with AbstractUser as well. I tried to do the same thing like so: from django.contrib.auth.models import AbstractUser class Blogger(models.Model): user = models.OneToOneField(AbstractUser, blank=True, null=True) In the settings.py, I have connected the PostGresSql database like so: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'bookandreviews', 'USER': 'postgres', 'HOST': 'localhost', 'PASSWORD': '2030', 'PORT': '5432' } } I ran py manage.py runserver and I got this error: django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: users.Bloggers.user: (fields.E300) Field defines a relation with model 'AbstractUser', which is either not installed, or is abstract. users.Bloggers.user: (fields.E307) The field users.Bloggers.user was declared with a lazy reference to 'auth.abstractuser', but app 'auth' doesn't provide model 'abstractuser'. I don't understand it. So I tried to add … -
if form.is_valid() return errors when using get_or_create
class Books(models.Model): book_file = models.FileField( upload_to="books", validators=[validate_book_extension], verbose_name="book", ) title = models.CharField(max_length=255, default=None) author = models.ForeignKey(Author, on_delete=models.CASCADE, default="") coauthors = models.ManyToManyField(CoAuthor, blank=True) publisher = models.ForeignKey( Publisher, on_delete=models.SET_DEFAULT, default=None, related_name="books_published", ) genres = models.ManyToManyField(Genre) edition = models.IntegerField(default=None) description = models.TextField(blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) i am having trouble with form validation when uploading a book to a database. The model has fields for authors and coauthors with ForeignKey and ManyToManyField relationships, and you're using the get_or_create method in the view function that handles the submission of fields with ForeignKey and ManyToManyField relationship. However, the if form.is_valid() statement returns errors and if i don't check if the form is valid the form submits. Below is the error that pops up. views.py @login_required def addbook(request): if not request.user.is_superuser: return redirect(notfound) else: books = Books.objects.all() genres = Genre.objects.all() authors = Author.objects.all() coauthors = CoAuthor.objects.all() publishers = Publisher.objects.all() form = BookForm() if request.method == "POST": form = BookForm(request.POST, request.FILES) if form.is_valid(): book = request.FILES.get("book_file") title = request.POST.get("title") genres_name = request.POST.getlist("genres") author_name = request.POST.get("author") co_authors = request.POST.getlist("coauthors") publisher_name = request.POST.get("publisher") author, created = Author.objects.get_or_create( name=author_name.title()) publisher, created = Publisher.objects.get_or_create( name=publisher_name.title() ) book = Books.objects.create( title=title.title(), publisher=publisher, edition=request.POST.get("edition"), author=author, book_file=book, ) for genre in genres_name: … -
Pythonanywhere Template is not rendering on the django
I'm trying to deploy my webapp on pythonanywhere, but my template is not rendering at all, however the same code is showing just fine on my local visual studio. i'm receiving the below error. my views is as follows: from django.shortcuts import render # Create your views here. def Home(request): return render(request, 'Home.html') my settings is TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'Templates'),], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] Please help, what am i missing? -
Forbidden (CSRF cookie not set.) - Django 4.1 and React
General Information: I'm facing the following error Forbidden (CSRF cookie not set.) while posting in my React app. I've been through many of the similar posts, but they doesn't seem to solve my issue. I believe my issue is on my React app, and not on my Django side, since I do get a 200 response on a GET request, but when posting, my React app doesn't get a grip on my CSRF token. Noted, but unexplainable: I do not see my CSRF set when I check in Applications in my chrome inspector on http://localhost:3000/ Terminal Response: Django System check identified 1 issue (0 silenced). April 01, 2023 - 22:02:51 Django version 4.1.7, using settings 'core.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [01/Apr/2023 22:05:05] "GET /accounts/csrf-cookie HTTP/1.1" 200 29 Forbidden (CSRF cookie not set.): /accounts/register/ [01/Apr/2023 22:05:14] "POST /accounts/register/ HTTP/1.1" 403 2870 React Note that the development build is not optimized. To create a production build, use npm run build. assets by status 1.33 MiB [cached] 17 assets assets by status 16.9 MiB [emitted] assets by chunk 16.9 MiB (name: main) asset static/js/bundle.js 16.9 MiB [emitted] (name: main) 1 related asset asset main.41b1aa5256b383579099.hot-update.js 4.01 KiB [emitted] … -
I want to deploy django to gae and display images
I have an app created with django and deployed with google app engine. Images stored in the static folder are not displayed in the template. But the css file works fine. I don't understand why the image is not loaded even though the css file is loaded. Is there any solution? ▼version Django 4.1.1 ▼Error GET https://<myapp>.an.r.appspot.com/static/img/example.png/ 404 ▼app.yaml runtime: python39 instance_class: F1 env: standard service: default entrypoint: gunicorn -b :$PORT config.wsgi:application includes: - secrets/secret.yaml handlers: - url: /static static_dir: staticfiles/ - url: .* secure: always script: auto ▼part of settings.py from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent if os.getenv('GAE_APPLICATION', None): # production DEBUG = False ALLOWED_HOSTS = ['myapp.an.r.appspot.com'] else: # develop DEBUG = True ALLOWED_HOSTS = ['*'] import yaml with open(os.path.join(BASE_DIR,'secrets','secret_dev.yaml'), encoding="utf-8") as file: objs = yaml.safe_load(file) for obj in objs: os.environ[obj] = objs[obj] INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', "myapp", 'django_cleanup.apps.CleanupConfig', 'django_feather', 'widget_tweaks', ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", 'myapp.middleware.middleware.AdminProtect', ] ROOT_URLCONF = "config.urls" TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [os.path.join(BASE_DIR, 'templates'),], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", 'myapp.context_processor.notice_content', ], }, }, ] WSGI_APPLICATION = "config.wsgi.application" # Database … -
Search a part of a word using django-elasticsearch-dsl-drf
I am building a Django application that contains search engine using elastic search by django_elasticsearch_dsl_drf library. I want to allow user to search for only letters or a part of a word and elastic search returns all words that contain these letters. For example if the user submitted 'legal' word the result will be all articles containing 'legal, legally, illegal, illegally'. I have used nGram tokenizer to make this but it doesn't work as when I submit the word no results are shown to me. here is the most important part which is in documents.py: from django_elasticsearch_dsl import Document, fields, Index from django_elasticsearch_dsl.registries import registry from django.conf import settings from .models import * from elasticsearch_dsl import analyzer, tokenizer autocomplete_analyzer = analyzer('autocomplete_analyzer', tokenizer=tokenizer('trigram', 'nGram', min_gram=1, max_gram=20), filter=['lowercase'] ) entry_index=Index('entries') @registry.register_document class EntryDocument(Document): title = fields.TextField( attr='title', fields={ 'raw': fields.TextField(required=True,analyzer=autocomplete_analyzer), 'suggest': fields.CompletionField(), } ) body = fields.TextField( attr='body', fields={ 'raw': fields.TextField(required=True,analyzer=autocomplete_analyzer), # 'suggest': fields.CompletionField() } ) class Index: name = 'entries' settings = { "number_of_shards": 1, "number_of_replicas": 0, 'max_ngram_diff': 20 } class Django: model = entry fields= [] for more details: models.py: class entry(models.Model): title = models.CharField(max_length=600) body = models.TextField() Serializers.py: class EntryDocumentSerializer(DocumentSerializer): class Meta: document = EntryDocument fields = ( 'title', … -
This django app asks a mutiple-choice question from the user
The app checks the user answer and shows the result and then checks if the user answered the question or not. if the user answered the question the options will disable and **checks **the option that user selected but i got that error: TemplateSyntaxError at /questions/ Could not parse the remainder: '[question.id]' from 'answers[question.id]' html: ` {% for question in questions %} <div class="question"> <p>{{ question.text }}</p> <form method="post" action="{% url 'submit_answer' question.id %}"> {% csrf_token %} <input type="hidden" name="question" value="{{ question.id }}"> <input type="radio" id="option_1_{{ question.id }}" name="answer" value="1" {% if 1 in answers[{{question.id}}] %}checked{% endif %} {% if answers[question.id] is not None %}disabled{% endif %}> <label for="option_1_{{ question.id }}">{{ question.option_1 }}</label> <br> <input type="radio" id="option_1_{{ question.id }}" name="answer" value="2" {% if 2 in answers[question.id] %}checked{% endif %} {% if answers[question.id] is not None %}disabled{% endif %}> <label for="option_2_{{ question.id }}">{{ question.option_2 }}</label> <br> <input type="radio" id="option_1_{{ question.id }}" name="answer" value="3" {% if 3 in answers[question.id] %}checked{% endif %} {% if answers[question.id] is not None %}disabled{% endif %}> <label for="option_3_{{ question.id }}">{{ question.option_3 }}</label> <br> {% if not request.session.question_answers.get(str(question.id)) %} <button type="submit">Submit Answer</button> {% else %} <p>Your answer has been submitted.</p> {% endif %} </form> </div> {% endfor %} … -
django filter by related
my models: class Person(models.Model): name = models.CharField(max_length=255) class BankAccount(models.Model): iban = models.CharField(max_length=28) owners = models.ManyToManyField(Person, through='BankAccountPerson') class BankAccountPerson(models.Model): bank_account = models.ForeignKey(BankAccount, on_delete=models.RESTRICT, related_name = 'ownership') person = models.ForeignKey(Person, on_delete=models.RESTRICT, related_name = 'ownership') is_owner = models.BooleanField(null=True, blank=True) class Meta: unique_together= [['bank_account','person']] let's assume, that account no 1 has two owners: person:1 and person:2 And now if I filter like this: person=Person.objects.get(pk=1) collection = BankAccount.objects.filter(owners=person) will get only one row - with person1. But I'd like to get two rows: - with both people. Because I want to get accounts with owners, where one of owners is person I can do it with SQL: SELECT * FROM structure_bankaccount INNER JOIN "structure_bankaccountperson" ON ("structure_bankaccount"."id" = "structure_bankaccountperson"."bank_account_id") WHERE structure_bankaccount.id in (SELECT bank_account_id FROM "structure_bankaccountperson" WHERE "structure_bankaccountperson"."person_id" = 1) I can do it with two steps: owned_accounts = BankAccountPerson.objects.filter(person=person).values_list('bank_account_id') collection = BankAccount.objects.filter(id__in=owned_accounts) But I wonder if I can do it with some Q, F or other function in one django filter... -
Django and Postgres "does not exist" when add new relation
Hi I'm havin some problems with Django and Postgres. Here's the model I'm working on: class UserMessage(models.Model): ... replied_by = models.ManyToManyField("users.User", related_name="replied_by_users", default=None, blank=True) When I add the field replied_by and perform the new migrations, all works but when I try to access to the model instances from database, it raised the following error: ProgrammingError at /admin/moments/usermoment/ relation "app_usermessage_replied_by" does not exist LINE 1: ...t"."event_id", "app_usermessage"."end_at" FROM "... And that's because there were already some instances before adding the replied_by field, but since I set the new field to None as default, it needs to ignore them. Here's a snippet of migration file: migrations.AddField( model_name='usermoessage', name='replied_by', field=models.ManyToManyField(blank=True, default=None, related_name='replied_by_users', to=settings.AUTH_USER_MODEL), ), How can I solve this problem without losing database data? Of course I'm in development mode, are there any good practice that I'm missing to handle database when you add a new relation. Thank you -
Can somebody help to fix this problem? im realy tired of trying
enter image description here class EmailVerificationView(TitleMixin, TemplateView): title = 'Store - Подтверждение электронной почты' template_name = 'users/email_verification.html' def get(self, request, *args, **kwargs): code = kwargs['code'] user = User.objects.filter(email=kwargs['email']) email_verifications = EmailVerification.objects.filter(user=user, code=code) if email_verifications.exists() and not email_verifications.first().is_expired(): user.is_verified_email = True user.save() return super(EmailVerificationView, self).get(request, args, **kwargs) else: return HttpResponseRedirect(reverse('index')) I already changed get to filter. Before i had get in user there was issue "get() returned more than one user -- it returned" Im trying to send email to verify acc. -
Django cannot find template, app is in installed_apps and backend DjangoTemplates is enabled
Inside of a page in my templates folder, I tried using an include statement in a for loop, like so: {% for model_othermodel in model.othermodels.all%} {% include othermodels.html with othermodel=model_othermodel %} {%endfor%} At first, I had the issue that it complained there was no key/value being sent to the other template, which was that othermodel=model_othermodel looked like other_model = model_othermodel. However, after that, I had the issue that it could not find the included html file (the file name is correct), for which the error problem would show me the base.html file that each page extends. (I will be using django_app to refer to the app folder) I got the error message: In template path\root\django_app\templates\base.html, error at line 0 No template names provided My base.html file is just a file for bootstrap that every other html file extends. My project structure looks like this: root/django_app root/django_project root/django_app/templates I tried adding the template path directly to 'DIRS' in TEMPLATES, such as so: DIRS = [os.path.join(BASE_DIR, django_app/templates/)] with variations such as django_app/templates, /templates/, /templates, etc. After that, I heard a suggestion to reorder my INSTALLED_APPS list, which is currently: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', 'django_app', ] to … -
Pythonanywhere deployment failure on the wsgi according to error log
I'm trying to deploy to Pythonanywhere and i believe i have followed all of the right steps. The latest error on the error log is: Error running WSGI application ModuleNotFoundError: No module named 'Project' File "/var/www/sizwe93_pythonanywhere_com_wsgi.py", line 17, in <module> application = get_wsgi_application() File "/home/sizwe93/.virtualenvs/mysite-virtualenv/lib/python3.10/site- packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) My WSGI file is on the Dashboard: from this # +++++++++++ DJANGO +++++++++++ # To use your own Django app use code like this: import os import sys # assuming your Django settings file is at '/home/myusername/mysite/mysite/settings.py' path = '/home/sizwe93/Project' if path not in sys.path: sys.path.insert(0, path) os.environ['DJANGO_SETTINGS_MODULE'] = 'Project.settings' ## Uncomment the lines below depending on your Django version ###### then, for Django >=1.5: from django.core.wsgi import get_wsgi_application application = get_wsgi_application() ###### or, for older Django <=1.4 #import django.core.handlers.wsgi #application = django.core.handlers.wsgi.WSGIHandler() I'm trying to deploy from my project on Github... I'm not sure what i'm missing, please help... -
print form value into the HttpResponseRedirect(HTML), Django
I'm filling in a reference number automatically when the form is loaded, now, i want to print this reference number to the HTML after the form is successfully submitted. !! views.py forms.py models.py HTML BTW, everything is working fine but the reference number never appeared !! please help -
How to use field variable of the model related with ForeignKey
I'm trying to create an Album model and a Song model which are both having a genre field. I want Song model's genre field is same with the Album model's by default. class Album(models.Model): genre = models.TextField() class Song(models.Model):` album = models.ForeignKey(Album, on_delete=models.CASCADE) genre = models.TextField() #The field I want to be same with its related model -
'ascii' codec can't decode byte 0xc3 in position 7: ordinal not in range(128)
Unicode error hint The string that could not be encoded/decoded was: Ubicación Getting error this spanish word in django standard translation. -
Django Web App Deployment on Render.com, Import Errors
I am currently trying to deploy my Django Web App to https://render.com/, but I got several problems, I am following this tutorial: https://www.youtube.com/watch?v=AgTr5mw4zdI, at 19:00 I have to import dj_database_url I have imported the Package in my Virtual Environment! This is what pip list says Here is my folder stucture: I think the problem is possibly because of the folder structure. Here is the Import -
Django form design
How can I make my form looks better? A few questions: How can I make the checkbox and buttons beside Favourite, Photo and Audio. And how can I change the design of the "Choose File" button to the same design as the "Save" and "Cancel" buttons? Can I show the image and audio after uploading it? BTW, I am using crispy form and Bootstrap 4. The html {% extends "base.html" %} {% block content %} <form method="POST" enctype="multipart/form-data"> <div class="mx-auto mt-4" style="width: 600px;"> {% csrf_token %} {{ form.as_p }} <div class="text-center"> <input type="submit" value="Save" class="btn btn-outline-info"> </div> </div> </form> {% if journal %} <div class="text-center"> <a href="{% url 'journal_detail' journal.id %}"><button type="button" class="btn btn-outline-info">Cancel</button></a> </div> {% else %} <div class="text-center"> <a href="{% url 'journal_list' %}"><button type="button" class="btn btn-outline-info">Cancel</button></a> </div> {% endif %} {% endblock %} -
Why does the form validation fail in this django formset?
I have been trying to make a django formset for giving feedback for assignments in a rubric style, where a form is generated for each criteria in an assignment, with the submissionID being automatically assigned, and the user selects what level the student has met a criteria to, and gives a comment about the criteria. Example: The problem I'm facing is that submitting the form does not do anything and just seems to refresh the current page, and I've tried everything I can think of to solve the problem, but the only thing I've managed to find out is where it is going wrong, which is at the line if form.is_valid(), which is returning false as it seems to be getting no forms passed to it for some reason. The expected result of the code is that when a post request is sent, it loops through the submitted forms, sets the submissionID, and saves the forms. So far I have tried doing some debugging by printing variables at different points of the code but mainly the line before it fails. Prints tried: formset: `(Hidden field TOTAL_FORMS) This field is required.(Hidden field INITIAL_FORMS) This field is required. ` Number of forms … -
Combine multiple django forms into one
I'm working with a django(4) project, Where I have two forms and want to combine them into one to display in my template with custom html not by sing {{form}} syntax. Here's my forms.py: class UserUpdateForm(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email'] # Create a ProfileUpdateForm to update image. class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['image'] How can I combine both of these forms into single one to display all the filed in HTML and submit as a single form? -
Why django translations don't work in celery task
I'm having problems with django text translations. My translation works fine in serializer, not in celery task. I have one "Person" model. There are 3 fields in the Person model. One of the fields is gender. The genders are defined in the "enums.py" file. In the serializer, the "get_gender_display()" method of the "Person" model works fine, but when I do the same in the celery task, it does not translate. It doesn't work even though I specify activate("tr") in the Celery task. I call the celery task from the serializer's create() method enums.py from django.utils.translation import gettext_lazy as _ class GenderTypeEnum: FEMALE = 1 MALE = 2 UNKNOWN = 3 types = ( (FEMALE, _("Female")), (MALE, _("Male")), (UNKNOWN, _("Unknown")) ) models.py from django.db import models from .enums import GenderTypeEnum from django.utils.translation import gettext_lazy as _ class PersonModel(models.Model): name = models.CharField( max_length=75, verbose_name=_('Name') ) last_name = models.CharField( max_length=75, verbose_name=_('Last Name') ) gender = models.PositiveIntegerField( choices=GenderTypeEnum.types, default=GenderTypeEnum.UNKNOWN, verbose_name=_('Gender') ) tasks.py from celery import shared_task from .models import PersonModel from django.utils.translation import gettext_lazy as _, activate, get_language @shared_task def test(): activate("tr") qs = PersonModel.objects.all() activate("tr") print(get_language()) # --> tr for obj in qs: print(obj.get_gender_display()) # --> always english, not translated serializers.py from rest_framework … -
Django debug toolbar not showing
My file directory system I have attached my file directory system. I have tried removing all *.pyc files as asked in some of the threads on the same topic, but the toolbar still doesn't show. The following is my webpage code: <html> <body> {% if name %} <h1>Hello {{ name }}!</h1> {%else%} <h1>Hello Dude!</h1> {% endif %} </body> </html> I tried adding mimetypes, adding the following code, and even editing the registry editor, but none of them are working. DEBUG_TOOLBAR_CONFIG = { "INTERCEPT_REDIRECTS": False, } No matter what I do, the browser console displays the following (though when I sometimes change the code the error doesn't get displayed, but neither does the toolbar). I'm using MS Edge, just in case it helps. Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/plain". Strict MIME type checking is enforced for module scripts per HTML spec. toolbar.js:1 When I try importing django in my virtual env, it says that there is no module called 'django'. I've tried all methods possible, but nothing seems to be working. -
Django. Need to load initial data to a form
I need to load data from database to form, so user can update it, but can't find a way to do it. with method below i get <django.db.models.query_utils.DeferredAttribute object at 0x000001DB8861EAC0> instead of currency. How to get data before putting it to dictionary in init_supplier? Thanks Here is my view.py: def supplier_form(request): s_data = supplier.objects.all init_supplier = { 'currency' : supplier.currency } submitted = False if request.method == "POST": form = s_form(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/home?submitted=TRUE') else: sup_form = s_form(initial=init_supplier) if submitted in request.GET: submitted = True return render(request, 'forms/supplier_form.html', {'sup_form':sup_form, 'submitted':submitted, 's_data' : s_data}) So far tried with init in forms and filtering in wievs. -
ModuleNotFoundError: No module named 'projects'
I deleted my migrations watching tutorials and when I try to make migration this error occurs ModuleNotFoundError: No module named 'projects' please help I have added my models.py file. from django.db import models import uuid from django.db.models.deletion import CASCADE from users.models import Profile >! Create your models here. class Project(models.Model): title = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) featured_image = models.ImageField( null=True, blank=True, default="default.jpg") demo_link = models.CharField(max_length=2000, null=True, blank=True) source_link = models.CharField(max_length=2000, null=True, blank=True) tags = models.ManyToManyField('Tag', blank=True) vote_total = models.IntegerField(default=0, null=True, blank=True) vote_ratio = models.IntegerField(default=0, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return self.title class Meta: ordering = ['-vote_ratio', '-vote_total', 'title'] @property def imageURL(self): try: url = self.featured_image.url except: url = '' return url @property def reviewers(self): queryset = self.review_set.all().values_list('owner__id', flat=True) return queryset @property def getVoteCount(self): reviews = self.review_set.all() upVotes = reviews.filter(value='up').count() totalVotes = reviews.count() ratio = (upVotes / totalVotes) * 100 self.vote_total = totalVotes self.vote_ratio = ratio self.save() class Review(models.Model): VOTE_TYPE = ( ('up', 'Up Vote'), ('down', 'Down Vote'), ) owner = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True) project = models.ForeignKey(Project, on_delete=models.CASCADE) body = models.TextField(null=True, blank=True) value = models.CharField(max_length=200, choices=VOTE_TYPE) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) class Meta: unique_together = [['owner', 'project']] def … -
How to create double nesting serializer in Django
While trying to create nested object, i'm getting this error. I may be using incorrect relationship here; need your expert guidance. Cannot assign "OrderedDict([('color', 'black), ('transmission', 'auto'), ('mileage', '20kmpl')])": "Vehicle.detail" must be a "Detail" instance Django==4.1.7 Python 3.9.13 Expecting { "auto_id": "some-uuid", "vehicle": [ { "manufacturer": "toyota", "year": 2020, "detail": { "color": "black", "transmission": "auto", "mileage": "20kmpl" } } ] } model class Auto(models.Model): auto_id = models.UUIDField(primary_key=True) class Detail(model.Model): color = models.CharField(max_length=10) transmission = models.CharField(max_length=10) mileage = models.CharField(max_length=10) class Vehicle(models.Model): manufacturer = models.CharField(max_length=10) year = models.PostiveIntegerField() auto = models.ForeignKey(Auto, related_name='vehicle', on_delete=models.cascade) detail = models.ForeignKey(Detail, on_delete=models.cascade) serializer class DetailSerializer(serializers.ModelSerializer): class Meta: model = Detail fields = ('color', 'transmission', 'mileage') class VehicleSerializer(serializers.ModelSerializer): detail = DetailSerializer() class Meta: model = Vehicle fields = ('manufacturer', 'year', 'detail') class AutoSerializer(serializers.ModelSerializer): vehicle = VehicleSerializer(many=True) class Meta: model = Auto fields = '__all__' def create(self, validated_data): vehicle_list = validated_data.pop('vehicle') auto = Auto.objects.create(**validated_data) for vehicle in vehicle_list: Vehicle.objects.create(auto=auto, **vehicle) return auto Could you please guide me, where i can convert the ordered dict for detail instance.