Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how can i solve paginator problem in python django?
error page it's a search_post.html it's a View.py -
Django Project to convert Binary to Decimal
I recently started learning Django and I want to create a Django project to convert Binary into Decimal The functionality should be similar to this one I am unable to figure out how should I proceed and what should I use. I want to achieve the following : I shouldn't use models.py because I don't want to store the data every time a user enters. I need to pass a condition to check whether the data entered is in the form of 1's and 0's. I need to pass the integer data after it is converted from binary data back to the HTML form and display in the browser forms.py from django import forms from django.forms import TextInput class BinaryDecimalForm(forms.Form) : binary = forms.CharField( widget=forms.TextInput(attrs={'class':'input','placeholder':'Binary...','size':40}), max_length=8 ) views.py from django.shortcuts import render from .forms import BinaryDecimalForm def home(request) : form = BinaryDecimalForm() if request.method == 'POST' : form = BinaryDecimalForm(request.POST) if form.is_valid : data = form.cleaned_data.get('binary') for d in data : if d.is_binary() : pass context = { 'form' : form } return render(request,'app\home.html',context) home.html <main> <br> <div class="container"> <div class="row"> <div class="col-md-8 mx-auto"> <form action="" method="post"></form> {% csrf_token %} {{form.binary}} <br> <br> <button class="btn btn-outline-primary" type="submit">CONVERT</button> <br> <br> <input … -
topic = models.ForeignKey(Topic) TypeError: __init__() missing 1 required positional argument: 'on_delete'
from django.db import models Create your models here. class Topic(models.Model): top_name = models.CharField(max_length=264, unique=True) def __str__(self): return self.top_name class Webpage(models.Model): topic = models.ForeignKey(Topic) name = models.CharField(max_length=264, unique=True) url = models.URLField(unique=True) def __str__(self): return self.name class AccessRecord(models.Model): name = models.ForeignKey(Webpage) date = models.DateField() ```def __str__(self):``` ```return str(self.date)``` **on_parameter is required ** I'm using Django v3.0 in Pycharm please guide me CODE THAT I WROTE -
Carousel items not showing 4 items in 2nd slide in django and html template
i am trying to display all carousel item through for loop dynamic from the database but 1st slide is perfectly showing 4 card items but 2nd slide only showing three carousel items . Here carousel items image and the html file <div class="row"> <h2 id="trendingservice">Trending <b class="underline-small"> Services</b></h2> <div id="myCarousel" class="carousel slide" data-ride="carousel" data-interval="0"> <div id="demo" class="carousel slide" data-ride="carousel"> <!--Slideshow starts here --> <div class="container carousel-inner no-padding"> <div class="carousel-item active"> <div class="col-xs-3 col-sm-3 col-md-3"> <div class="card" style="width: 18rem;"> <img src="/media/{{ services.0.Image }}" class="card-img-top" alt="..." /> <div class="card-body"> <h5 class="card-title">{{ services.0.service_name }}</h5> <p class="card-text"> {{ services.0.service_desc|safe }} </p> <a href="/website/services/{{ services.0.service_name }}" class="color-two btn-custom">Get Services</a> </div> </div> </div> {% for i in services|slice:"1:" %} <div class="col-xs-3 col-sm-4 col-md-3"> <div class="card" style="width: 18rem;"> <img src="/media/{{ i.Image }}" class="card-img-top" alt="..." /> <div class="card-body"> <h5 class="card-title">{{ i.service_name}}</h5> <p class="card-text"> {{ i.service_desc|safe }} </p> <a href="/website/services/{{ i.service_name }}" class="color-two btn-custom">Get Services</a> </div> </div> </div> {% if forloop.counter|divisibleby:3 and forloop.counter > 0 and not forloop.last%} </div> <div class="carousel-item"> {% endif %} {% endfor %} </div> </div> </div> <!-- left and right controls for the slide --> <a class="carousel-control-prev" href="#demo" data-slide="prev"> <span class="carousel-control-prev-icon"></span> </a> <a class="carousel-control-next" href="#demo" data-slide="next"> <span class="carousel-control-next-icon"></span> </a> </div> </div> </div> **here is view.py … -
run Gunicorn with WSGI inside a folder
I have my project structure as below. I use folders to put all the settings files in them. ~/myproject/ - env - server - api - home - settings - dev.py - prod.py - wsgi - dev.py - prod.py the myproject/server/home/wsgi/dev.py is: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "home.settings.dev") application = get_wsgi_application() also inside myproject/server/home/settings/dev.py is: WSGI_APPLICATION = 'home.wsgi.dev.application' with all the above setup the server runs perfectly. When i try to deploy and run the gunicorn, it just fails. Here is my gunicorn.service: [Unit] Description=gunicorn daemon After=network.target [Service] User=demouser Group=www-data WorkingDirectory=/home/demouser/myproject ExecStart=/home/demouser/myproject/env/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/demouser/myproject.sock home.wsgi.dev:application [Install] WantedBy=multi-user.target I am not sure why i get this error as the gunicorn never starts: Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Sun 2020-08-30 05:04:48 UTC; 14min ago Process: 13354 ExecStart=/home/demouser/myproject/env/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/ Main PID: 13354 (code=exited, status=203/EXEC) Aug 30 05:04:48 localhost systemd[1]: Started gunicorn daemon. Aug 30 05:04:48 localhost systemd[13354]: gunicorn.service: Failed to execute command: No such file or directory Aug 30 05:04:48 localhost systemd[13354]: gunicorn.service: Failed at step EXEC spawning /home/demouser/myproject/env/ Aug 30 05:04:48 localhost systemd[1]: gunicorn.service: Main process exited, code=exited, status=203/EXEC Aug 30 05:04:48 localhost systemd[1]: … -
Why django is accepting two diiferent passwords? Giving no error at all
Why this code is accepting both password and confirm_password field? without errors Here is first models.py file: (indent is not a problem here) from django.db import models from django.contrib.auth.models import AbstractBaseUser from .managers import UserManager from django.utils.translation import ugettext_lazy as _ # Create your models here. ROLES = ( ('Customer', 'Customer'), ('Vendor', 'Vendor') ) class User(AbstractBaseUser): email = models.EmailField(verbose_name='Email Address', max_length=255, unique=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) role = models.CharField(max_length=15, choices=ROLES) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] objects = UserManager() def __str__(self): return self.email def get_name(self): return self.first_name + ' ' + self.last_name def get_role(self): return self.role def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.staff @property def is_admin(self): return self.admin @property def is_active(self): return self.active Next the manager for user model: Here I'm just accepting data and creating accounts only. from django.contrib.auth.models import BaseUserManager from django.db import models from django.utils.translation import ugettext_lazy as _ class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): if not email: raise ValueError('User must have an Email Address') user = self.model(email=self.normalize_email(email), **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password, **extra_fields): extra_fields.setdefault('staff', False) extra_fields.setdefault('admin', False) … -
debugging jQuery ajax - works on localhost server, doesn't work on production server
For example, the following ajax call is working just fine on my localhost: $.ajax({ type:"POST", url: "/teachers/studentMonthAgenda/", data:{ 'event_start': dayMs, 'event_end': endOfMonthMs, 'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val(), }, dataType: 'json', cache: false, success: function( eventData ) { getEvents(eventData); }, error: function(xhr, status, error){ var errorMessage = xhr.status + ': ' + xhr.statusText alert('Error - ' + errorMessage); } }); On my production server with the following attributes: Python 3.6 running on 64bit Amazon Linux/2.9.13 elastic beanstalk the same code leaves absolutely no trace of an error. I'm finding ajax to be the only thing that can't be debugged easily on elastic beanstalk because it leave absolutely squat in the log file if there is an error, and there clearly is something going wrong in this case. The inputs (dayMS and endOfMonthMs) are good too, so it really must be the ajax call that is the problem. I should add, it was working before I redirected traffic from port 80 to port 443. -
Django: Is there a way to use widgets on functions without class in view.py?
I am new to django and trying to use widgets and bootstrap to make my forms template look better. I saw a video tutorial on how to do so, but he uses class in views.py while I want it on function I created. Is there anyway to use the given widget on function addItem? The forms.py file: class ItemsForm(ModelForm): class Meta: model = Item fields = "__all__" widgets = { 'name': forms.TextInput(attrs={'class': 'form-control'}), 'price': forms.TextInput(attrs={'class': 'form-control'}), 'category': forms.Select(attrs={'class': 'form-control'}), 'image':forms.TextInput(attrs = {'class':'form-control-file'}), } My views.py file: def addItem(request): if request.method=="POST": form=ItemsForm(request.POST, request.FILES) print(form) if form.is_valid(): try: print("valid") form.save() return redirect("/items") except: print("validation failed") else: form=ItemsForm() print("invalid") return render(request, "dashboard/items/items_form.html",{'form':form}) The template I am trying to render it in: <div class="form-group"> <form action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} {{form.as_p}} <input type="submit" name="Submit"> </form> </div> -
connecting list view and detail view -django
i am trying to create class based detailed view, which can be accessed by clicking listview items.. the problem is it was easly achieved in function based views but cant do the same in class based views. model.py from django.db import models import datetime # Create your models here. class BlogPost(models.Model): title = models.CharField(max_length=500) writer = models.CharField(max_length=150,default='my dept') category =models.CharField(max_length=150) image = models.ImageField(upload_to='images') post = models.TextField(max_length=2000) Date = models.DateField( default=datetime.date.today) def __str__(self): return self.title views.py from.models import BlogPost , EDITORIAL_RESPONSIBILITIES , Reviewers ,Confrences ,ABSTRACT_IN_CONFERENCES class BlogList(ListView): model = BlogPost template_name = 'blog/bloglist.html' context_object_name = 'post' class BlogDetail(DetailView): model = BlogPost template_name = 'blogdetail.html' urls.py path('list', BlogList.as_view(), name='list'), path('(?P<id>\d+)/', BlogDetail.as_view()) listview template is working absolutely fine.. the directory structure is fine.. both listviw.html and detail.html are in same folder under templates/blog/ .. listview template <div class="post-body"> {% for p in post %} <blockquote>{{p}}</br></br>{{p.Date}}</blockquote> {% endfor %} </div><!-- end post-body --> -
Django - how to create a form for two models that is related?
I have a model called Kitchen and a model called Furnitures. A kitchen has lot of furnitures, how can I create a form/view/template in a way that the user can fill the info about these two models at the same time and when the button is pressed the two models are created and already related with each other? Is that possible? -
Cannot call QuerySet with a ForeignKey in Django
Version Mac OS : 10.15.6 Django : 3.7.6 What I want to do Get all Want_Items that are had by a specific user Hello, I'm a beginner to Django. I am trying to create an app that each can exchange their items. I created models, User, Parent_Item, Want_Item, Give_Item. And I set relations between them like below. User - Parent_Item => One To Many Parent_Item - Give_Item => One To Many Parent_Item - Want_Item => One To Many I succeeded in getting all parent_item that one user has. However, I cannot get want_item for some reason. This is my attempts and errors I was faced with. >>>toshi_want = Toshi.item.want_item.all() Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: 'RelatedManager' object has no attribute 'want_item' >>> toshi_all=Toshi.item.all() >>> print(toshi_all) <QuerySet [<Parent_Item: MacBook>, <Parent_Item: Desk>, <Parent_Item: shirt>]> >>> print(toshi_all.want_item.all()) Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: 'QuerySet' object has no attribute 'want_item' I surely set a ForeignKey with related_name = "want_item". Why cannot I use this in this case?? I would like you to teach me solutions and why it happens. models.py class User(models.Model): username = models.CharField(max_length=150, unique=True) email = models.EmailField(max_length=100, unique=True) password = … -
Django Foreign Key Constraint failed after blank = True
I get an Integrity error, Foreign Key Constraint failed. I have the following function I am trying to run: if request.method == "POST": #Get token access_token = AccessToken.objects.get(token = request.POST.get('access_token'), expires__gt = timezone.now()) #Get profile customer = access_token.user.customer # Check if customer has a order that is not delivered if Order.objects.filter(customer = customer).exclude(status = Order.DELIVERED): return JsonResponse({"status": "fail", "error": "Your Last Order must be completed"}) # Check Address if not request.POST["address"]: return JsonResponse({"status": "failed", "error": "Address is required."}) # Ger Order Details order_details = json.loads(request.POST["order_details"]) order_total = 0 for meal in order_details: order_total += Meal.objects.get(id = meal["meal_id"]).price * meal["quantity"] if len(order_details)>0: # Step 1 - Create an Order order = Order.objects.create( customer = customer, restaurant_id = request.POST["restaurant_id"], total = order_total, status = Order.PENDING, address = request.POST["address"] ) # Step 2 - Create Order details for meal in order_details: OrderDetails.objects.create( order = order, meal_id = meal["meal_id"], quantity = meal["quantity"], sub_total = Meal.objects.get(id = meal["meal_id"]).price * meal["quantity"] ) return JsonResponse({"status": "success"}) Here is my order class: Class Order(models.Model): PENDING = 1 COOKING = 2 READY = 3 ONTHEWAY = 4 DELIVERED = 5 STATUS_CHOICES = ( (PENDING, "Pending"), (COOKING, "Cooking"), (READY, "Ready"), (ONTHEWAY, "On The Way"), (DELIVERED, "Delivered"), ) customer = models.ForeignKey(Customer, … -
Django - How to get all items from a model that has foreign key?
I'm creating two models: Feedstockformula and formula. This is the code for each one: FeedstockFormula: from django.db import models class FeedstockFormulas(models.Model): ratio = models.FloatField() feedstock = models.OneToOneField("dashboard.Feedstock", on_delete=models.CASCADE, default="0") formulas = models.ForeignKey("dashboard.Formulas", on_delete=models.CASCADE, default="") Formula: from django.db import models class Formulas(models.Model): name = models.CharField(max_length=100) cost = models.FloatField() weight = models.FloatField() How can I get all the FeedstockFormulas that is part of a Formula? -
Django-Import-Export: Import Error - AttributeError: 'str' object has no attribute 'year'
I'm trying to use the django-import-export package to import a csv into my django model. the csv is very simple, a header row and the one row of values. there are two fields on the csv that are defined in the model as DateField's #models.py edit_date = models.DateField(verbose_name="Edit Date", blank=True, default="1970-01-01") premiere_date = models.DateField(verbose_name="Premiere Date", null=True, blank=True) there are another set of DateTime.Field's in the model that are not included in the csv file. I have added header fields to the csv for these, but the csv hs no values for the fields. created = models.DateTimeField(blank=True) updated = models.DateTimeField(blank=True) deleted_at = models.DateTimeField(blank=True,null=True) For the django-import-export package, I have a Resource class defined in my admin.py and it is working for exporting a csv. But when I try to import a csv - I get an Attribute Error. AttributeError: 'str' object has no attribute 'year' The full traceback is listed below. I've tried to fix this by adding a before_save_instance method to the Resource class. But I'm still getting the same error. I've been through the docs and searched stack overflow, but I can't find a clear explanation of how to handle imports with the import-export package. #admin.py from datetime import … -
Does the django-rest-framework provide an admin site to manage models?
I'm looking to setup a REST API server with django, and googling suggests this is best done using the django-rest-framework. The API will return objects stored in a database, and I would also like to be able to add/modify the objects in the database using the django admin site. However, looking at the django-rest-framework documentaion, I see no reference to the admin site (I did find things about "AdminRenderer", but it looked like this isn't what I want). Simply, does the django admin site exist for a django-rest-framework project? -
Django Access Token Matching Query Does Not Exist
I have the following code I am trying to test: def customer_add_order(request): """ params: access_token restaurant_id address order_details(json format), example: [{"meal_id": 1, "quantity":2}, {"meal_id": 2, "quantity":3}] stripe_token return: {"status": "success"} """ if request.method == "POST": #Get token access_token = AccessToken.objects.get(token = request.POST.get("access_token"), expires__gt = timezone.now()) #Get profile customer = access_token.user.customer # Check if customer has a order that is not delivered if Order.objects.filter(customer = customer).exclude(status = Order.DELIVERED): return JsonResponse({"status": "fail", "error": "Your Last Order must be completed"}) # Check Address if not request.POST("address"): return JsonResponse({"status": "failed", "error": "Address is required."}) # Ger Order Details order_details = json.load(request.POST["order_details"]) order_total = 0 for meal in order_details: order_total += Meal.objects.get(id = meal["meal_id"]).price * meal[quantity] if len(order_details)>0: # Step 1 - Create an Order order = Order.objects.create( customer = customer, restaurant_id = request.POST["restaurant_id"], total = order_total, status = Order.PENDING, address = request.POST["address"] ) # Step 2 - Create Order details for meal in order_details: OrderDetails.objects.create( order = order, meal_id = meal["meal_id"], quantity = meal["quantity"], sub_total = Meal.objects.get(id = meal["meal_id"]).price * meal["quantity"] ) return JsonResponse({"status": "success"}) I enter the params in Postman, and use an access token that shows valid in django, and it hasn't expired. I am using the rest framework and the function … -
Django Admin page models name instead of TABLE object(id)
Is there any way to change the way objects are named in Django Admin page. Currently all of the objects are using a TABLE Object(id) as their name: table in admin page Can i make it for example a key form the table like a name or smth. And is there any way to add search bar that goes over the names of the items in the table to filter it by that name. -
Unable to import apps from settings.py's INSTALLED_APPS list
I'm hitting an error when running makemigrations, and it seems to be related to my INSTALLED_APPS list. Here is a screenshot of my project: and here is the error: I've also attempted to use the following strings in the INSTALLED_APPS list, but I got the same error: '.api.apps.ApiConfig', '.pizzas.apps.PizzasConfig', The classes ApiConfig and PizzaConfig both follow this structure in their respective apps.py files: from django.apps import AppConfig class PizzasConfig(AppConfig): name = 'pizzas' Does anyone have any ideas as to what I could be missing here? -
Pinax-teams: what does self.memberships mean in BaseTeam?
I am trying to understand each step of the Pinax-teams models.py file (https://github.com/pinax/pinax-teams/blob/master/pinax/teams/models.py). I can't work out what memberships in the following method (belonging to the BaseTeam class) refers to: def for_user(self, user): try: return self.memberships.get(user=user) except ObjectDoesNotExist: pass There are several ForeignKey fields in other classes with related_name="memberships" but none of these fields link to the BaseTeam class directly. Please can someone tell me what memberships means? -
Filtering elements from Django database on two conditions
I want to select elements from my Django database on two conditions - whether the boolean value "used" is true and whether or not the "dateUsed" is within the last 20 days. However, my current filter statement is returning an empty QuerySet, even though there should be elements that meet both conditions. Am I filtering the elements correctly? I've attached the code that filters the elements, the definitions of my models, as well as the block of code that changes the value of "used" once the model elements have been displayed on my site. Filter: def pastSongs(request): window = datetime.now().date() - timedelta(days=20) songHistory = Song.objects.filter(used = True).filter(dateUsed__gt = window) ent = {} ent["ent"] = songHistory return render(request, 'rollingStone/songs.html',ent) Models: class Song(models.Model): rank = models.IntegerField() artist = models.CharField(max_length=100) title = models.CharField(max_length=100) cover = models.URLField() writers = models.CharField(max_length=100) producers = models.CharField(max_length=100) releaseInfo = models.CharField(max_length=100) description = models.TextField(max_length=3000) used = models.BooleanField(default=False) dateUsed = models.DateField(auto_now=True) Changing "used" field: def reload(): # Change status of old song/album to used, and save the date that it was used if entry["status"] == "filled": currentSong = Songs.objects.get(entry["songEnt"].name) currentAlbum = Albums.objects.get(entry["albumEnt"].name) currentSong.dateUsed = datetime.now().date() - timedelta(days=1) currentAlbum.dateUsed = datetime.now().date() - timedelta(days=1) currentSong.used = True currentAlbum.used = True currentSong.save() currentAlbum.save() -
Trying to understand how to add to cart in Django ecommerce tutorials
I have been following this tutorials for quite some time by JustDjango on youtube here is the link https://www.youtube.com/watch?v=Xjty8q524Jo&t=3s I don't actually understand logic in add to cart function the codes are not just making sense to me. @login_required def add_to_cart(request, slug): item = get_object_or_404(Item, slug=slug) order_item, created = OrderItem.objects.get_or_create( item=item, user=request.user, ordered=False ) order_qs = Order.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] # check if the order item is in the order if order.items.filter(item__slug=item.slug).exists(): order_item.quantity += 1 order_item.save() messages.info(request, "This item quantity was updated.") return redirect("core:order-summary") else: order.items.add(order_item) messages.info(request, "This item was added to your cart.") return redirect("core:order-summary") else: ordered_date = timezone.now() order = Order.objects.create( user=request.user, ordered_date=ordered_date) order.items.add(order_item) messages.info(request, "This item was added to your cart.") return redirect("core:order-summary") This part below confuses me a lot. Who can explain wat dis means order = order_qs[0] order_qs = Order.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] # check if the order item is in the order if order.items.filter(item__slug=item.slug).exists(): Is there anytutorials that explains adding to cart in django very well, I will like to see it What is the logic in this if and else along with the nested if else inside it if order_qs.exists(): ............... # check if the order item … -
Is there an elegant way to export a Bootstrap-Studio project to a folder of lovely Django templates?
Dear wise and experienced spirits of StackOverflow, I am turning to thee in deep despair. My teacher gave me the honourable task to design a data-administration interface for our school paramedics. Somehow experienced in Python through machine learning I planned on writing the backend of the website with Django, as I did not have any interest in learning a fully new language / framework in such short time. Because of me being quite a greenhorn when it comes to WebDev, I remembered owning a license for Bootstrap-Studio through GitHub-Edu. As you might guess, I now have a fairly pretty frontend with all those forms I needed, but am unable to convert it into these Django templates that I need even more. I reeeeaaaaally hope that there might be any chance of getting this project done as ASAP as possible (see what I did there, huh?), because I am really running out of mental fuel these days. Yes, I might be a fool, but there are so many deadlines to hit... :( Thank you very much in advance, every tiniest bit of help is higly appreciated. Thus indebted to you for your pains taken for me, I bid you farewell. -
What is the difference in localhost:8000 and http://127.0.0.1:8000?
I am running a Django project with react redux (trying to implement authentication system) and the very weird thing i observed that my site is rendering properly when i use localhost:8000 or http://127.0.0.1:8000. But when i m trying to login/signup (ie trying to send post request) then it working only when i use localhost:8000, and giving some error when using http://127.0.0.1:8000. One of the error when using http://127.0.0.1:8000 is shown below. However i have seen this and found localhost will often resolve to ::1, the IPv6 loopback address. But i am getting is it related to this or not ? And whether localhost:8000 and http://127.0.0.1:8000 is same or not ? Please try to answer in simple words because I have not much knowledge of internet protocol or networking. -
Django Admin StackedInline
I have a stackeinline Django admin. This is used to add multiple products for a shop. However, when I click on 'Save and add another' it sometimes shows 'Entity too large', even when the files are below the allowed size, or sometimes it shows 'DATA_UPLOAD_MAX_NUMBER_FIELDS' error. My question is, does Django stackedinline admin save each and every object each time we click on save? If no, then what could be the reason for this error? -
Creating instances of 2 related models using nested serializer in Django
I am a newbie at Django and I have come across this problem with my code. I have a Custom User Model and an Account model which are related by many-to-many field. During SignUp a user is asked to either create an Account or not ( join other account through a link ). If the User creates an Account then he is the owner of the account and other Users can join the account.(Did not finish the code for ownership) One User can be a part of several accounts at the same time. Creation of Account(or not) and the User takes place in the Signup view. I read up about the nested serializer in the documentation and i think this should create the two models instances. How to create relationships in one view using nested serializers? Other Approaches to solve the issue? Models class Account(models.Model): AccountName = models.TextField(max_length=100, blank=False, null=False) class User(AbstractBaseUser): AccountName = models.ManyToManyField(Account) CreateAccount = models.BooleanField(blank=False, null=False) EmailId = models.EmailField(max_length=128, blank=False, null=False, unique=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) USERNAME_FIELD = 'EmailId' REQUIRED_FIELDS = ['AccountName', 'CreateAccount',] # Implemented the other req. functions objects = MyAccountManager() Serializers class AccountCreationSerializer(ModelSerializer): class Meta: model = …