Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Change the error message for a M2M relation
Change the error message for a M2M relation: I have 2 models, Item and Type: class Item(models.Model): types = models.ManyToManyField(Type, related_name='items') class ItemForm(forms.Form): class Meta: model =Item fields = ['types', 'name', 'desc'] I get the following validation error: Select a valid choice. 0 is not one of the available choices. I want to change this message. How can be done ? -
Writable nested serializer on django reset framework validation error on the nested foreign key. Field is required
I am trying to make a writable nested serializer in Django Rest Framework. But I get validation error: slug is required. but it is the foreign key and it is not known before insert of the parent object takes place. Here is my models and serializers: Models: class Letter(BaseModel): char = models.CharField( max_length=1, ) slug = models.ForeignKey( to="core.LetterSlug", related_name="letters", on_delete=models.CASCADE, ) class LetterSlug(BaseModel): char = models.CharField( max_length=1, ) Serializers: class LetterSerializer(serializers.ModelSerializer): class Meta: model = Letter fields = '__all__' class LetterSlugSerializer(serializers.ModelSerializer): letters = LetterSerializer(many=True,instance=Letter.objects.all()) class Meta: model = LetterSlug fields = ('char', 'letters') def create(self, validated_data): letter_data = validated_data.pop('letters') slug = LetterSlug.objects.create(**validated_data) Letter.objects.create(slug=slug, **letter_data) return slug I expect it to add several Letter objects all of which share the same foreign key to the newly created LetterSlug object. I tried commenting out contents of my create method, and made sure that it's during validations before calling create method. -
Django Rest Framework not login after registation
I have a site on the Django and I have custom User model. On site, where I use Django Forms, I can register and after login, and it works well. Then I started to use a DRF and Django-rest-auth. I write a custom register serializer, after I wrote a path for it in the settings. from rest_framework import serializers from ideas.models import Post, Unit, StatusOfPost from accounts.models import User from django.contrib.auth import authenticate from django.contrib.auth import get_user_model from allauth.account import app_settings as allauth_settings from allauth.utils import email_address_exists from allauth.account.adapter import get_adapter from allauth.account.utils import setup_user_email class RegisterSerializer(serializers.Serializer): phone_number = serializers.CharField(required=True, write_only=True) username = serializers.CharField(required=True, write_only=True) email = serializers.CharField(required=True, write_only=True) first_name = serializers.CharField(required=True, write_only=True) last_name = serializers.CharField(required=True, write_only=True) password1 = serializers.CharField(required=True, write_only=True) password2 = serializers.CharField(required=True, write_only=True) def get_cleaned_data(self): return { 'first_name': self.validated_data.get('first_name', ''), 'last_name': self.validated_data.get('last_name', ''), 'address': self.validated_data.get('address', ''), 'username': self.validated_data.get('username', ''), 'password': self.validated_data.get('password', ''), 'email': self.validated_data.get('email', ''), 'phone_number': self.validated_data.get('phone_number',''), } def validate_email(self, email): email = get_adapter().clean_email(email) if allauth_settings.UNIQUE_EMAIL: if email and email_address_exists(email): raise serializers.ValidationError( ("A user is already registered with this e-mail address.")) return email def validate_username(self, username): username = get_adapter().clean_username(username) return username def validate_password1(self, password): return get_adapter().clean_password(password) def validate(self, data): if data['password1'] != data['password2']: raise serializers.ValidationError( ("The two password … -
Mysql install error in Django 2 Linux mint
I try to connect MYsql with Django. For that, I need to install mysqlclient by this following command pip install mysqlclient but it's giving me this following error /usr/local/lib/python2.7/dist-packages/pip-18.0-py2.7.egg/pip/_vendor/requests/init.py:83: RequestsDependencyWarning: Old version of cryptography ([1, 2, 3]) may cause slowdown. warnings.warn(warning, RequestsDependencyWarning) Collecting mysqlclient Using cached https://files.pythonhosted.org/packages/ec/fd/83329b9d3e14f7344d1cb31f128e6dbba70c5975c9e57896815dbb1988ad/mysqlclient-1.3.13.tar.gz Installing collected packages: mysqlclient Running setup.py install for mysqlclient ... error Complete output from command /usr/bin/python -u -c "import setuptools, tokenize;file='/tmp/pip-install-kP3VWP/mysqlclient/setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record /tmp/pip-record-Znr67C/install-record.txt --single-version-externally-managed --compile: running install running build running build_py creating build creating build/lib.linux-x86_64-2.7 copying _mysql_exceptions.py -> build/lib.linux-x86_64-2.7 creating build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/init.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/compat.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/connections.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/converters.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/cursors.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/release.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/times.py -> build/lib.linux-x86_64-2.7/MySQLdb creating build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/init.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/REFRESH.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants running build_ext building '_mysql' extension creating build/temp.linux-x86_64-2.7 x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fno-strict-aliasing -Wdate-time -D_FORTIFY_SOURCE=2 -g -fstack-protector-strong -Wformat -Werror=format-security -fPIC -Dversion_info=(1,3,13,'final',0) -D__version__=1.3.13 -I/usr/include/mysql -I/usr/include/python2.7 -c _mysql.c -o build/temp.linux-x86_64-2.7/_mysql.o _mysql.c:37:20: fatal error: Python.h: No such file or directory compilation terminated. error: command 'x86_64-linux-gnu-gcc' failed with exit … -
One to one relation in django
You are using a Foreign key in Django models automatically _ id is added to the respective field while saving in db. Is the same happend to one to one and many to many relations in Django models? -
prefetch_related cache with custom manager
I have something similar to the following set up:- from django.contrib.sites.models import Site from django.contrib.sites.managers import CurrentSiteManager from django.db import models class A(models.Model): pass class B(models.Model): a = models.ForeignKey(A) class C(models.Model): site = models.ForeignKey(Site) a = models.ForeignKey(A, related_name='cs') objects = models.Manager() on_site = CurrentSiteManager() If I use prefetch_related to fetch all of the Cs associated with a particular instance of B, it fetches all Cs, regardless of the Site. Fine. I then want to use the custom on_site manager so that I only get the Cs that are on the current site, but the objects have been cached internally by Django (I think) and so it returns them all, whether they're on the current site or not. >>> a=A.objects.create() >>> B.objects.create(a=A.objects.get()) >>> s1=Site.objects.create(domain='site1.com') >>> s2=Site.objects.create(domain='site2.com') >>> C.objects.create(site=s1, a=a) >>> C.objects.create(site=s2, a=a) >>> b = B.objects.prefetch_related('a__cs__site').last() >>> for c in b.a.cs(manager='on_site').all(): print c.site site1.com site2.com I know I can filter manually by site in this particular case but in the actual code, I don't want to have to "know" that I need to do this extra filter when using the custom manager like this, just because I've done a prefetch_related earlier on. Is this a bug in Django? Should it clear … -
django-allauth ACCOUNT SESSION REMEMBER=None but it does not work?
Firstly, i konw django-allauth should work as follows: None: optionally remember, depending on user input; True: always remember; False: never remember;enter code here but,in my case , when ACCOUNT SESSION REMEMBER = None, No matter whether the user choose to check 'remember me', it does not work.ACCOUNT SESSION REMEMBER = False or True , it is right. -
Share Celery queues with Django functions and start workers at startup
I have a Django project and 2 Celery workers, I want to start the worker 1 at django startup and update store some vars in a queue, the other worker should be called whenever I want and use the vars stored in the queue, I also want to be able to read the queue vars from other non-celery functions. My problem is that I don't know where should I call the first worker in Django and also how to define a global queue. For calling the worker, I tried the urls.py but it seems it calls the worker multiple times. -
Filter by string in django
I have 2 models: UserProfile and User_Details and I want to display the details for one user.I think the problem is at the filter and I don't know how to filter after a string,I'm new to django.How can I fix this? class ShowProfile(APIView): renderer_classes = [TemplateHTMLRenderer] template_name = 'profile.html' def get(self, request, pk, format=None): details=User_Details.objects.all().filter(user=request.user.username) serializer = ProfileSerializer2(details, many=True) pprint.pprint(json.loads(JSONRenderer().render(serializer.data))) return Response({'fields ': serializer}) def post(self, request): serializer = CreatePostSerializer(data=request.data) if not serializer.is_valid(): return Response({'fields': serializer }) user = UserProfile.objects.filter(username=request.user.username).first() serializer.save(user=user) pprint.pprint(json.loads(JSONRenderer().render(serializer.data))) return redirect('mainPage') Models: class UserProfile(AbstractUser): pass class User_Details(models.Model): user = models.OneToOneField(UserProfile, on_delete=models.CASCADE) first_name = models.CharField(max_length=50, blank = True) last_name = models.CharField(max_length=50, blank=True) gender = models.CharField(max_length=6, blank=True, default='') public_info=models.CharField(max_length=100, blank=True, default='') Template: {% extends 'base2.html' %} {% load rest_framework %} {% block content %} <div class="container"> <div class="row"> <div class="col-md-3 "> <div class="list-group "> <a href="#" class="list-group-item list-group-item-action active">Profile</a> <a href="{% url 'show_my_posts' pk=user.id %}" class="list-group-item list-group-item-action">My Posts</a> </div> </div> {% for d in fields %} {{d.firs_name }}<h1>a</h1> {% endfor %} {% endblock %} -
Does accessing a related object through self hit the database in Django?
In Django, if I have a ForeignKey or a ManyToMany field in a model, is the database hit every time I try to access them through self? How many time is the database hit in this example? # loop done 10 times for x in looping_array: print(self.foreign_key_object) -
Can we call GET/POST ajax call from Pentaho data integration spoon
I am using Django, Neo4j, and pentaho. In Pentaho Data Integration, we can use the javascript for any transaction. My question is that can we call ajax from the PDI javasticpt to django server method. Actually i want to send success msg to server after the ETL process done by the PDI. -
How to rub python .py file from django and show the result in the browser?
This is my django dir structure: https://drive.google.com/file/d/1cjls7jB7oGHL0PLYWowhj_vz0pCXkHev/view?usp=sharing I have trends.py file. I run this trends.py from the terminal and it prints the result of the twitter trading topic on Terminal. Please refer to this image. https://drive.google.com/file/d/1OCX-zmK-CA1rZrlEwY7v1pkrsSusDoeV/view?usp=sharing I am using Django 1.11. I want to run this script from a URL and show the result on the browser. -
Associate multiple unique forms to a unique object in Django
I'm trying to build a web application using Django where a user can create a 'Project' and within that 'Project', there are four different forms. My Question is, how do I associate those forms to a specific 'project' in the sense that the form is linked to that specific 'project'. I'm close to doing it but I'm having issues with the 'create-project.html', 'create-request-1.html' and 'create-request-2.html' pages from rendering due to the 'PK' in the 'projects.html' page URL. The exact errors I get for navigating to those pages is - NoReverseMatch at /projects/create-project/ Reverse for 'initiate_project' with no arguments not found. 1 pattern(s) tried: ['projects\\/project\\/(?P<pk>[0-9]+)\\/$'] Or NoReverseMatch at /project/create-post-1/ Reverse for 'initiate_project' with no arguments not found. 1 pattern(s) tried: ['projects\\/project\\/(?P<pk>[0-9]+)\\/$'] The path is as follows - 'projects.html' - 'create-project.html' - 'initiate-project.html' - 'create-request-1.html' 'create-request-2.html' I can navigate and go into each unique 'project' (e.g. project 1, project 2) in 'projects.html' but I can't get into my forms ('create-request-1.html', 'create-request-2.html') inside the 'initiate-project.html' page that's within each 'project' in the 'projects.html' page. Here's my code so far - model.py - from django.db import models class create_new_project(models.Model): list_display = ('project_name', 'project_manager', 'technical_lead', 'test_lead') class Meta: verbose_name = 'Create New Project' verbose_name_plural = … -
how to display the content in front-end in div area from DB using ajax?
I would like to display the content after clicking the "Get Reports" button beneath the "Get Reports" button that is #search-results area. And Data will be filtered with the selected date's content.(Refer screenshot). Actual Result: I'm getting the expected result in the developer tool and not in the "#search-results" section. #views.py from django.shortcuts import render, get_object_or_404,render_to_response from .models import Statusreport def statusreport(request): return render(request, "statusreport.html") def search_report(request): if request.method == 'POST': search = request.POST['search'] print("checkoutput"+search) else: search = '' statusreport = Statusreport.objects.filter(created_date__contains=search) print(statusreport) return render_to_response("statusreport-detail.html", {'statusreport': statusreport}) #statusreport.html <main class="container"> < form method="POST"> {% csrf_token %} <div class="row" style="padding-top: 100px"> <div class="col"> <label class = 'control-label' for="datepicker">Select Date: </label> <input data-date-format="yyyy-mm-dd" id="datepicker"> </br> </br> <button type="button" class="btn btn-info">GET REPORTS</button> </div> </div> </form> </main> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap- datepicker/1.7.1/js/bootstrap-datepicker.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384- JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> <style type="text/css"> // solution 1: .datepicker { font-size: 0.875em; } .datepicker td, .datepicker th { width: 1.5em; height: 1.5em; } </style> <script type="text/javascript"> $('#datepicker').datepicker({ weekStart: 1, daysOfWeekHighlighted: "6,0", autoclose: true, todayHighlight: true, }); $('#datepicker').datepicker("setDate", new Date()); $(document).ready(function(){ $("button").click(function(){ $.ajax({ type : 'POST', url: "/statusreport/statusreport-detail/", data: { 'search' : $('#datepicker').val(), 'csrfmiddlewaretoken' : $('input[name=csrfmiddlewaretoken]').val() }, sucess : searchSuccess, dataType: 'html' }); }); }); function searchSuccess(data, textStatus, jqXHR) { … -
Django admin site doesn't reflect the data from the form
I'm working on a Django project (v 2.0). I've created and registered an app (user review form) in admin.py. But the problem is upon submitting the form, it doesn't reflect in the admin site. -
No password set in the admin Panel
I have my own RegisterForm. I register successfully, and I can see a newly created user with its encrypted password in DBBrowser. But there's no encrypted password in the admin panel. When I look at the password field in the admin panel I only see "No Password Set" and more I can't log in with my newly created user's username and password. Thank you for your help. My Code: views.py from django.shortcuts import render,HttpResponse,redirect from .forms import RegisterForm, LoginForm from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import login,authenticate,logout from django.contrib import messages # Create your views here. def register(request): if request.method == "POST": form = RegisterForm(request.POST) if form.is_valid(): username = form.cleaned_data.get("username") email = form.cleaned_data.get("email") password = form.cleaned_data.get("password") newUser = User(username= username, email = email) newUser.set_password(password) newUser.save() messages.success(request,"Kayıt İşlemi Başarılı.") login(request,newUser) return redirect("index") context = { "form" : form, } return render(request,"register.html", context) else: form = RegisterForm() #şimdilik içi boş. Sonra GET POST yapılacak context = { "form" : form, } return render(request,"register.html", context) def loginUser(request): form = LoginForm(request.POST or None) context = {"form":form} if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") user = authenticate(request, username=username, password = password) if user is not None: messages.success(request,"Giriş Başarılı Şekilde Yapıldı.") … -
How to get values from Post Method
I have a form which as a input field (List). I would like to access that field individually. My code is below with output what i get. def alltestdata(request): if request.method == 'POST': username = request.POST print(username) return redirect('lab:Dashboard') My output will come something like this <QueryDict: {'csrfmiddlewaretoken': ['vPkRRW9dCFLRRmVAm3PlOS1MURkZ6pSLBxz6ryEuVkwzuD2vW6mlWstFYxF2T4Tx'], 'name': ['gg', 'rr', 'rr','ee']}> -
at the time of submit form it show The current path, home/insert, didn't match any of these
When i Click on submit button is show me. Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: ^admin/ ^home/$ ^insert/$ [name='insert'] The current path, home/insert, didn't match any of these. views.py def insert_page(request): name1 = request.GET['NAME'] email1 = request.GET['EMAIL'] message1 = request.GET['MSG'] data = Feedback(name = name1,email = email1 , message =message1) data.save() return HttpResponse("<html><body bgcolor = cyan> Thanks For Feedback </body></html>") index.html <form action="./insert" method="get"> <div class="row"> <div class="col-md-6 col-sm-6"> <div class="form-group"> <input type="text" class="form-control" required="required" placeholder="Name" name="NAME"> </div> </div> <div class="col-md-6 col-sm-6"> <div class="form-group"> <input type="text" class="form-control" required="required" placeholder="Email address" name = "EMAIL"> </div> </div> </div> <div class="row"> <div class="col-md-12 col-sm-12"> <div class="form-group"> <textarea name="message" id="message" required="required" class="form-control" rows="3" placeholder="Message" name = "MSG" ></textarea> </div> <div class="form-group"> <button type="submit" class="btn btn-default">Submit Request</button> </div> </div> </div> </form> urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^home/$',index_page), url(r'^insert/$',views.insert_page,name = 'insert'), ] -
Django Middleware - get path parameter
This question is an extension to Django: How to access URL regex parameters inside a middleware class? I've the following Middleware:- class WorkFlowMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): ##### I want to get the path parameter before the processing of the view.###### response = self.get_response(request) return response Using process_view, fetches the path parameters after the response = self.get_response(request). How can I prefetch before response = self.get_response(request) and do some processing on it? -
NoReverseMatch at /books/ Reverse for 'urlvar' not found. 'urlvar' is not a valid view function or pattern name. error Django
hello I am getting an error saying NoReverseMatch at /books/ Reverse for 'urlvar' not found. 'urlvar' is not a valid view function or pattern name. I guess {% with %} tag is not working well in books/index.html but idk how to solve this. this is my code : books/urls.py from django.conf.urls import url from books import views urlpatterns = [ url(r'^$', views.BooksModelView.as_view(), name='index'), url(r'^book/$', views.BookList.as_view(), name='book_list'), url(r'^author/$', views.AuthorList.as_view(), name='author_list'), url(r'^publisher/$', views.PublisherList.as_view(), name='publisher_list'), url(r'^book/(?P<pk>\d+)/$', views.BookDetail.as_view(), name='book_detail'), url(r'^author/(?P<pk>\d+)/$', views.AuthorDetail.as_view(), name='author_detail'), url(r'^publisher/(?P<pk>\d+)/$', views.PublisherDetail.as_view(), name='publisher_detail'), ] templates/books/index.html {% extends 'base_books.html' %} {% block content %} <h2>Books Management Systemt</h2> <ul> {% for modelname in object_list %} {% with 'books:'|add:modelname|lower|add:'_list' as urlvar %} <li><a href="{% url 'urlvar' %}">{{ modelname }}</a></li> {% endwith %} {% endfor %} </ul> {% endblock %} Thank you so much -
Get model object from api request
I have an api_view that is called from many modules. url(r'^[0-9a-z\-]+/(?P<pk>[0-9a-z\-]+)/activate_entity/$', activate_entity) @api_view(['POST', 'GET']) def activate_entity(request, pk, *args, **kwargs): What is the correct way to get the instance of the model object dynamically inside activate_entity view without writing too many if statements? , for example i am calling it from module invoice api/v1/invoice/8f9ef9aa-94ac-412d-ba9d-343a70b55a96/activate_entity/ api/v1/finance/8f9ef9aa-94ac-412d-ba9d-343a70b55a96/activate_entity/ -
Pycharms : run Django from virtual env
I have a Django project in Pycharms with a virtualenv named venv My Terminal path is (venv) C:\projects\Django\deya> I install my packages inside this virtualenv The problem is that when I run project from Pycharms run icon I am getting errors like No module named 'django_tables2' The command that Pycharms running is : "C:\Program Files\JetBrains\PyCharm 2017.3\bin\runnerw.exe" C:\Users\kostas\AppData\Local\Programs\Python\Python37\python.exe C:/projects/Django/deya/manage.py runserver 127.0.0.1:8000 My project run fine from Terminal command line , inside virtualenv (venv) C:\projects\Django\deya>python manage.py runserver Can you help me settup the configuration of my projet to run from Pycharms run console? Thanks in advanced Kostas -
Using a decorator with Django blocks the request
I'm trying to create my own decorator in order to validate a REST call with Django (using Django Rest Framework). The decorator looks like this: def allowed_states(allowed=[]): def decorator(func): def wrapper(self, request, *args, **kwargs): print(func) result = func(self, request, *args, **kwargs) return result return wrapper return decorator The request API looks something like this: @swagger_auto_schema( operation_id="my_api", responses={ status.HTTP_204_NO_CONTENT: "", } ) @action(detail=True, methods=["DELETE"]) @allowed_states(allowed=["state1", "state2"]) def my_api(self, request, *args, **kwargs): # do some stuff here When my @allowed_states decorator is removed, the call works just fine. When I add it back I get a 404 error from Django framework saying it could not find a url pattern to execute for this call. -
Django Rest Framework : Setting foreign key value in serializer
I have the following models: class School(models.Model): id = patch.BigAutoField(primary_key=True) name = models.CharField('Name', max_length=100) address = models.CharField('Address', max_length=500, blank=True, null=True) class Child(BaseModel): id = patch.BigAutoField(primary_key=True) name = models.CharField('Name', max_length=100, blank=True, null=True) school = models.ForeignKey('User', blank=True, null=True, db_constraint=False, db_index=True, on_delete=models.CASCADE, default=None) I have the following serializers : class SchoolSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) name = serializers.CharField(required=True, max_length=100) address = serializers.CharField(required=False, max_length=400) def create(self, validated_data): return School.objects.create(**validated_data) def update(self, instance, validated_data): instance.name = validated_data.get('name', instance.name) instance.address = validated_data.get('address', instance.address) instance.save() return instance class Meta: model = School fields = ('id', 'name', 'address') class ChildSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) name = serializers.CharField(required=False, max_length=100, allow_blank=False) school = SchoolSerializer() def create(self, validated_data): return Child.objects.create(**validated_data) def update(self, instance, validated_data): instance.name = validated_data.get('name', instance.name) instance.school = validated_data.get('school', instance.school) instance.save() return instance Now the problem that I am facing is that when I saving any value in my child table using serializer then the value of school is showing null in my database but in my request object I am getting value for school_id. -
Make migrations using models corresponding to the different databases in Django
This is my models.py file in app. from django.db import models class ImaraInventory(models.Model): branch = models.CharField(max_length=255) channel_type = models.CharField(max_length=255) day = models.DateField() partner_id = models.CharField(max_length=255) qty = models.BigIntegerField() sku_id = models.CharField(max_length=255) is_virtual = models.IntegerField() class Meta: unique_together = ('channel_type', 'branch', 'partner_id', 'day', 'sku_id') class ImaraSales(models.Model): attribution = models.CharField(max_length=255) branch = models.CharField(max_length=255) channel_type = models.CharField(max_length=255) day = models.DateField() partner_id = models.CharField(max_length=255) sku_id = models.CharField(max_length=255) live = models.BooleanField() disc_value = models.DecimalField(decimal_places=3,max_digits=12) revenue = models.DecimalField(decimal_places=3,max_digits=12) sales_qty = models.IntegerField() class Meta: unique_together = ('attribution', 'branch' , 'channel_type', 'day', 'partner_id', 'sku_id') class ImaraReturns(models.Model): branch = models.CharField(max_length=255) channel_type = models.CharField(max_length=255) partner_id = models.CharField(max_length=255) sku_id = models.CharField(max_length=255) day = models.DateField() return_qty = models.IntegerField() class Meta: unique_together = ('branch', 'channel_type', 'partner_id', 'sku_id', 'day') class WrognInventory(models.Model): branch = models.CharField(max_length=255) channel_type = models.CharField(max_length=255) day = models.DateField() partner_id = models.CharField(max_length=255) qty = models.BigIntegerField() sku_id = models.CharField(max_length=255) is_virtual = models.IntegerField() class Meta: unique_together = ('channel_type', 'branch', 'partner_id', 'day', 'sku_id') class WrognSales(models.Model): attribution = models.CharField(max_length=255) branch = models.CharField(max_length=255) channel_type = models.CharField(max_length=255) day = models.DateField() partner_id = models.CharField(max_length=255) sku_id = models.CharField(max_length=255) live = models.BooleanField() disc_value = models.DecimalField(decimal_places=3,max_digits=12) revenue = models.DecimalField(decimal_places=3,max_digits=12) sales_qty = models.IntegerField() class Meta: unique_together = ('attribution', 'branch' , 'channel_type', 'day', 'partner_id', 'sku_id') class WrognReturns(models.Model): branch = models.CharField(max_length=255) channel_type = models.CharField(max_length=255) partner_id = …