Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
- 
        Assigning several model instances of one Model to another Model, and then comparing them?I have a model called Hero, which has about 500 different objects. I'm having the user select 4 instances of Hero in a form, and assigning them to a Match model to register what Heroes they played with. I've tried creating a Deck model, that could contain the 4 heroes and then assign that Deck model in Match model and form, but then the user can't select a new combination, only current Deck combinations. This works fine in the adminpanel, where I can add new combinations, but the user doesn't get that opportunity. It's not quite what I want and I can't wrap my head around, is how I can then later compare two instances of Deck or the selected Heroes in Match to see if the user selected the same Heroes in their Deck/Match and/or count how many times that specific combination of Hero is used in a deck/Match. In short: What I want is for the user to, through a form, select 4 Hero objects and save them to a Deck model. If their specific combination of selected Heroes is already in Deck, then it should register it under that. I know it's confusing, but that's owing to …
- 
        How to empty Cart After checking out or making Order?DjangoI have e commerce project,I need to empty cart after user checkout and order status is "shipped also if I empty cart manually also orders already made be empty! where is the problem in code and how to separate cart and orders made? def checkout_home(request): cart_obj, cart_created = Cart.objects.new_or_get(request) order_obj = None if cart_created or cart_obj.products.count() == 0: return redirect("cart:home") login_form = LoginForm() address_form = AddressForm() shipping_address_id = request.session.get("shipping_address_id", None) address_qs = None if request.user.is_authenticated: address_qs = Address.objects.filter(user=request.user) order_obj, order_obj_created = Order.objects.new_or_get(cart_obj=cart_obj,user=request.user) if shipping_address_id: order_obj.shipping_address = Address.objects.get(id=shipping_address_id) del request.session["shipping_address_id"] order_obj.save() context = { "object": order_obj, # "billing_profile": billing_profile, "login_form": login_form, "address_form": address_form, "address_qs": address_qs,} return render(request, "carts/checkout.html", context) def checkout_done_view(request): Orders = Order.objects.filter(user=request.user) return render(request, "carts/checkout-done.html",{"orders":Orders}) orders.models.py class OrderManager(models.Manager): def new_or_get(self, user, cart_obj): created = False qs = self.get_queryset().filter( user=user, cart=cart_obj, active=True, status='created' ) if qs.count() == 0: obj = self.model.objects.create( user=user, cart=cart_obj) created = True else: obj = qs.first() return obj, created class Order(models.Model): user = models.ForeignKey(User,null=True, blank=True, on_delete=models.CASCADE) shipping_address = models.ForeignKey(Address, on_delete='CASCADE',related_name="shipping_address",null=True, blank=True) # shipping_address_final = models.TextField(blank=True, null=True) order_id = models.CharField(max_length=120, blank=True) cart = models.OneToOneField(Cart, on_delete=models.CASCADE) status = models.CharField(max_length=120, default="created", choices=ORDER_STATUS_CHOISES) shipping_total = models.DecimalField(default=5.00, max_digits=100, decimal_places=2) total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) active = models.BooleanField(default=True) date_posted = models.DateTimeField(default=timezone.now) objects …
- 
        Login with jwt authentication not workingI have tried creating a user login api with jwt authentication but instead of returning the token it is always returning not authorised. This code seemed to work earlier in the initial phase but now it is just not working. I have no idea what is wrong. I have added the jWT_AUTH and Authentication classes in settings.py . Please Help serializer class UserLoginSerializer(serializers.ModelSerializer): username = serializers.CharField() password = serializers.CharField() class Meta : model = User fields = ('username','password') class TokenSerializer(serializers.Serializer): token = serializers.CharField(max_length=255) views from django.contrib.auth.models import User from django.contrib.auth import authenticate, login from rest_framework_jwt.settings import api_settings jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER class LoginView(generics.CreateAPIView): permission_classes = (permissions.AllowAny,) serializer_class = UserLoginSerializer queryset = User.objects.all() def post(self, request, *args, **kwargs): username = request.data.get("username", "") password = request.data.get("password", "") user = authenticate(request, username=username, password=password) if user is not None: login(request, user) serializer = TokenSerializer(data={ "token": jwt_encode_handler( jwt_payload_handler(user) )}) if serializer.is_valid(): return Response(serializer.data['token']) return Response("Not Authorized",status=status.HTTP_401_UNAUTHORIZED) I cannot login even when I am using correct username and password.
