Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to filter a model Django and compare against an id
I'm trying to filter a model called "CartItem" , that has a field called item , I want to check whether a product id is in this field. each cartitem instance is connected to a cart.id. The product id is taken from a form in templates. I currently have " {% if cartitem.objects.filter(item_id=product_id).exists %} " in the template, I also tried making an items list in the views.py , to try to use the "if in" statement in the template, based off the "items" contents. at the moment I get an error: TemplateSyntaxError Exception Value: Could not parse the remainder: '(item.id=product.id).exists' from 'cartitem.objects.filter(item.id=product.id).exists' Thanks models.py class CartItem(models.Model): item = models.ForeignKey(Product, blank=True, on_delete=models.CASCADE, null=True) items_cart = models.ForeignKey('Cart', blank=True, on_delete=models.CASCADE, null=True) quantity = models.IntegerField(null=True, blank=True) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return 'item:{} cart:{} quantity:{}'.format(self.item, self.items_cart, self.quantity) views.py def cart_update(request): product_id = request.POST.get('product_id') cart_obj, new_obj = Cart.objects.new_or_get(request) cart_items = CartItem.objects.filter(items_cart_id=cart_obj) items = [] for item in cart_items: items.append(item.item.id) print(items) if product_id is not None: try: product_obj = Product.objects.get(id=product_id) except Product.DoesNotExist: print("Show message to user, product is gone?") return redirect("cart:home") cart_obj, new_obj = Cart.objects.new_or_get(request) cart_items = CartItem.objects.filter(items_cart_id=cart_obj) if product_obj in cart_items: cart_items.delete(product_obj) added = False else: newitem = CartItem(item=product_obj, items_cart=cart_obj, quantity=1) … -
Required field of html is not working with django template syntax
Required field html validation not working with django its not asking to select from the list do anyone knows how to solve it only its working when I remove the django template syntax <select name="assignee" required id="assignee" class="form-control"> {% for user in b %} <option>{{user.firstname}} {{user.lastname}}</option> {% endfor %} </select> -
Django - updating m2m field value after save
The problem is, that after saving a model instance with new m2m_field value, I want to automatically add some more related objects to it. class MyModel(models.Model): m2m_field = models.ManyToManyField("app.RelatedModel") @receiver(models.signals.m2m_changed, sender=MyModel.m2m_field.through) def m2m_field_changed(sender, instance, **kwargs): instance.m2m_field.add(related_object_instance) That obviously results in an infinite loop, because after adding the instance to the m2m_field, the receiver is fired again and so on. Is there a proper way to do it? Thanks for any help. -
Make a choices list for forms.py after receiving data from views.py in django
So this is the scenario. I allow my user to first input their vehicle brand with one form and then use another form to list down the models available for that vehicle brand. The information on the vehicles and the brands is stored in my database. Refer to this image to get a better idea... And this is my views.py...(INCOMPLETE FOR NOW) def driver_dashboard_trip_brand (request, brand): if request.method == "POST": form = AddVehicleForm(request.POST) else: form = AddVehicleForm() brands = VehicleBrand.objects.all() context = { "form":form, "brands":brands, "chosen_brand":brand } return render (request, "app/driver_dashboard.html", context) And my forms.py... class AddVehicleForm(forms.ModelForm): model = forms.ChoiceField() vehicle_colour = forms.ChoiceField(choices=COLOURS) vehicle_number = forms.CharField(max_length=8, widget=forms.TextInput(attrs={'placeholder': 'eg: CAB-1234'})) class Meta: model = Vehicle fields = ['model', 'vehicle_colour', 'vehicle_number'] So in order to set a query in the forms.py, I would first need to send the data from views.py to forms.py and THEN I also need to do a query. So my question is how can I query for all the car models from the VehicleModel database and create choices attribute for the form, once the user chooses the car brand. Any help would be greatly appreciated and I would definitely upvote your answer and all comments if I am … -
Create multiple tables in a single database in django
I created an app in Django and made migrations and migrated to my database "emp". Then I created another project with an app and I created a table in the same database emp and made migrations. Migrations were made but when I migrated it showed "No changes detected" and the table was also not created. When I did the same process in a different database it worked. I wanted to know that how can I create multiple tables in a single database Please Help!! -
Django Custom Form
so I'm trying to create a comment form, but I cannot make the form appear in the way I want. Let me explain: I want this: Using this code: <div class="ui action input"> <input type="text" placeholder="Search..."> <button class="ui icon button"> <i class="search icon"></i> </button> </div> And the form that I have to show the form I created in forms.py is: <form action="" method="POST"> <!-- NOVO COMMENT --> {% csrf_token %} <input type="hidden" name="post_id" value={{post.id}}> {{ c_form }} <button type="submit" name="submit_c_form" class="ui primary button mt-10 w-full"><i class="paper plane outline icon"></i>Send</button> </form> Which comes out like this: Here is my forms.py where I create the comment form: Thank you anyone out there that can help me :) -
How can I filter a Django_Table that display records from a Dict instead of a model
I would like to know if there is a way to filter on field in a Django table that is created with a dictionary instead of with a Model. I have a Model that has 2 properties: #models.py class DeviceConfiguration(Model): device = models.OneToOneField(Device, on_delete=models.CASCADE) config = models.JSONField() In that JSON lives some structured data that needs to be proccessed before i can present it in a table (It contains a dict with lists with dicts that needs to converted to a list of dicts). I have the following table that uses an Accessor to traverse my custom JSON: #tables.py class RawConfigTable(tables.Table): hostname = tables.Column(accessor=A('system__hostname')) version = tables.Column(accessor=A('system__version')) interface = tables.Column(accessor=A('interfaces__name')) status = tables.Column(accessor=A('interfaces__protocol')) speed = tables.Column(accessor=A('interfaces__speed')) class Meta: attrs = {'class': 'table table-condensed table-vertical-center', 'id': 'dashboard_table'} fields = ('hostname', 'version', 'interface', 'status', 'speed') sequence = fields order_by = ('hostname', ) In the views.py the table gets instanciated with the proccessed JSON as per documentation: #views.py class RawInterfaceList(View): """Displays all the interfaces from all devices in table form""" def get(self, request): all_configs = [] for device in Device.objects.all(): config = device.deviceconfiguration.config input = { 'system': config['system'], 'interfaces': config['interfaces'] } all_configs.append(proccess(input)) # This is the custom proccessing i was talking about table … -
I am not able to upload images for my E commerce application. I am getting following errors. Can anyone review my error?
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/img/uploads/products_img/jet-black-half-sleeve-t-shirt-men-s-plain-t-shirts-106-1560838106.jpg Using the URLconf defined in Eshop.urls, Django tried these URL patterns, in this order: admin/ ^static/(?P.*)$ The current path, img/uploads/products_img/jet-black-half-sleeve-t-shirt-men-s-plain-t-shirts-106-1560838106.jpg, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. -
relation "account_account_groups" does not exist LINE 1: ... "auth_group"."name" FROM "auth_group" INNER JOIN "account_a
admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin from account.models import Account class AccountAdmin(UserAdmin): list_display = ('email','username','date_joined', 'last_login','is_admin','is_staff') search_fields = ('email','username',) readonly_fields=('id', 'date_joined', 'last_login') filter_horizontal = () list_filter = () fieldsets = () admin.site.register(Account, AccountAdmin) models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.contrib.auth.models import PermissionsMixin class MyAccountManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError('Users must have an email address') if not username: raise ValueError('Users must have a username') user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): user = self.create_user( email=self.normalize_email(email), password=password, username=username, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user def get_profile_image_filepath(self, filename): return 'profile_images/' + str(self.pk) + '/profile_image.png' def get_default_profile_image(): return "chatapp/default.png" class Account(AbstractBaseUser, PermissionsMixin): email = models.EmailField(verbose_name="email",max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField(verbose_name="date joined", auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) profile_image = models.ImageField(max_length=255, upload_to=get_profile_image_filepath, null=True, blank=True, default=get_default_profile_image) hide_email = models.BooleanField(default=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = MyAccountManager() def __str__(self): return self.username def get_profile_image_filename(self): return str(self.profile_image)[str(self.profile_image).index('profile_images/' + str(self.pk) + "/"):] # For checking permissions. to keep it simple all admin have ALL permissons … -
I can't get the field that contains the object from another model when I create a record
models.py: class A(models.Model): name = models.CharField(max_length=120) def save(self, args, **kwargs): super().save(args, **kwargs) print(self.a_name.all()) class A1(models.Model): description = models.CharField(max_length=120) name = models.ForeignKey(A, on_delete=models.CASCADE, related_name="a_name") class Tags(models.Model): name = model.CharField(max_length=120) a1 = models.ForeignKey(A1, on_delete=models.CASCADE, related_name="a1_tags") admin.py: class TagsI(nested_admin.NestedTabularInline): model = Tags extra = 1 class A1I(nested_admin.NestedTabularInline): inlines = [TagsI] model = A1 extra = 1 class AI(nested_admin.NestedTabularInline): inlines = [A1I] model = A extra = 1 I can't get the field that contains the object from another model when I create a record. I get an error self.a_name.all() A' object has no attribute 'a_name'. How do I get this related object when I save the record? -
Django MRO for permission subclasses
I am using Django 3.2 I have a model Foo, and I want users to be able to update/delete objects that they created. To that end, I have written a OwnerPermissionMixin class as follows: /path/to/permissions.py class OwnerPermissionMixin(PermissionRequiredMixin): owner_attribute = 'owner' def has_permission(self) -> bool: """ Require the the user has the relevant global permission and is the owner of this object. :return: Does the user have permission to perform this action? """ return self.request.user.is_superuser or ( super().has_permission() and self.request.user == getattr(self.get_object(), self.owner_attribute) ) /path/to/views.py class FooUpdateView(LoginRequiredMixin, OwnerPermissionMixin, UpdateView): model=Foo class FooDeleteView(LoginRequiredMixin, OwnerPermissionMixin, DeleteView): model=Foo My question is: am I inheriting the base classes in the right order? both Mixins have the same base class AccessMixin - and it seems to make sense (from a philosophical point of view), that LoginPermissions are enforced before Owner permission - but I want to make sure I'm not missing anything obvious. -
Taggit Django - Return View of Posts Based on User Post Tags)
I have recently been playing around Taggit. I have managed to filter my Posts model, based on different Tags by adding the following filter .filter(tags__name__in='categoryone'). Although, would anyone be able to provide me with guidance on how to filter my Posts based on the tags my user has already used within his or her previous posts? So for example, if my user has previously created a Post within the "categoryone" tag, all the posts he or she would see on their Post Feed would be tags relevant to "categoryone" but he or she wouldn't see any posts within "categorytwo" or "categorythree" unless he or she makes a post within either or both of those categories. I was hoping something such as .filter(tags=self.request.user) but this is throwing an Instance error. Any examples would be greatly appreciated! :-) Thanks! -
Django sending Html email template with javascript functions
I am trying to send an HTML Template over email in DJANGO site and for some reason javascript part isn't working . Email is sent sucessfully with an image only a function is not working in email browser. Here's the template code. <html> <script> function validate() { var x = document.forms["form"]["eid"].value; if (x == "E101") { document.getElementById('id1').style.display='block'; return false; } } </script> <body> <h2 style="color:red;">Hello </h2>,<br> <p >Please find the OTP for requested file.<p><span style="width" class="">File Name :{0} </span></p> <p ><span style="width" class="">OTP : {1} </span></p> <div id="id1" style="display:none;"><img src="cid:0" ></div> <form name="form" onsubmit="return validate()" method="post" required> Employee id: <input type="text" name="eid"> <input type="submit" value="Submit"> </form> <p> </body> </html> -
custom result per logged in user in Foreign Key dropdown django admin
I have a model Called Business and it has many BusinessAddress inside. When userA creates Business say - business_a and then when he creates the BusinessAddress business_address_a_1 He could be able to choose the business_a in the dropdown. But when userB creates his business_b and then when creating the BusinessAddress, dropdown form for foreign key Business in Django admin should not show business_a and business_b instead it should only show business_b and if more business created by the userB that too. My model sample is like this class Business(models.Model): title = models.CharField(max_length=200) def __str__(self): # Show title as the identifier return self.title class BusinessAddress(models.Model): business = models.ForeignKey(Business, on_delete=models.DO_NOTHING) address = models.CharField(max_length=200) def __str__(self): return self.business.title I earlier added the changes to only show the business and business address of the particular user using overriding the get_queryset . But Since Django is new to me I couldn't find a way to achieve this. Could someone guide me on this? -
Best Way to Override Bootstrap Colour Variables
I have a Django (Wagtail CMS) project and I am trying to create a functionality that will allow me to change the 8 Bootstrap theme colours, more about that here. In order to override those colours, I need to use Bootstrap via the SCSS source. I'm using django-compressor to compress the static files in HTML and django-libsass as a SASS compiler. This is in my settings file (settings/base.py) COMPRESS_OFFLINE = True LIBSASS_OUTPUT_STYLE = 'compressed' LIBSASS_SOURCEMAPS = True LIBSASS_PRECISION = 6 This is my HTML file (templates/base.html) {% compress css %} <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"> <style type="text/x-scss" media="screen"> $dark: #000000; </style> <link rel="stylesheet" type="text/x-scss" href="{% static 'scss/bootstrap/bootstrap.scss' %}"> {% endcompress %} I am trying to override the "dark" theme colour with #000, this hex will be replaced with a template tag. The above code doesn't seem to work. But, the code below works: {% compress css %} <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"> <style type="text/x-scss" media="screen"> $dark: #000000; @import "engine/static/scss/bootstrap/bootstrap.scss" </style> {% endcompress %} Now the second code snippet of my base.html file works perfectly, but having an @import seems to be very inefficient. I could create a custom SCSS file with my own colour overrides, but … -
docker-compose up gets stuck at .env doesn't exist
I want to insert environmental variables from an .env file into my containerized Django application, so I can use it to securely set Django's settings.py. However on $docker-compose up I receive part of an UserWarning which apparently originates in the django-environ package (and breaks my code): /usr/local/lib/python3.9/site-packages/environ/environ.py:628: UserWarning: /app/djangoDocker/.env doesn't exist - if you're not configuring your environment separately, create one. web | warnings.warn( The warning breaks at that point and (although all the container claim to be running) I can neither stop them from that console (zsh, Ctrl+C) nor can I access the website locally. What am I missing? Really appreciate any useful input. Dockerfile: (located in root) # pull official base image FROM python:3.9.5 # set environment variables, grab via os.environ ENV PYTHONUNBUFFERED 1 ENV PYTHONDONTWRITEBYTECODE 1 # set work directory WORKDIR /app # install dependencies RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt # add entrypoint script COPY ./entrypoint.sh ./app # run entrypoint.sh ENTRYPOINT ["./entrypoint.sh"] # copy project COPY . /app docker-compose.yml (located in root; I've tried either using env_file or environment as in the comments) version: '3' services: web: build: . container_name: web command: gunicorn djangoDocker.wsgi:application --bind 0.0.0.0:8000 volumes: - .:/app … -
Cannot completely terminate celery [windows 10]
I have a problem here that I believed to originate from an unkilled celery worker: nttracker\celery.py from __future__ import absolute_import import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'nttracker.settings') postgres_broker = 'sqla+postgresql://crimsonpython24:_16064Coding4Life@host/nttracker' app = Celery('nttracker', broker='amqp://', backend='rpc://', include=['nttracker.tasks']) app.autodiscover_tasks() app.conf.update( timezone = "Asia/Taipei", result_backend = 'django-db', broker_url = 'redis://127.0.0.1:6379', cache_backend = 'default', beat_schedule = { 'add-every-10-seconds': { 'task': 'nttracker.tasks.add', 'schedule': 10.0, 'args': (16, 16) }, } ) if __name__ == '__main__': app.start() nttracker\tasks.py from __future__ import absolute_import import django django.setup() from celery import Celery from celery.schedules import crontab app = Celery() @app.task def add(x, y): z = x + y print(z) output from celery -A nttracker.celery worker --pool=solo -------------- celery@LAPTOP-A0OM125L v5.0.5 (singularity) --- ***** ----- -- ******* ---- Windows-10-10.0.19041-SP0 2021-06-04 23:02:25 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: nttracker:0x1a520896400 - ** ---------- .> transport: redis://127.0.0.1:6379// - ** ---------- .> results: - *** --- * --- .> concurrency: 12 (solo) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [2021-06-04 23:02:26,607: WARNING/MainProcess] c:\users\xxx\onedrive\desktop\github_new\nttracker\venv\lib\site-packages\celery\fixups\django.py:203: UserWarning: Using settings.DEBUG leads to a memory leak, never use this setting in production environments! warnings.warn('''Using settings.DEBUG … -
matching query does not exist in database
whenever I try to get my list of items in query I am getting this error from django.db import models Create your models here. class ToDo(models.Model): name = models.CharField(max_length = 200) def __str__(self): return self.name class Item(models.Model): todolist = models.ForeignKey(ToDo, on_delete = models.CASCADE) text = models.CharField(max_length = 300) complete = models.BooleanField() def __str__(self, text = text): return self.text that line i am executing in my pycharm terminal In [3]: lt = ToDo.objects.get(id = 1) --------------------------------------------------------------------------- DoesNotExist Traceback (most recent call last) <ipython-input-3-23a0e6ec0ffa> in <module> ----> 1 lt = ToDo.objects.get(id = 1) ~\anaconda3\lib\site-packages\django\db\models\manager.py in manager_method(self, *args, **kwargs) 83 def create_method(name, method): 84 def manager_method(self, *args, **kwargs): ---> 85 return getattr(self.get_queryset(), name)(*args, **kwargs) 86 manager_method.__name__ = method.__name__ 87 manager_method.__doc__ = method.__doc__ ~\anaconda3\lib\site-packages\django\db\models\query.py in get(self, *args, **kwargs) 433 return clone._result_cache[0] 434 if not num: --> 435 raise self.model.DoesNotExist( 436 "%s matching query does not exist." % 437 self.model._meta.object_name DoesNotExist: ToDo matching query does not exist. -
social_auth_app_django pipeline: first time visitor issue
I'm trying to implement social auth with google-oauth2. I almost implemented it, but I'm confused about first-time social visitor scenario: Suppose the social user visited my site for the first time and attempted to authenticate with using Google. In this case he won't be logged in, but only registered on my website. In order to log in this user has to click on authentication with Google button the second time, and when he already registered on my system the logging in will be successful. Questions: Is it a standard routine for the first time visitors? Is it possible to log the social user on the first attempt? I'm using the following social auth pipeline: SOCIAL_AUTH_PIPELINE = ( # Get the information we can about the user and return it in a simple # format to create the user instance later. In some cases the details are # already part of the auth response from the provider, but sometimes this # could hit a provider API. 'social_core.pipeline.social_auth.social_details', # Get the social uid from whichever service we're authing thru. The uid is # the unique identifier of the given user in the provider. 'social_core.pipeline.social_auth.social_uid', # Verifies that the current auth process is … -
i didn't use django auth to login, but i want to use django sessions
I need help and I don't have so much time left, so basically I'm making an app for my end studies project, this app requires login, of course, and I didn't pass the Django auth which already provided by Django, but now instead of getting back and changing the code which I don't have much time to do so, I'll looking for sessions solution, I didn't how to implement it, can someone help me please, if you need more details just tell me, I'll provide you with everything. Thanks. -
Check if a user is in a group before posting. How to select all available groups in my function?
I am new in Django and my first project was buildidng a simple social clone. My site allows people to post something in different groups, but I want to check if a user is already in that group before posting. I think that the main problem I don't know how to select all the groups in order to verify my condition. models.py from django.contrib.auth import get_user_model User = get_user_model() class Post(models.Model): user = models.ForeignKey(User,related_name='posts',on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=True) message = models.TextField() message_html = models.TextField(editable=False) group = models.ForeignKey(Group,related_name='posts',null=True,blank=True,on_delete=models.CASCADE) views.py from django.contrib.auth import get_user_model User = get_user_model() from django import template register = template.Library() @register.filter def has_group(user, group): return user.groups.filter(name=group).exists() ##### ..... #### class CreatePost(LoginRequiredMixin,SelectRelatedMixin,generic.CreateView): fields = ('message','group') model = models.Post def form_valid(self, form): if has_group(self.request.user, ""): self.object = form.save(commit=False) self.object.user = self.request.user self.object.save() return super().form_valid(form) else: messages.error(self.request, 'Join the group first') return HttpResponseRedirect(reverse('groups:all')) I was trying to resolve this, but I was unsuccessful. Thank you. -
Github actions django rest unit testing ValueError: Port could not be cast to integer value as 'None'
I have a Django and Django REST app, and when I run my unit testing locally, every runs and passes. However, when I create a GitHub Action to run my unit testing, some of my unit tests failure with the following message: File "/opt/hostedtoolcache/Python/3.9.5/x64/lib/python3.9/urllib/parse.py", line 178, in port raise ValueError(message) from None ValueError: Port could not be cast to integer value as 'None' Here is my Action: django-test-lint: runs-on: ubuntu-latest services: postgres: image: postgres:12.3-alpine env: POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: github_actions ports: - 5432:5432 options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 steps: - name: Checkout uses: actions/checkout@v2 - name: Set up Python 3.9 uses: actions/setup-python@v1 with: python-version: 3.9 - name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt - name: psycopg2 prerequisites run: sudo apt-get install libpq-dev - name: Run migrations run: python app/manage.py migrate - name: Run tests and lint with coverage run: | cd app coverage erase coverage run manage.py test && flake8 coverage report -m -
Django - Query values based on the result of an existing query
I have a query that matches some foreign key properties buy_book__entity and sell_book__entity to a parameter company_group. I need to further add onto this query to filter the results only on the results that match a predicate. Is this possible to do in one query? return (Q(buy_book__entity__company_groups__alias__iexact=company_group) & \ Q(sell_book__entity__company_groups__alias__iexact=company_group)) & \ # I only want to run the below query on objects which # the book entity types are internal (Q(buy_book__entity__primary_company_group__alias__iexact=Case( When(buy_book__entity__type=ENTITY.INTERNAL, then=Value(company_group)), default=Value(None))) | \ Q(sell_book__entity__primary_company_group__alias__iexact=Case( When(sell_book__entity__type=ENTITY.INTERNAL, then=Value(company_group)), default=Value(None)))) I tried the above query utilizing Case and When but this doesn't exactly work because it will give the value as None to the primary_company_group whereas I need it not to query by that at all, almost like an ignore. Since primary_company_group is a nullable foreign key this skews my results heavily. Just FYI, I don't want to filter all entity__type to internal. Just the ones that are internal, I need to run the further query on those. -
Pycharm not recognizing django models, appconfig, etc
I am using Pycharm 2021.1.1, It was all fine, suddenly when I try to write from django.apps import AppConfig It is showing unsolved reference AppConfig from django.db import models It is showing Unsloved reference models But I have installed all necessary modules, like Django, DjangoRestFramework, and the actual virtualenv is activated. -
How to serialize JSON Request data from serializer in Django?
I am trying to serialize a json data through serializers.Serializer { "data": { "phoneNumber": "1234567890", "countryCode": "+11", "otp": "73146", } } The sterilizer class I wrote for it and also I don't know why source is not working, I tried the JSON in the picture below but still it's saying the field is required