Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
connection.queries returns me nothing django
from django.db import connection, reset_queries Prints: [] reset_queries() p = XModel.objects.filter(id=id) \ .values('name') \ .annotate(quantity=Count('p_id'))\ .order_by('-quantity') \ .distinct()[:int(count)] print(connection.queries) While this prints: reset_queries() tc = ZModel.objects\ .filter(id=id, stock__gt=0) \ .aggregate(Sum('price')) print(connection.queries) I was trying to print MySQL queries that Django makes and came across connection.queries, I was wondering why doesn't it prints empty with first, while with second it works fine. Although I am getting the result I expect it to. Probably the query is executed. Also am executing only one at a time. -
Django redirect not working wiht registration
ValueError at / The view landing.views.base didn't return an HttpResponse object. It returned None instead. Request Method: POST Request URL: http://127.0.0.1:8000/?ex=tset1&adalt=1 Django Version: 2.0.7 Exception Type: ValueError Exception Value: The view landing.views.base didn't return an HttpResponse object. It returned None instead. Exception Location: /var/www/venv/lib/python3.5/site-packages/django/core/handlers/base.py in _get_response, line 139 Python Executable: /var/www/venv/bin/python Python Version: 3.5.2 This is err with django 2.0.7 Anybody have idia? -
Django REstful how to use two serializers in one router
Can anyone explain to me how i can use two serializer in one router? I thinking about run http://127.0.0.1:8000/stats/ and use top10Serializer and when i change url to http://127.0.0.1:8000/stats/autor_object to run AutorSerializer. I must change view to APIView ? Models.py class Top10(models.Model): T10_word=models.CharField(name='T10Word',max_length=255) T10_word_count=models.IntegerField(name="T10Count") def __str__(self): return self.T10Word + ":" + str(self.T10Count) class Stats(models.Model): # Fields Word = models.CharField(name='Word',max_length=255) Word_count = models.IntegerField(name="Count") def __str__(self): return self.Word+":"+str(self.Count) class Autor(models.Model): # Fields name = models.CharField(max_length=255) content=models.TextField(max_length=None) sub_name = models.CharField(name='Subname', max_length=255, default='puste',unique=True) # Relationship Fields words = models.ManyToManyField(Stats) def __str__(self): return self.name Serializers.py class StatsSerializer(serializers.ModelSerializer): class Meta: model=Stats fields=('Word','Count') class top10Serializer(serializers.ModelSerializer): class Meta: model=Top10 fields=('T10Word','T10Count') class AutorSerializer(serializers.ModelSerializer): words=StatsSerializer(read_only=True,many=True) top10=top10Serializer(read_only=True,many=True) class Meta: model=Autor fields=('name','words') urls.py router=routers.DefaultRouter() router.register('autors',views.AutorView) router.register('stats',views.Top10View) views.py class AutorView(viewsets.ModelViewSet): queryset = Autor.objects.all() serializer_class = AutorSerializer lookup_field = "Subname" class StatsView(viewsets.ModelViewSet): serializer_class = StatsSerializer queryset = Stats.objects.all() def get_queryset(self): qs = super(StatsView, self).get_queryset() qs = qs.all().order_by("-Count")[::1][:10] return qs class Top10View(viewsets.ModelViewSet): queryset = Top10.objects.all() serializer_class = top10Serializer def get_queryset(self): qs2 = super(Top10View, self).get_queryset() qs2 = qs2.all().order_by("-T10Count")[::1][:10] return qs2 -
use redis and mongo alongside postgres in docker
I am learning to use docker in one of my project which has the following tech stack django redis mysql - production sqlite - development mongod I could configure a simple docker which covers django related and mysql but have no idea how to glue redis and mongod as well. I see various ways in internet but based on the configuration i already made how should i fit them well. Here is what I have done docker-compose.yml version: '3' services: db: image: postgres web: build: context: . dockerfile: docker/python/Dockerfile command: bash -c "sleep 3; python /code/manage.py migrate --noinput && python manage.py runserver 0.0.0.0:8000" volumes: - .:/code ports: - "8000:8000" depends_on: - db Dockerfile # python image (https://hub.docker.com/_/python/) FROM python:3.6 # Environment Variables ENV PYTHONBUFFERED 1 ENV PYTHONDONTWRITEBYTECODE 1 COPY ./requirements/requirements.txt /code/requirements.txt RUN pip install -r /code/requirements.txt RUN chmod ug+x /code/initialize.sh COPY . /code/ WORKDIR /code EXPOSE 8000 initialize.sh #!/bin/bash # This script initializes the Django project. It will be executed (from # supervisord) every time the Docker image is run. # If we're not in production, create a temporary dev database if [ "$DJANGO_PRODUCTION" != "true" ]; then echo "DJANGO_PRODUCTION=false; creating local database..." # Wait until the MySQL daemon is … -
Extending django-admin-tools admin template doesn't render header
Trying to add custom page into the admin. I want this page to have the same header and upper menu like any other page in admin from django-admin-tools. Everything seems to be ok except the welcome section. This is how it should look like This is how it looks As you can see there is missing the upper right section. This is my base template: {% extends "admin:admin/app_index.html" %} {% load django_tables2 %} {% block extrastyle %} {{ block.super }} <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/datepicker/0.6.5/datepicker.min.css"> {% endblock %} {% block extrahead %} {{ block.super }} <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/datepicker/0.6.5/datepicker.min.js"></script> <script> $(document).ready(function () { $(".datepicker").datepicker( { format: 'dd.mm.yyyy' } ); }) </script> {% endblock %} {% block content %} {{ block.super }} {% block render_home_table %} <section class="home_table_section"> <button class="copy_table_to_cb">Clipboard</button> {% render_table home_table %} </section> {% endblock %} {% block render_away_table %} <button class="copy_table_to_cb">Clipboard</button> <section class="away_table_section"> {% render_table away_table %} </section> {% endblock %} {% endblock %} How to fix this? Do I have to extend another template? -
django models to model 'has-a' and 'contains' relationships
I have the following entities: from django.db import models class Foo(models.Model): pass class Bar(models.Model): pass class FooBar(models.Model): pwned_foo = # Foobar contains one Foo object bars = # Collection of Bar objects How do I express the relation between Foo, Bar and FooBar in the FooBar class? -
django get object id not correct after del some objects?
data in sqlite when i del some object in sqlite, the data in table like image! def get_permission(request): ls = [] permissions2 = Permission.objects.using("sqlite").all().order_by('id') for p1 in permissions2: print p1.pk, p1.id, p1 ls.append([p1.id, p1.name]) return JsonResponse(ls, safe=False) ...,[36, "Can add tags"], [37, "Can change tags"], [38, "Can delete tags"], [39, "Can add task log"], [40, "Can change task log"], [41, "Can delete task log"],.... but the object.id is the index -
I want to start a python file that containing imports from django library in the OS shell
I have a very simple case in which I want to run a script with python myscript.py: from models import Company c = Company(number="1234567890", name="Company name") models.py: from django.db import models class Company(models.Model): number = models.CharField("company number", max_length=20, unique=True) name = models.CharField("company name", max_length=30, unique=True) class Meta: verbose_name = "Company" verbose_name_plural = "Companies" I want to run python myscript.py or something like python manage.py execute_file myscript.py I know my question is trivial and I can import a python manage.py shell environment, but that's not the point. Can I run it in a much simple manner? -
Python Graphql Django Server Mutation info.context.files return empty list without file
on my front-end the file is being send to the server when i tried to access **kwargs dictionary i can see the of the file being received in the server but when i tried to access the file by info.context.FILES its sending an empty list which does have any file my code are here: class CreateAgency(graphene.Mutation): id = graphene.UUID() authorName = graphene.String() authorEmail = graphene.String() authorPhone = graphene.Int() agencyName = graphene.String() agencyAddress = graphene.String() thefile = Upload() #graphene.String() agencyLandlineNumber = graphene.Int() agencyEmail = graphene.String() agencyWebsite = graphene.String() userId = graphene.UUID() class Arguments: authorName = graphene.String() authorEmail = graphene.String() authorPhone = graphene.Int() agencyName = graphene.String() agencyAddress = graphene.String() thefile = Upload() #graphene.String() agencyLandlineNumber = graphene.Int() agencyEmail = graphene.String() agencyWebsite = graphene.String() userId = graphene.UUID() #@classmethod @staticmethod def mutate(self, info, **kwargs): #self, file, info, **kwargs authorName = kwargs.get('authorName') authorEmail = kwargs.get('authorEmail') authorPhone = kwargs.get('authorPhone') agencyName = kwargs.get('agencyName') agencyAddress = kwargs.get('agencyAddress') thisfinal = kwargs.get('thefile') #file string #files = info.context.FILES.get(file) #files = kwargs.context.FILES['thefile'] agencyLandlineNumber = kwargs.get('agencyLandlineNumber') agencyEmail = kwargs.get('agencyEmail') agencyWebsite = kwargs.get('agencyWebsite') userId = kwargs.get('userId') print(type(thisfinal)) #print(info.context.FILES['thefile']) #print(info.context.FILES) print(kwargs) #print(context) print(info.context.FILES.getlist('thefile')) print(info.context.FILES) if info.context.FILES and info.context.method == 'POST': getFile = info.context.FILES['thefile'] print("#######################") print(info.context.FILES) print(kwargs) print(self) #print(context) print(getFile) print("#######################") #print(files) #print(thisfinal) print("#######################") print(agencyName) print("#######################") actionCreate … -
Django: prefetch_related has no effect
I'm trying to optimize a DB query using prefetch_related without success. models.py class Order(models.Model): # some fields ... @property def last_operation(self) -> Optional['OrderOperation']: try: return self.orderoperation_set.latest() except OrderOperation.DoesNotExist: return None @property def total(self) -> Optional[Decimal]: last_operation = self.last_operation return last_operation.total if last_operation else None class OrderOperation(TimeStampable, models.Model): order = models.ForeignKey(Order) total = DecimalField(max_digits=9, decimal_places=2) Running a shell, I can see the problem: orders = Order.objects.prefetch_related('orderoperation_set') # There are 1000 orders result = sum([order.total for order in orders]) len(connection.queries) >>> 1003 As we can see, there is one query per order.total, so 1000 queries, that makes the whole request very bad, with performance linear to the number of orders. Trying to understand why this is happening, I found this in the prefetch_related Django doc: Remember that, as always with QuerySets, any subsequent chained methods which imply a different database query will ignore previously cached results, and retrieve data using a fresh database query. So, it seems normal that calling latest() each time run a new query. How would you do to improve performance in this case? (making a few queries instead of N, with N is the number of orders). -
Form sends <textarea> tag along with the body
I'd like to submit this form as a Django template: <form action="/feedback" method="post"> {% csrf_token %} <div class="form-group"> {% if form.title.errors %} <div class="alert alert-danger" role="alert"> {{ form.title.errors }}</div> {% endif %} <div class="row"> <div class="col-xs-6 col-xs-push-6"> <div class="form-group"> <input id="id_title" class="form-control" name="title" value="{{title}}" > </div> </div> </div> </div> {% if form.body.errors %} <div class="alert alert-danger" role="alert">{{ form.body.errors }}</div> {% endif %} <div class="form-group"> <textarea class="form-control" id="id_body" name="body" rows="20">{{body}}</textarea> </div> <button type="submit" value="Submit" id="send"> Send</button> </div> </form> The problem is that the received form body contains <textarea> tag like this: <textarea cols="40" id="id_body" name="body" rows="10"> Your site is good!</textarea> But I want it to be: Your site is good! I had tried different tricks like changing textarea class but could not fix it. So appreciate your help. -
Django - Modify field value after every query
I am fairly new to Django coming from Laravel background. I would like to modify a field value everytime I query it. For example, every time you query firstname@User you return the Capitalized firstname. In Laravel this is known as Accessors but apparantely Accessors have different meaning in Django. For my case, I have a key-value table called Meta where the value field can be of any type: class Meta(models.Model): key = models.CharField(max_length=30) value = models.TextField() model = models.ForeignKey('Model', on_delete=models.CASCADE) and upon getting the value Meta.objects.get(key='foo'), I would like to return ast.literal_eval(value) to convert the string expression to the correct respective type. I did some research and only found the following: Create a custom Field. Use get_foo_display(self) but this only works for ChoiceField as far as I understood. What is the best choice to apply this function for everytime I query value filtering by the key -
Django Queryset with LIMIT depending on Queryset conditions/filters
I have a model Item and a constant MAX_NR.: class Item(models.Model): is_featured = models.BooleanField() is_active = models.BooleanField() With a queryset I want to get: all the Items that have is_active=True and is_featured=True, if their number is more than MAX_NR the Items that have is_active=True, is_featured=True and additional other Items that have is_active=True until the MAX_NR of records, if the number of is_featured=True is less than MAX_NR, orderd by is_featured=True Can this be done in one Queryset ? -
django - best way for transfer money to users bank account
I am developing a django based application and want to transfer money to users bank account according to their earned points. At the end of week I have a payback amount that should be send to users. How to deposit that amount to their bank account automatically at end of week. Should I make transitions manually or there is any secure way to ? Is it possible to transfer money from my bank account to another with script ? If not then how big companies like - adsense, facebook, amazon transfer credits ??? -
Django ORM - Savings with **kwargs and retrieving instance
Currently saving to my Product model like so: Product(**kwargs).save() How can I retrieve the instance immediately without performing a query similar to below? Product.objects.get(unique_val = kwargs['unique_val']) Thanks EDIT: I'm trying to avoid hitting the database a much as possible. -
Where to use Java Backend and where Python would win?
This question probably has an answer here. But, all the answers are almost a decade old. I want to know about the current scenario in 2018 where we have hell lotta options like NodeJS, Ruby and PHP. I understand well where to use Node and where should I switch to Java backend (not really sure about Ruby and PHP though) but here, I am more concerned with Java vs Python for backend dev. Which one to go and when? Also, I want a deep intricate answer based on some technical reasons behind and not something like Go with Python if you want to go fast and Java if you want to go far. -
Google maps : show Place details of marker on google map
I have a django project using geocomplete The javascript file is this (jquery.geocomplete.js) : /** * jQuery Geocoding and Places Autocomplete Plugin - V 1.7.0 * * @author Martin Kleppe <kleppe@ubilabs.net>, 2016 * @author Ubilabs http://ubilabs.net, 2016 * @license MIT License <http://www.opensource.org/licenses/mit-license.php> */ // # $.geocomplete() // ## jQuery Geocoding and Places Autocomplete Plugin // // * https://github.com/ubilabs/geocomplete/ // * by Martin Kleppe <kleppe@ubilabs.net> (function($, window, document, undefined){ // ## Options // The default options for this plugin. // // * `map` - Might be a selector, an jQuery object or a DOM element. Default is `false` which shows no map. // * `details` - The container that should be populated with data. Defaults to `false` which ignores the setting. // * 'detailsScope' - Allows you to scope the 'details' container and have multiple geocomplete fields on one page. Must be a parent of the input. Default is 'null' // * `location` - Location to initialize the map on. Might be an address `string` or an `array` with [latitude, longitude] or a `google.maps.LatLng`object. Default is `false` which shows a blank map. // * `bounds` - Whether to snap geocode search to map bounds. Default: `true` if false search globally. Alternatively … -
Overwriting a border on an image in Python PIL
I have a gallery application where the users upload photos and my code gives it a border, writes some of the photo attributes on the border and stores it. image2 = Image.open('media/' + str(image.file)) width, height = image2.size; image2 = ImageOps.expand(image2, border=(int(width/25),int(height/20),int(width/25),int(height/10)), fill='rgb(0,0,0)') (Note that here my bottom border is longer than the top because I am writing attributes on the bottom border.) Now I'm building an edit feature for the uploaded images where the user can change the attributes of the uploaded images. But the attributes that are already written on the border have to be overwritten. So here, my approach is to put a black patch on the bottom border and re-write the new attributes without changes the top and side borders and without changing the aspect ratio. All of this has to be done using PIL. Question is how do I put a black box on the bottom border? I tried ImageOps.fit() as mentioned here https://pillow.readthedocs.io/en/3.3.x/reference/ImageOps.html#PIL.ImageOps.fit, but the aspect ratio doesn't seem to be right and I want to overwrite on the black border a black box and not crop the photo. -
We need help how to filter two table fields within one URL using django rest framework
How do I achieve the following... Here, I have two models example1 and example2 in that I joined two table using serializers now I want to filter using fields (patient_n_key,centre_master_short_name) either in example2 serializer or example2 viewset models.py class Example1(models.Model): patient_id = models.AutoField(primary_key=True) patient_n_key = models.CharField(max_length=15, blank=True, unique=True) centre_master_short_name = models.CharField(blank=False, max_length=33) class Meta: managed = False ordering = ['patient_id'] db_table = 'example1' class Example2(models.Model): appointment_id = models.AutoField(primary_key=True) appointment_n_key = models.CharField(max_length=15, blank=True) patient_n_key = models.ForeignKey('PatientMasters', db_column='patient_n_key', to_field='patient_n_key', on_delete=models.CASCADE, related_name="Example2_id") centre_master_short_name = models.CharField(blank=False, max_length=33) class Meta: managed = False ordering = ['appointment_id'] db_table = 'example2' serializers1.py class Example1serializer(serializers.ModelSerializer): class Meta: model=models.Example1 fields='__all__' class Example2Serializer(serializers.ModelSerializer): patient_n_key = Example1serializer(read_only=True) class Meta: model=models.Example2 fields='__all__' views.py class Example1viewset(viewsets.ModelViewSet): queryset=models.Example1.objects.all() serializer_class=serializers1.Example1serializer lookup_field = 'patient_n_key' class Example2viewset(viewsets.ModelViewSet): queryset=models.Example2.objects.all() serializer_class=serializers1.Example2serializer lookup_field = 'appointment_n_key' urls.py router.register(r'example1', views.Example1viewset, base_name='example1') router.register(r'example2', views.Example2viewset, base_name='example2') -
Dictinct Row in queryset using Django Rest Framework
I want to remove the duplicate row, distinct row in a Mysql DB. "Prpk" has a relation with "MeteoZone" (meteozone). I've a model like this : class MeteoZone(models.Model): name = models.CharField(max_length=45, unique=True) communes = models.ManyToManyField(Commune, related_name='meteozone', blank=True) massifs = models.ManyToManyField(Massif, related_name='meteozone', blank=True) def __str__(self): return self.name class Prpk(models.Model): begin = models.FloatField() end = models.FloatField() status = models.CharField(max_length=15) # Relations report = models.ForeignKey(Report, on_delete=models.PROTECT, unique=False) meteozone = models.OneToOneField(MeteoZone, related_name='prpk', on_delete=models.PROTECT, null=False, unique=False) highway = models.OneToOneField(Highway,related_name='prpk', on_delete=models.PROTECT, null=True, unique=False) department = models.OneToOneField(Department,on_delete=models.PROTECT, null=True, unique=False) def __str__(self): return ("%s-%s" % (self.begin,self.end)) And a serializer : class PrpkSerializer(serializers.ModelSerializer): # Get 'meteozones', 'communes' and 'massifs' meteozone = MeteozoneSerializer(read_only=True) begin = serializers.FloatField() end = serializers.FloatField() status = serializers.CharField(max_length=15) class Meta: model = Prpk fields = ('begin', 'end', 'status', 'meteozone') ordering = ('begin', ) In my view, in the query_set, I want to display only the unique records. Look at a part of records : id begin end status commune_id department_id highway_id massif_id meteozone_id report_id 76 25 25.6 1 NULL 13 2 45 40 1 77 25 25.6 1 NULL 13 2 161 40 1 In this records, I just one only one record in json, but DRF returns 2 records, like this : [ { "begin": … -
Django query returning multiple users instead of one
On my dashboard I'm querying a profile model that has a one to one relationship with user model. But instead of getting one user since there is only one profile per user, I'm getting all users in the database and one profile. I could probably work around the issue but from a security perspective I'm concerned about somehow getting all users from database. I checked the database fields and everything is OK so problem is with the code. Here's the code: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) firstname = models.CharField(max_length=100, blank=True) lastname = models.CharField(max_length=100, blank=True) city = models.CharField(max_length=100, blank=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() Here's the code for form: class ProfileForm(forms.ModelForm): class Meta: model = Profile exclude = ['afield', 'anotherfield'] labels = { 'user': _('User Name'), 'firstname': _('First Name'), 'lastname': _('Last Name'), 'city': _('City'), Here's the view: @login_required def buy_subscription(request): if request.user.is_authenticated: if request.method == "POST": form = ProfileForm(request.POST, instance=request.user.profile) if form.is_valid(): form.save() else: form = ProfileForm(instance=request.user.profile) return render(request, 'dashboard/mypage.html', {'form': form}) else: return redirect("login/") Template is standard: {% for field in form %} {% render_field field class="form-control" %} {% endfor %} -
How to let user save or edit his profile info in Django manually without using Django forms
i am working on a bootstrap template. but heaving problem with saving profile info in database. here is my code. i don't know if i am doing it right. but it,s not working . models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) Propic = models.ImageField(upload_to="Banners/", null=True,blank=True) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) views.py def profile(request): ids = request.user.id user = User.objects.get(pk=ids) if request.method == "POST": bio = request.POST["bio"] location = request.POST["location"] image = request.FILES['pic'] form = user.profile(bio = bio , location = location , propic=image) form.save() return HttpResponse("info saved") return render(request, "dashbord/user.html", {"user": user }) -
How do I retrieve data from two tables in Django using postgresql
In my views.py this is my code: def search(request): qset = Q() query = request.GET.get('q', '') queryC = request.GET.get('clients', '') queryD = request.GET.get('documents', '') queryT = request.GET.get('topics', '') if query: newquery = stopwords.strip_stopwords(query) terms = newquery.split() if queryT != 'empty': for term in terms: qset |= ( Q(Topic_id__Name__icontains=queryT) & Q(Question_id__Statement__icontains=term) ) results = set(Response.objects.filter(qset).distinct()) else: for term in terms: qset &= ( Q(Question_id__Statement__icontains=term) ) results = set(Response.objects.filter(qset).distinct()) else: results = [] return render_to_response("app/search.html", { "results": results, "query": query }) It returns the responses that is closely related to the query from user input. But I also want it to return the question that is linked to the response. My response table has a foreign key to the question table linked by Questions_id. I've read I might have to use select_related() but not sure how to. -
Django Querysets - optimize their number when working with multiple conditions
I have 2 Models, Parent and Child. class Parent(models.Model): has_featured = models.BooleanField() is_active = models.BooleanField(c) class Child(models.Model): parent = models.ForeignKey(Parent,on_delete=models.CASCADE) is_featured = models.BooleanField() is_active = models.BooleanField() Rules: 1) For the Parent/child to be shown is_active should be true 2) The Child can be shown only if both is_active on the Parent and is_active on child is True 3) has_featured, is_featured determines if they appear in special positions 4) A Child can appear in a featured spot, if Account has_featured is True and Child is_featured is True I have a featured slide, were I need to show a minimum number of child Elements, which by default should have is_featured True Because I need to show a minimum number I have the following problematic situations: 1) There is no has_featured=True Parent. I can show any Child with the limit MAX_NR corresponding to Account is_active=True indifferent of is_featured value. Children needs to be active. 2) There are has_featured=True Parent, also Child is_featured=True, but the number of Children is bellow the MIN_NR In this case the list of Children needs to be completed until MAX_NR with Children corresponding to Account is_active=True indifferent of Child is_featured value. 3) There are has_featured=True Parent, but there are … -
lookup field should not required while update but required while create
I am using model viewset in django rest framework. where lookup field is company class UserViewSet(viewsets.ModelViewSet): """ A viewset for viewing and editing user instances. """ serializer_class = UserSerializer queryset = User.objects.all() lookup_field = 'company' Company is required when create user. POST method - /localhost/user/ but when i trying to update PUT method - /localhost/user/1/ here 1 is company_id it is raising error { "company": [ "This field is required." ] } serializers.py class UserSerializer(DynamicFieldsModelSerializer): class Meta: model = User fields = "__all__" If i make company allow_null =True then it will also not required for create metod. How can i make company required for create. and not required for update