- 
        Django list of files returns an empty arrayI'm starting with Django, so I'm pretty new to this. I'm sending a file to the Django server, saving it, trying to get the last file (the one I just send) from the saved folder and then I want to perform some processes on that file, after that I want to delete the original file. I already managed to upload and save the file to the filesystem, but I'm having trouble selecting this file from the folder. I'm trying select and remove it this way: @api_view(['POST', 'GET']) def geojson_to_shape_view(request): if request.method == 'POST': serializer = FileSerializer(data=request.data) if serializer.is_valid(): # serializer.save() calls .create() in serializers.py file = serializer.save() # Get last saved file print("Analyzing last posted file...") list_of_files = glob.glob('../media/temp_files/*') print(list_of_files) if list_of_files: latest_file = max(list_of_files, key=os.path.getctime) print("Deleting last posted file...") try: os.remove(latest_file) pass except: print("Can't remove the file") return Response(FileSerializer(file).data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) And this code returns: Analyzing last posted file... [] I tried to run a script in the same folder with these file interactions and it run with no problems, so I thinking is some django permission issue. I also tried to change the path to settings.MEDIA_ROOT + 'temp_files/*', but the problem persists.
- 
        Django: Query with foreign keyI have two models called Thread and Post. A Thread has 0..* posts. Now, I need a query that gets all threads sorted by the datetime of the latest post in the thread. In case there is no post yet in the thread, the datetime of the thread creation is important. Honestly, I am a bit overwhelmed with the database query. Thread: created_at = DateTimeField() Post thread = ForeignKey(Thread) My current approach does not work: newest = Post.objects.filter(thread=OuterRef('pk')).order_by('-created_at') threads = Thread.objects.annotate( latest_post=Case( When(Exists(Subquery(newest.values_list('created_at')[:1])), then=Value(Subquery( newest.values_list('created_at')[:1]), ), default=Value(Thread.created_at)))).order_by('-latest_post') Can someone help me?
- 
        Inconsistency between test and django: :int() argument must be a string but also TypeError: string indices must be integersI have an API view that receives a request and creates some data. It works fine. When I am running my test I wrote with pytest I receive this error: node_name = (data_node['name']) TypeError: string indices must be integers When I change my code to be an integer like this: node_name = int((data_node['name'])) my django view gives me this error: :int() argument must be a string And I am like... whuat?! This is my view (shortened for brevity): @api_view(['POST']) def CreateGraphView(request): for data_node in nodes: print(type(data_node)) node_name = (data_node['name']) print(node_name) print(type(node_name)) new_node = Node.objects.create(name=node_name) status_code = HttpResponse.status_code return Response(status_code) The data (request) I am sending looks like this: {'project': 'project1', 'name': 'Graph1', 'description': 'test', 'nodes': [{'name': '25', 'graph': 3}], 'edges': [{'name': 'EdgeForGraph1', 'graph': 3, 'source': '25', 'target': '25'}]} And finally, if it helps my test (I send the same data): def test_aut_user_can_create_graph(self, client): data = data url = api_reverse('nameofurl') response = client.post(url, data) assert response.status_code == 201 I am very confused why my test wouldn't accept the code and my code wouldn't accept my test. Especially because when debugging and printing out the type of data_node it tells me it is a dict. So that should be correct. Can someone …
- 
        Django-filter, how to make multiple fields search? (with django-filter!)How can I make multiple fields search with Django-filter from model like: class Location(models.Model): loc = models.CharField(max_length=100, blank=True) loc_mansioned = models.CharField(max_length=100, blank=True) loc_country = models.CharField(max_length=100, blank=True) loc_modern = models.CharField(max_length=100, blank=True) I need one input field on my website, that can search over all fields of Location model
- 
        Cancel the POST when the page is refreshedMy problem is : When an user refresh the Form the data in the Form is sent. I have a Form with request POST. The user write his name, mail and message. If the mail is correct the message is sent. In my view if the Form is valid, I add the message in my model Message. After that I disable the button "Send". But if the user refresh the page. My view is called and an other row is added in my model. I would like, when the user refresh the page, block the POST. My View: def contact(request): form = MessageForm(request.POST or None) if form.is_valid(): name = form.cleaned_data['name'] message = form.cleaned_data['message'] mail = form.cleaned_data['mail'] new_message = Message() new_message.name = name new_message.message = message new_message.mail = mail new_message.save() envoi = True return render(request, 'vautmieux/contact.html', locals()) My url: path('contact/', views.contact, name='contact'), My HTML: <form action="{% url "contact" %}" method="post"> {% csrf_token %} <div class="row"> <div class="col-md-6"> {{ form.name }} {{ form.mail }} </div> <div class="col-md-6" > {{ form.message }} </div> <button id="sendMessageButton" type="submit">ENVOYER LE MESSAGE !</button> </div> {% if envoi %}Votre message a bien été envoyé !{% endif %} </form>
- 
        How to create invite code only registration app in Django 2.2?How do i create invite code only registration app in Django 2.2 using "alllauth". Can't find any updated repository
- 
        Avoid non-specified attributes on model creationI want to create an object in Python but, since I'm using Django, I don't want to save those attributes with None or null value. When I create an object passing a couple of arguments, those attributes passed are assigned correctly; but the rest, which I wish were not created, are assigned the value "None" models.py: from djongo import models from mongoengine import * class MyClass(Document): _id = StringField(max_length=20, primary_key = True) atr1 = StringField() atr2 = StringField(max_length=300) atr3 = EmbeddedDocumentField(AdministrativeOptions) atr4 = EmbeddedDocumentField(CancelationPolicy) atr5 = StringField(max_length=50) atr6 = IntField() views.py: def index(request): a = MyClass( _id = 'TestID', atr1 = 'Xxxx' ) for key in a: print(str(key) + " = " + str(a[key])) a.save() What I get from the print loop is: _id = TestID atr1 = Xxxx atr2 = None atr3 = None atr4 = None atr5 = None atr6 = None Which means I am saving an object full of empty data. I would like to save a MyClass object with just the specified attributes in order to save space in memory.
- 
        Repeat command in while loop or similar until not existing result is foundi need to repeat a cmd which always generated a new random string, after that i need to make sure that this specific string has not been generated before. I never did while loops before and im not able to figure out how to repate the cmd until a result has been found which is not already part of the database. I can't be to specific as this source is closed all this is packed into a celery task tasks.py @app.task def allocate_new_string(user_pk): user = User.objects.get(pk=user_pk) new_string = subprocess.Popen("$get_new_string_cmd", shell=True, stdout=subprocess.PIPE).communicate()[ 0].decode('utf-8').strip() try: while True: if Used_String.objects.filter(string=new_string, atom=0).exists(): new_string << how to repeat the command from above here until a new random string has been found? else: used_string = Used_String.objects.create(user=user, string=new_string, atom=0) used_string.save() logger.info(str("New String has been set) except: logger.info(str("Something went wrong while processing the task")) The function i want to have here is: Search for a none existing sting until one has found that has never been generated before or is at least not part of the database. the cmd im using isn't openSSL or something like that and it's quite likly that i hit two times the same random generated string. Thanks in advance
- 
        How to have another text input in django form in admin user page?I am trying to add another user input but when I added it in forms.py, it didn't show me anything in admin page. Although it is showing in browser page. forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField(required=True) Id = forms.CharField(max_length=15, required=True) class Meta: model = User fields = ['username','email','password1','password2','Id']
- 
        duplicate key value violates unique constraint "core_user_username_key" DETAIL: Key (username)=(patient1) already existsOn the change password page, when you enter a new password and repeat it, get out such an error, how to fix it? Request Method: POST Request URL: http://0.0.0.0:8010/callcenter/patient/2/password_change Django Version: 2.1.5 Exception Type: IntegrityError Exception Value: duplicate key value violates unique constraint "core_user_username_key" DETAIL: Key (username)=(patient1) already exists. Exception Location: /usr/local/lib/python3.7/site-packages/django/db/backends/utils.py in _execute, line 85 Python Executable: /usr/local/bin/python Python Version: 3.7.2 Python Path: ['/opt/project', '/opt/project', '/opt/.pycharm_helpers/pycharm_display', '/usr/local/lib/python37.zip', '/usr/local/lib/python3.7', '/usr/local/lib/python3.7/lib-dynload', '/usr/local/lib/python3.7/site-packages', '/opt/.pycharm_helpers/pycharm_matplotlib_backend'] I tried to add forms.py class Meta: model = User fields = ('username', 'first_name', 'last_name', 'password1', 'password2') but it did not help forms.py class CallcenterPasswordChange(forms.ModelForm): password1 = forms.CharField(widget=forms.PasswordInput(), label='Новый пароль') password2 = forms.CharField(widget=forms.PasswordInput(), label='Повтор нового пароля') def clean(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError( self.error_messages['password_mismatch'], code='Повтор нового пароля не совпадает',) return self.cleaned_data def save(self, commit=True): user = super(CallcenterPasswordChange, self).save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user class Meta: model = User fields = ('password1', 'password2') password_cahnge.html {% extends 'callcenter/base.html' %} {% load static %} {% block inside_content %} <h1>Введите новый пароль</h1> <form action="{% url 'callcenter:password_change' patient_pk %}" method="post" enctype="multipart/form-data"> {{ form.as_p }} {% csrf_token %} <p><input type="submit" value="Изменить пароль"></p> </form> {% endblock %} views.py class CallcenterPasswordChangeView(AbsCallcenterView): template_name = 'callcenter/password_change.html' …
- 
        Is it possible to force a website input to be in English?I'm creating a website in 2 languages - English and Hebrew. I have an input field (the slug/username) which must be in English. When I enter the website from my mobile phone, I can write text in Hebrew. Is it possible to force the keyboard to be in English in this input field? I noticed that for the email address (email input) the keyboard is already in English.
- 
        TypeError: quote_from_bytes() expected bytes after redirectI wrote a function which after execution returns the user to the anchor page. But I'm getting an error. TypeError: quote_from_bytes() expected bytes view.py class CourseEditView(AuthorizedMixin, UpdateView): """ Edit course instances """ model = Courses form_class = CoursesEditForm template_name = 'additional_info_edit.html' def get_success_url(self): pk = self.object.employee.pk return redirect('{}#education'.format(reverse('profile', kwargs={'pk': pk}))) How to avoid a mistake?
- 
        Based on the side nav load data in the main templatethis is img I have a side nav, on selection from side nav that particular html must load in the index.html page. How do I go about implementing in django. views.py class IndexView(TemplateView): template_name = 'index.html' def get(self, request, *args, **kwargs): associate_id = id_to_numeric(request.user.username) user_details = usr_model.objects.using('users').filter(associate_nbr=associate_id) assoc_data = AssocDetailsTb.objects.filter(associate_nbr=associate_id) if assoc_data.exists(): details = AssocDetailsTb.objects.get(associate_nbr=associate_id) return render(request, 'index.html', {'details': details}) else: name ='' nbr ='' client ='' lob='' img ='' for i in user_details: name = i.associate_name nbr = i.associate_nbr client = i.client lob =i.lob img = i.associate_image print(client,lob) cli = ClientTb.objects.get(client_name = client) print(cli.id) lo = LobTb.objects.get(lob_name=lob) data = AssocDetailsTb() data.associate_name = name data.associate_nbr = nbr data.client = cli data.lob = lo data.associate_image = img data.save() return render(request, 'index.html') def page1(request): associate_id = id_to_numeric(request.user.username) details = AssocDetailsTb.objects.get(associate_nbr=associate_id) return render(request,'page1.html',{'details':details}) html <ul class="sub-menu children dropdown-menu"> <li><i class="fa fa-hospital-o"></i><a href="{% url 'qual:page1'%}">Accounts Receivable</a></li> I want to load all the templates in the same page
- 
        how to start a task at a specific time with django & celeryI'm using Celery and it work for async but i need to setup an opertion to a specific datetime for example "the 30 of august 2019 at 11 and 35 min do this" my celery.py is very easy now but it work: import time from datetime import datetime, timedelta from datetime import date from celery import shared_task,current_task, task from celery import Celery app = Celery() @app.task def test(): print ('1') todaynow = datetime.now() print todaynow i call it from view and run print on rabbit any idea for program a task? ty
- 
        If you see valid patterns in the file then the issue is pro bably caused by a circular importI tried to import pyrebase in my views.py, but I've got an error arisen: Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\USER\Documents\python projects\yerekshe\lib\site-packages\django\urls\resolvers.py", line 581, in url_patterns iter(patterns) TypeError: 'module' object is not iterable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\USER\AppData\Local\Programs\Python\Python36\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Users\USER\AppData\Local\Programs\Python\Python36\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "C:\Users\USER\Documents\python projects\yerekshe\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\USER\Documents\python projects\yerekshe\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\USER\Documents\python projects\yerekshe\lib\site-packages\django\core\management\base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "C:\Users\USER\Documents\python projects\yerekshe\lib\site-packages\django\core\management\base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\USER\Documents\python projects\yerekshe\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\USER\Documents\python projects\yerekshe\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\USER\Documents\python projects\yerekshe\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\USER\Documents\python projects\yerekshe\lib\site-packages\django\urls\resolvers.py", line 398, in check for pattern in self.url_patterns: File "C:\Users\USER\Documents\python projects\yerekshe\lib\site-packages\django\utils\functional.py", line 80, in get res = instance.dict[self.name] = self.func(instance) File "C:\Users\USER\Documents\python projects\yerekshe\lib\site-packages\django\urls\resolvers.py", line 588, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf 'yerekshe.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is pro bably caused by a circular import. here is my views.py: from django.shortcuts import …
- 
        What is the meaning of detail argument in Django ViewSet?I create a custom action method in Django ViewSet and I see detail argument. If I set detail=True I can't call this method from URL but if I set detail=False, I can call this method. May I know what is the meaning of detail argument? Here is my method=> @action(methods=['get'], detail=True) def byhello(self, request): return Response({"From Hello":"Got it"})
- 
        why does super function exactly use in my code?My problem is about why exactly was super(CommentManager, self) used in code below. couldn't that instance object in filter_by_instance just be used instead? class CommentManager(Models.Manager): def filter_by_instance(self, instance): content_type = ContentType.objects.get_for_model(instance.__class__) obj_id = instance.id qs = super(CommentManager, self).filter(content_type=content_type, object_id=obj_id).filter(parent=None) return qs Couldn't it be something like this: class CommentManager(Models.Manager): def filter_by_instance(self, instance): content_type = ContentType.objects.get_for_model(instance.__class__) obj_id = instance.id qs = instance.filter(content_type=content_type, object_id=obj_id).filter(parent=None) return qs
- 
        Use some Pandas Functions into my Django AppHi guys I have a problem: I've made my first Django App extensively using pandas in my views.py to load csvs, make some data prep and loading my pickle ML model. The problem is that all this was working fine until I tested on the deployed app (using nginx and uwsgi) where I got an error No Module named pandas which, researching seems to be a very common issue due to the fact that Django doesn't allow importing pandas directly. I saw some Django-pandas frameworks but their documentation is quite cryptic to me. Can you explain me in a simple way How can I execute those functions in pandas using Django (even with the help of a Django-pandas framework): pandas.read_csv() DataFrame.loc[...] DataFrame.sort_values() Series.unique() Series.size Series.iloc[0] DataFrame.from_dict(...) # would pickle function be affected? model = pickle.load(open(...)) model.predict() To make a better example: import pandas as pd df = pd.read_csv('...') df = df.loc[df['...'] == '...'] serie = df['...'].sort_values() serie = pd.Series(serie.unique()) serie.size value1 = int(serie.iloc[0]) df = pd.DataFrame.from_dict(dictionary) model = pickle.load(open(...)) # I don't know if pickle would give problems as well as pandas prediction = model.predict(df)
- 
        Django template check value with URL parameterI'm trying to create a select in html to list all month and the default value of the select should be equal to the month parameter from the URL My URL : /list-working-session/?month=7&year=2019 month and year are the parameter in My HTML: <select name="month" class="form-control" id="month" required> {% for i in months %} {% if i == request.GET.month %} <option value="{{ i }}" selected="selected">{{ i }}</option> {% else %} <option value="{{ i }}">{{ i }}</option> {% endif %} {% endfor %} </select> months is the context from the view with range(1,13) and i managed to list from 1 to 12 in select option but i can't get the IF condition to work so the default select value equal to the month in the URL. Any help would be appreciate
- 
        Can I call location.reload() from HttpResponseRedirect?Is it possible to call location.reload() when using HttpResponseRedirect using Django? I have a function that changes the state of an item when a button is clicked. Often the user scrolls down to click this button. The button is hooked up to the view change_state: def change_state(request, item_title, new_state): modify_state(item_title, new_state) return HttpResponseRedirect(reverse('slug-of-prev-page')) When I redirect to slug-of-prev-page the entire page will reload, snapping the page to the top. I know using something that manipulates the DOM, like React.js, would be better for this type of thing. But I'm looking for a quick solution. Or is my best bet to hook up a call to change_state, POST the data, and then call location.reload()?
- 
        How to create another superuser in django?I have a user created in django and I want to create another user but when I try to create it gives me error. djongo.sql2mongo.SQLDecodeError: FAILED SQL: INSERT INTO "auth_user" ("password", "last_login", "is_superuser", "username", "first_name", "last_name", "email", "is_staff", "is_active", "date_joined") VALUES (%(0)s, %(1)s, %(2)s, %(3)s, %(4)s, %(5)s, %(6)s, %(7)s, %(8)s, %(9)s) Params: ['pbkdf2_sha256$150000$MqcpwdeHoQyA$yXEd56NQb5QfWNwwjZOIS0OJmzVpUizpRsTWoHNPgEw=', None, True, 'bilalkhan', '', '', '', True, True, datetime.datetime(2019, 7, 30, 8, 30, 16, 156047)] Pymongo error: {'writeErrors': [{'index': 0, 'code': 11000, 'errmsg': 'E11000 duplicate key error collection: firstapp_db.auth_user index: auth_user_email_1c89df09_uniq dup key: { : "" }', 'op': {'id': 49, 'password': 'pbkdf2_sha256$150000$MqcpwdeHoQyA$yXEd56NQb5QfWNwwjZOIS0OJmzVpUizpRsTWoHNPgEw=', 'last_login': None, 'is_superuser': True, 'username': 'bilalkhan', 'first_name': '', 'last_name': '', 'email': '', 'is_staff': True, 'is_active': True, 'date_joined': datetime.datetime(2019, 7, 30, 8, 30, 16, 156047), '_id': ObjectId('5d4000187b6675a2aa5457b5')}}], 'writeConcernErrors': [], 'nInserted': 0, 'nUpserted': 0, 'nMatched': 0, 'nModified': 0, 'nRemoved': 0, 'upserted': []} Version: 1.2.33
- 
        Why validate_<field> triggered 3 times? Django Rest FrameworkI have following cutsom base Serializer: class CustombBaseSerializer(Serializer): def get_object(self, model, **kwargs): try: return model.objects.get(**kwargs) except model.DoesNotExist: raise ValidationError( f"{model._meta.verbose_name.title()} Does Not Exist." ) and following serializer inherited from CutsomBaseSerializer (above): class TextAnswerSerializer(CustombBaseSerializer): sheet_code = CharField( max_length=11, ) def validate_sheet_code(self, value): return self.get_object(SheetCode, pk=value) def validate(self, attrs): if attrs.get('sheet_code').user_id != attrs.get('user_id'): raise ValidationError("It's not yours!") if attrs.get('sheet_code').kind == 'infinity': # some stuff elif attrs.get('sheet_code').kind == 'feedback': # some more stuff else: # some other stuff return attrs when I send data to this serializer, it raises an exception: myapp.models.SheetCode.MultipleObjectsReturned: get() returned more than one SheetCode -- it returned 3! I find that, the validate_sheet_code triggered 3 times. what's the problem? and how to fix it?