Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django.db.utils.OperationalError: database is locked even only when there a two user using the app simultaneously
I know this is a common question but I want something different. Is it possible to resolve this error without changing the database type? I am using sqlite3 and when 2 users are using the app, this error comes. I think the error might be due to the connection not being closed for a user. Is there a way to close the cursor cursor.close() manually in django? -
Docker Compose Shared Named Volume Permissions Denied
The following docker-compose spins up containers for a Django application: version: '3.7' services: web: build: context: . dockerfile: Dockerfile.prod container_name: web volumes: - static_volume:/static - media_volume:/media ... nginx: container_name: nginx build: ./nginx_proxy restart: always volumes: - static_volume:/static - media_volume:/media ... volumes: media_volume: static_volume: The web container is built using the following Dockerfile: # pull official base image FROM python:3.8 ... # organise permissions RUN chown -R manager:manager /static RUN chmod -R 755 /static RUN chown -R manager:manager /media RUN chmod -R 755 /media RUN ls -la ... When the permissions are printed as web container is being built, it returns the following: Step 21/23 : RUN ls -la ---> Running in e61984edfbcb total 1760 drwxr-xr-x 1 manager:manager 4096 Jan 25 00:00 media drwxr-xr-x 1 manager:manager 4096 Jan 25 00:00 static Removing intermediate container e61984edfbcb As expected and set in the Dockerfile. BUT when the containers are spun up (docker-compose up) and I look inside the permissions of the web container, I find the following: docker exec -it web bash manager@c8762586f678:/$ ls -la total 1760 drwxrwxr-x 3 root:root 4096 Sep 22 11:12 media drwxr-xr-x 3 manager:manager 4096 Sep 22 11:12 static Why do the two named volumes have different permissions - … -
how do i get to show the repeating event details on all following dates in python django
Event Name : Guest Booking Event State date : 1-feb-2022 and event ends on 5-feb-2022. Contact person : ABC Contact number : 12345 When I create this event on 1st of feb and end date will select as 5th of feb, my challenge is, created event should display event name, event date, contact person name and contact number till 5th of feb automatically, without me creating same for 2nd of feb, 3rd of feb till 5th of feb manually. -
Getting Error while entering the date input in the Admin Database
#model.py class Add_Timelog(models.Model): project=models.ManyToManyField(Project) client=models.ManyToManyField(Client) Job=models.ManyToManyField(Add_Job) Date = models.DateTimeField(max_length=100) Hours=models.TimeField(Date,null=True) def __str__(self): return str(self.Date) Settings.py DATE_INPUT_FORMATS = ('%Y-%m-%d') While I entered the Date in the admin database it is showing as an undefined in the field and throwing an error as an "enter a valid date". I have changed the formats and entered the date manually in the Date field based on the format mentioned, but still error is throwing. Kindly help to resolve the issue. enter image description here -
How to set data in Vuejs Mounted for amcharts?
I build restful APIs based on Django. It gives me: { "id": 1, "date": "2021-08-22", "team_name": "Juventus", "home_away": "AWAY", "name": "Dybala", "number": 9, "age": 27, "shots": 3, "SCA": 4, "touches": 54, "passes": 35 }, Now I want to visualize this data as a Radar Chart with amCharts. From the example amCarts store data like this: var data = [{ "category": "Lithuania", # should be Shots in my case "value": 501 # 3 }, { "category": "Czechia", #SCA "value": 301 }, ... { "category": "Germany", # etc "value": 165 }, }] My front end is on Vue and I do not know how to set data in the format amCharts is asking. Can I use a loop inside the Mounted function? Or it's better to change the format of the API? Or should I change the Model of my Django app? -
Django NFT architecture
I am quite new in NFT, just learning thing but i am good at django. I want to build NFT marketplace, Can i develop it with django? The question is very ameture i know but i don't know how it works, can anyone suggest me is it possible to develop NFT with django and reactjs? I found some snippet on internet of django and nft: from django.db import models class NFTProject(models.Model): contract_address = models.CharField(max_length=100) contract_abi = models.TextField() name = models.CharField(max_length=50) # e.g BAYC number_of_nfts = models.PositiveIntegerField() def __str__(self): return self.name -
Saving list in django database
I have a question about saving a list in Django database. Let me explain my problem, is pretty complex so I hope you understand that. At the base, I have a list of values (called learning objectives) where each student will have a grade from 1 to 5. Now, the idea is that the teacher, to give the evaluation, will press a checkbox corresponding to each grade and the database will create some sort of record to store the student's evaluation. models.py GRADING_VALUE = ( ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5'), ) class Grading(models.Model): value = models.CharField(max_length=10, choices=GRADING_VALUE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.value class LearningObjective(models.Model): name = models.CharField(max_length=300) mission = models.ForeignKey(Mission, on_delete=models.DO_NOTHING) grading = models.ForeignKey( Grading, on_delete=models.DO_NOTHING, blank=True, null=True) note = models.ForeignKey( Note, on_delete=models.DO_NOTHING, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class MissionEntry(models.Model): mission = models.ForeignKey(Mission, on_delete=models.DO_NOTHING) log_entry = models.ForeignKey(LogEntry, on_delete=models.DO_NOTHING) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return str(self.mission) + ' ' + str(self.log_entry) class LearningObjGradingNote(models.Model): learning_objective = models.ForeignKey( LearningObjective, on_delete=models.DO_NOTHING, blank=True, null=True) grade = models.ForeignKey( Grading, on_delete=models.DO_NOTHING, blank=True, null=True) note = models.ForeignKey( Note, on_delete=models.DO_NOTHING, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) views.py … -
Image files not importing Using Django
Hello Guys, I have one query in Django HTML. I was calling an image from the model in the HTML But it is not reflecting The code is listed below the below is the Models class UserProfileInfo(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, related_name='users1') portfolio_site = models.URLField(blank=True) bio = models.CharField(max_length=2000) profile_pic = models.ImageField(upload_to='profile_pics', blank=True) def __str__(self): return self.user.username the below is the Views files class UserDetailView(DetailView): context_object_name = 'users_detail' model = models.UserProfileInfo template_name = 'blog/user_detail.html' the below is the Html File {% extends "blog/base.html" %} {% load static %} {% block content %} <div class="container"> <h1>Welcome</h1> <table> <thead> <th>User Name</th> <th>portfolio_site</th> <th>bio</th> <th>profile_pic</th> </thead> <tr> <td>{{ users_detail.user }}</td> <td>{{ users_detail.portfolio_site }}</td> <td>{{ users_detail.bio }}</td> <td><img src="media/{{ users_detail.profile_pic }}" width ="300" alt="">media/{{ users_detail.profile_pic }} </td> </tr> </table> <p></p> <p><img src="media/profile_pics/denny.jpg" alt="hiiii">ho</p> </div> {% endblock %} -
typehead to get the refreshed list of data from the database in python django
file.js var source = new Bloodhound({ hint: false, datumTokenizer: Bloodhound.tokenizers.obj.whitespace("description"), queryTokenizer: Bloodhound.tokenizers.whitespace, // /a_c/p_s/?term=d&category=all remote: "/a_c/p_s/" + "?term=mobile&category=store", }); source.initialize(); $("#search-bar").typeahead(null, { name: "suggestion", displayKey: "search_text", source: source.ttAdapter(), }); }); urls.py path('a_c/p_s/<term>/<category>', views.product_search,name='product_search'), views.py def product_search(request, term, category): pass I have a category dropdown and an input field for search text. I have to get the suggestion list from the database based on the changed value of category dropdown and input search text value I'm using typeahead . I don't know whether i'm doing it right or not with typehead bloodhound. Please if anyone could help me with that. I'm getting an error of url not found in console. -
How to merge QuerySets from the same model
I want to combine (|) a series of QuerySets:all_english_text in a loop: tag_result = Tag.objects.get(id=all_tag[index]) all_english_text = tag_result.notes.all().values('english_text', 'id') by the following def: def list_by_tag_post(request): # get POST all_tag = request.POST.getlist('tag_list') for index in range(len(all_tag)): tag_result = Tag.objects.get(id=all_tag[index]) all_english_text = tag_result.notes.all().values('english_text', 'id') result = list(chain(*all_english_text)) # Merging method all_english_text = result # to template context = {'all_english_text': all_english_text, 'all_tag': all_tag} return render(request, 'list_by_tag.html', context) 3 methods were tried, they all didn't work: result = list(chain(*all_english_text)) # Merging method 1 result = chain(*all_english_text) # Merging method 2 result = all_english_text.union(*all_english_text))# Merging method 3 -
Downloading Image from URL - from AWS S3 on flutter and saving it to the gallery FLUTTER
So prior to switching to AWS S3. I was using Gallery saver (https://pub.dev/packages/gallery_saver) I switched to hosting media files on AWS S3 (with django as my back end) and was trying to download an image. I pass in the URL(signed URL) that points to the media file in my aws s3 bucket and now its not downloading the image and saving it to the gallery. this is what I was using before, no code has changed: await GallerySaver.saveImage(url); is there any other way to save images from a url link to an AWS S3 object to your gallery in flutter. Am I doing something wrong? The image it self loads perfectly in flutter using CachedNetworkImage so I know the URL works and when I click the url in the browser, I'm able to access/download the image. -
How to set user type in a customuser model when a new user registers
I have two models CustomUser and Manager_profile given below. There are 2 types of users a manager and a customer. There is a form to register as a manager. How can I set the is_manager field to True when a manager registers? I also have another question. How can I store the data from department field to the Manager_profile model? #Models class CustomUser(AbstractUser): is_manager = models.BooleanField(default=False) is_customer = models.BooleanField(default=False) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) def __str__(self): return self.first_name class Manager_profile(models.Model): user = models.OneToOneField(CustomUser,on_delete=models.CASCADE) department = models.CharField(max_length=100) def __str__(self): return self.department #Form from django.contrib.auth.forms import UserCreationForm from account.models import CustomUser from django import forms class ManagerCreateForm(UserCreationForm): department = forms.CharField() class Meta: model = CustomUser fields = ['username','first_name','last_name','department'] -
Question regarding HTML form action attribute
I have used Django to set up the backend of a web app and have an HTML form I am using as a signup page and was wondering if there's anything I need to add to the Forms' form action attribute. What I am trying to do is grab the data that the user has posted it and send it over to PGadmin database. Here is my html form for reference: <div> {% block content %} <form action="" method="post" name="Userinfo" id="Userinfo"> <label for="fname">First Name</label> {% csrf_token %} <input type="text" id="fname" name="firstname" placeholder="Your first name.."> <label for="lname">Last Name</label> <input type="text" id="lname" name="lastname" placeholder="Your last name.."> <label for="DOB">Date Of Birth</label> <input type="text" id="DOB" name="DOB" placeholder="The Date you were born"> <label for="Email">Email Address</label> <input type="text" id="Email" name="Email" placeholder="Your email address"> <input type="submit" value="Submit"> </form> {% endblock %} </div> P.S this isn't all the whole file, just a snippet. Also here is the views.py file that I have, which makes any imputed data get processed as a POST request vs as a GET. Not sure if there is anything I need to add in order to make it send the data to PGadmin. class CommentForm(forms.Form): fname = forms.CharField(max_length=25) lname = forms.CharField(max_length=25) dob = forms.datefield() … -
child model accesing the parent model feild in django
Hello guys I have one query in my Django project. I Have two models as mentioned below UserProfileInfo and Post. I want to bring profile_Pic in the Post model so that I can call in HTML. class UserProfileInfo(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, related_name='users1') portfolio_site = models.URLField(blank=True) bio = models.CharField(max_length=2000) profile_pic = models.ImageField(upload_to='profile_pics', blank=True) def __str__(self): class Post(models.Model): ) author = models.ForeignKey( UserProfileInfo, related_name='users', on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.CharField(max_length=2000) create_date = models.DateTimeField(default=timezone.now()) published_date = models.DateTimeField(blank=True, null=True) def __str__(self): return self.title -
Django Form says image field is required meanwhile image is uploaded in Graphql Altair client
I'm using GraphQL in a Django project and the Altair GraphQL client, and I'm facing an issue with file uploads. When the request is submitted via Altair, the submitted fields are detected in my ImageUploadMutation. After initialising the form with the fields (form = ArtistPhotoForm({'photo': file})), form.data also prints the right fields. However, after calling the form.is_valid() method, I get photo: This field is required! Here are the important code segments: models.py class ArtistPhoto(models.Model): # Use width_field and height_field to optimize getting photo's width and height # This ThumnailerImageField is from easy_thumbnails; but i don't think the issue is here photo = ThumbnailerImageField( thumbnail_storage=FILE_STORAGE_CLASS(), upload_to=ARTISTS_PHOTOS_UPLOAD_DIR, resize_source=dict(size=(1800, 1800), sharpen=True), validators=[FileExtensionValidator(['png, jpg, gif'])], width_field='photo_width', height_field='photo_height' ) photo_width = models.PositiveIntegerField() photo_height = models.PositiveIntegerField() forms.py class ArtistPhotoForm(forms.ModelForm): class Meta: model = ArtistPhoto fields = ['photo'] mutation # Output class contains the fields success and errors class ImageUploadMutation(graphene.Mutation, Output): class Arguments: file = Upload(required=True) form_for = ImageFormEnum(required=True) # Apparently this should be an instance method not a class method @verification_and_login_required def mutate(self, info, file: InMemoryUploadedFile, form_for, **kwargs): if form_for == 'artist_photo': form = ArtistPhotoForm({'photo': file}) if form.is_valid(): print("Form is valid") print(form.cleaned_data) return ImageUploadMutation(success=True) print(form.errors) return ImageUploadMutation(success=False, errors=form.errors.get_json_data()) I get the error message { "data": { … -
Python django how i can prevent the duplicate entry of studnumber,email,username(unmae) in registration?
Python Django how i can prevent the duplicate entry of studnumber,email,username(unmae) in registration? def Unreg(request): if request.method=='POST': studnumber=request.POST['studnumber'] fname=request.POST['fname'] age=request.POST['age'] gender=request.POST['gender'] uname=request.POST['uname'] email=request.POST['email'] pwd=request.POST['pwd'] contact=request.POST['contact'] newacc(studnumber=studnumber,fname=fname,age=age,gender=gender,uname=uname,email=email,pwd=pwd,contact=contact).save() messages.success(request,"The New User is save !") return render(request,'Registration.html') else: return render(request,'Registration.html') -
My local django project works, and it also works on Heroku until i submit form and then i get error when it works fine locally
I have a website with an email form and when i submit locally it works. When i submit form on heroku i got a 500 server error or an application error. What can i do?? 2022-02-02T01:30:06.285140+00:00 app[web.1]: response = response or self.get_response(reque st) 2022-02-02T01:30:06.285140+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-p ackages/django/core/handlers/exception.py", line 49, in inner 2022-02-02T01:30:06.285140+00:00 app[web.1]: response = response_for_exception(request, exc ) 2022-02-02T01:30:06.285140+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-p ackages/django/core/handlers/exception.py", line 103, in response_for_exception 2022-02-02T01:30:06.285141+00:00 app[web.1]: response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) 2022-02-02T01:30:06.285141+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-p ackages/django/core/handlers/exception.py", line 47, in inner 2022-02-02T01:30:06.285141+00:00 app[web.1]: response = get_response(request) 2022-02-02T01:30:06.285141+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-p ackages/django/core/handlers/base.py", line 179, in _get_response 2022-02-02T01:30:06.285142+00:00 app[web.1]: response = wrapped_callback(request, *callback _args, **callback_kwargs) 2022-02-02T01:30:06.285142+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-p ackages/django/views/generic/base.py", line 70, in view 2022-02-02T01:30:06.285143+00:00 app[web.1]: return self.dispatch(request, *args, **kwargs) 2022-02-02T01:30:06.285143+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-p ackages/django/views/generic/base.py", line 98, in dispatch 2022-02-02T01:30:06.285143+00:00 app[web.1]: return handler(request, *args, **kwargs) 2022-02-02T01:30:06.285143+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-p ackages/django/views/generic/edit.py", line 142, in post 2022-02-02T01:30:06.285144+00:00 app[web.1]: return self.form_valid(form) 2022-02-02T01:30:06.285144+00:00 app[web.1]: File "/app/mainpage/views.py", line 30, in for m_valid 2022-02-02T01:30:06.285144+00:00 app[web.1]: send_mail( 2022-02-02T01:30:06.285144+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-p ackages/django/core/mail/__init__.py", line 61, in send_mail 2022-02-02T01:30:06.285145+00:00 app[web.1]: return mail.send() 2022-02-02T01:30:06.285145+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-p ackages/django/core/mail/message.py", line 284, in send 2022-02-02T01:30:06.285146+00:00 app[web.1]: return self.get_connection(fail_silently).send _messages([self]) 2022-02-02T01:30:06.285149+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-p ackages/django/core/mail/backends/smtp.py", line 109, in send_messages 2022-02-02T01:30:06.285149+00:00 app[web.1]: sent … -
Como rescato informacion de un select en html con Django
Buenas a todos estoy trabajando con formularios con Django y necesito rescatar la informacion de un select y mandarla hacia la view pero no encuentro manera de hacerlo, si alguien podria ayudarme porfavor, gracias de antemanoenter image description here -
Production not the same as local
When running locally my files are correct but on production it seems that none of the changes are through. I might be forgetting to do something to make the production files the same as local. TemplateDoesNotExist at / inbox.html Request Method: GET Request URL: https://url.com/ Django Version: 3.2.9 Exception Type: TemplateDoesNotExist Exception Value: inbox.html Exception Location: /app/.heroku/python/lib/python3.9/site-packages/django/template/backends/django.py, line 84, in reraise Python Executable: /app/.heroku/python/bin/python Python Version: 3.9.6 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python39.zip', '/app/.heroku/python/lib/python3.9', '/app/.heroku/python/lib/python3.9/lib-dynload', '/app/.heroku/python/lib/python3.9/site-packages'] Server time: Tue, 01 Feb 2022 16:02:49 -0800 settings.py """ Django settings for portfolio project. Generated by 'django-admin startproject' using Django 3.2.9. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! import os #Gets rid of from decouple import config SECRET_KEY = config("SECRET_KEY") # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True #DEBUG = config('DJANGO_DEBUG',default=True, cast=bool) ALLOWED_HOSTS = ["url.com",'127.0.0.1','localhost'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', … -
Best way to create a queue for handling request to REST Api created via Django
I have the following scenario: Back end => a geospatial database and the Open Data Cube tool API => Users can define parameters (xmin,xmax,ymin,ymax) to make GET requests Process => On each requests analytics are calculated and satellite images pixels' values are given back to the user My question is the following: As the process is quite heavy (it can reserve many GB of RAM) how it is possible to handle multiple requests at the same time? Is there any queue that I can save the requests and serve each one sequently? Language/frameworks => Python 3.8 and Django Thanks in advance -
Render ModelForm in different app's template
Is there a way I could render the following modelform in a different template outside of it's app, it works correctly on a template inside the app but does not work outside of it. Models.py class Bid(models.Model): tasker = models.ForeignKey(Tasker, on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=0) task_owner = models.ManyToManyField(User, blank=True) completed = models.BooleanField(default=False) Forms.py class CreateBidForm(forms.ModelForm): class Meta: model = Bid fields = ( 'tasker', 'price', 'task_owner', 'completed' ) Views.py class SubmitBid(CreateView): template_name = "listing_detail.html" form_class = CreateBidForm def post(self, request): form = CreateBidForm(request.POST or None, request.FILESquest) if form.is_valid(): bid = form.save(commit=False) bid.tasker = request.user bid.save() return redirect('/') -
Trying to add new model and field to existing data in Django
I'm learning Django and making a kind of social network and am trying to add a model and field to my models. The following post perfectly explains what I'm trying to do... Django - Private messaging conversation view I'm trying to add the model and field after I already have some messages saved. I'm making this for learning purposes for now, so deleting the existing messages and starting over would probably solve the problem, but I'm trying to learn how to navigate this because next time I could have actual users and deleting the messages might not be possible. Here are my models: from django.db import models from django.contrib.auth.models import User # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) city = models.CharField(max_length=60) country = models.CharField(max_length=60) skillstolearn = models.CharField(max_length=200) skillstoteach = models.CharField(max_length=200) description = models.TextField() def __str__(self): return self.user.username class Conversation(models.Model): participants = models.ManyToManyField(User) def __str__(self): return self.participants class Message(models.Model): sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name='sender') receiver = models.ForeignKey(User, on_delete=models.CASCADE, related_name='receiver') content = models.TextField() conversation = models.ForeignKey(Conversation, default=None, on_delete=models.CASCADE) timestamp = models.DateTimeField() def __str__(self): return self.sender.username + ' to ' + self.receiver.username Before trying to make the current migrations, the file did not have the Conversation model nor the … -
Is there any other way passing lookup parameters in django
I'm trying to pass a lookup parameter to my views.py to render to the templates model.py class Category(models.Model): name = models.CharField(max_length=20) slug = models.SlugField(max_length=200, blank=True, unique=True) class Post(models.Model): """" created_on = models.DateTimeField(auto_now_add=True) cover = models.ImageField(null=True, blank=True ) categories = models.ManyToManyField(Category, related_name='posts', blank=True) views.py def index_category(request, category): posts = Post.objects.filter(categories__name__contains=category).order_by('-created_on') context = { "category": category, "posts": posts, } return render(request, "blog/index_category.html", context) index_category.html {% extends "base.html" %} {% block content %} <div class="col-md-8 offset-md-2"> <h1>{% block title %}{{ category | title }}{% endblock title %}</h1> <hr> {% for post in posts %} <h2><a href="{% url 'index-detail' post.slug %}">{{ post.title }}</a></h2> <small> {{ post.created_on.date }} |&nbsp; Categories:&nbsp; {% for category in post.categories.all %} <a href="{% url 'blog-category' category.name %}"> {{ category.name }} </a>&nbsp; {% endfor %} </small> <p>{{ post.body | slice:":200" }}...</p> {% endfor %} </div> {% endblock %} When i refresh my localhost on my category page, it's returning nothing except the block title. Is there any other way to filter the many-to-many relationship between the post and the category??? -
I want to nest a model into the Serialiazer. Category' object has no attribute 'brand_set'
I want to nest a model into the serializer. Like on list of Category, there should be fields from Brand model, But I m getting error by on setting this way ? models.py class Category(models.Model): title = models.CharField(max_length=50) timestamp = models.DateTimeField(auto_now_add=True) #.... class Brand(models.Model): title = models.CharField(max_length=50) category = models.ForeignKey( Category, blank=True, null=True, on_delete=models.SET_NULL, related_name="category") #.... Serializers class CategorySerializerNested(serializers.ModelSerializer): brands = serializers.SerializerMethodField(read_only=True) class Meta: model = Category fields = '__all__' def get_brands(self, obj): brands = obj.brand_set.all() #this thin popping error how to fix that.... serializer = BrandSerializerNested(brands, many=True) return serializer.data class BrandSerializerNested(serializers.ModelSerializer): products = serializers.SerializerMethodField(read_only=True) def get_products(self, obj): products = obj.product_set.all() serializer = ProductSerializer(products, many=True) return serializer.data class Meta: model = Brand fields = '__all__' View.py @api_view(['GET']) def getCategoryWithBrands(request, pk): category = Category.objects.get(id=pk) serializer = CategorySerializerNested(category, many=False) return Response(serializer.data) url.py path('nested/<str:pk>/', views.getCategoryWithBrands, name="category-with-brands"), Error: AttributeError: 'Category' object has no attribute 'brand_set' [02/Feb/2022 03:24:49] "GET /api/v1/categories/nested/1/ HTTP/1.1" 500 125121 I'm sure im doing something illogical but i dont know now, please help me to fix this , if there's any better way to do that please also help there as well. Thanks -
Duplicates with ManyToMany
I have model: class GPD(models.Model): employee = models.ForeignKey(Employee, verbose_name='Employee', on_delete = models.CASCADE, related_name='+') gpd_year = models.PositiveIntegerField(default=2021, validators=[ MaxValueValidator(2121), MinValueValidator(2021) ]) corp_goal = models.ManyToManyField(CorporateGoal, blank=True) team_goal = models.ManyToManyField(TeamGoal, blank=True) ind_goal = models.ManyToManyField(IndividualGoal, blank=True) def __str__(self): print('**********************') print(self.corp_goal.all()) print('**********************') return 'GPD ' + str(self.gpd_year) + ' for ' + self.employee.name + ' ' + self.employee.lastname As you can see, I have many to many relationship and when I am trying to print(self.corp_goal.all()) I have duplicates: When I am using print(self.corp_goal.all().distinct()) - I have the same problem. How fix it?