Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Synchronizing data from external source to db used in django project?
I need to synchronize data from a csv-file every night to update the data in my django project (I'm using mysql as backend). The data contains user information - sometimes users are to be removed, sometimes new user has to be added and sometimes some of the information about a specific user has changed and needs to be updated. I need to keep this in sync. Are there any built in functions to do this (i.e. manage.py/django-admin)? Do I write a python script and work with my django models to manipulate the data? Is it ok/safe to work directly with the tables in the database, bypassing the models? What is best practice? I'm using Python 3.7 and Django 2.1 if this helps. -
Django queryset : Calculate monthly average
I have a sales model and i want to calculate the (Number of transactions)/(num of days) when grouped by month, week, year. class SaleItem(models.Model): id = models.UUIDField(default=uuid4, primary_key=True) bill = models.ForeignKey() item = models.ForeignKey('item') quantity = models.PositiveSmallIntegerField() price = models.DecimalField(max_digits=13, decimal_places=3, default=0) So if sales is grouped by month then this becomes (# transcations/# days in that month) for each month. Now if the sales if grouped by year this becomes (# transcations/# days in that year) Currently i can get the number of transactions aggregate = 'month' # parameter # get number of transactions SaleItem.objects.annotate(date=Trunc('bill__date', aggregate)).values('date').annotate(sales=Count('bill', distinct=True)) But how can i divide each count by the number of days in that group? -
Django - custom admin Home link
MacOS OSX 10.13.6 Django 1.11.3 I have a working Django application. Under Admin I have a menu with several items, first of them is "Home". It's not configured in settings.py and it points to Admin (i.e. model list). How can I customise its url ( make its url to point to one of the other views or any arbitrary location) ? Ideally I would like to control it with a url pattern match in urlpatterns in urls.py, but other options like some setting would work as well. Thanks! -
TypeError at /index/ -- 'bool' object is not callable
from django.shortcuts import render Create your views here. def index(request): title = 'You are not registered in the site' if request.user.is_authenticated(): title = "Welcome %s" %(request.user) context = { "template_title" : title } return render(request, 'mysite/index.html',context) -
How can I restrain acess for my profile view?
I did a view to access personal information. To do this, there is a pk in the URL. However, this is problematic because they can access other user info just by changing the value of the pk. I read the doc and I didn't find anything related to that. How can I prevent this problem? path('profil/<int:pk>', views.ProfilView.as_view(), name="profil") -
Django Rest Framework - List all API in Auto generated doc
i'm using DRF in order to serve a set of API of my application, my api abstraction layer uses the ListCreateAPIView and i have many applications linked to my app, every application, implements an API abstraction level. Now, what i'm trying to do, is to use the default DRF auto generated doc and "try-it" features that comes as "Battery included" from the framework, and in addition, adding to the breadcrumb "API Root" the list of all api that are implemented in the application without using ANY additional package/library, to be clear: Is this possible? Thanks -
Python 2.7 [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:618)>
I am porting a django project over from RHEL5 to RHEL7 and python 2.5 to 2.7.5 and am having certificate problems. The bit of code I am troubleshooting is a suds Client invocation of a web service WSDL client = Client(_LDAP_URLS[env]) where LDAP_URLS is already defined in the code. I imported it using from suds.client import Client I think this may be more of a Linux and Python interaction problem between the two versions rather than an issue with the code, but I could be wrong. Here is the full code. (this is django by the way, so this is a view.py file) from django.conf import settings from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect, HttpResponse from django.shortcuts import render_to_response from suds.client import Client from suds.wsse import Security import suds from gaic.security.sso import BinarySecurityToken from ud_data_extract import UDDataExtractForm import logging import re import sys # logger = logging.getLogger('gaic.toys') logging.basicConfig() log = logging.getLogger(__name__) # logger.setLevel(logging.DEBUG) def index(request): pass def users_default(request): return HttpResponseRedirect(reverse('apps.toys.views.users', kwargs={'env': 'production'})) def users(request, env): msg = '' searching = (request.method == 'POST') or (request.GET.get('s', None)) log.error("def users") if searching: log.error("searching") if request.method == 'POST': log.error("request.method = POST") search_text = request.POST.get('search', None) else: log.error("request.method != POST") search_text = request.GET.get('s', … -
django.db.utils.IntegrityError: FOREIGN KEY constraint failed
I came across with this problem. Frankly speaking I have been trying to fix the situation for 3 days, but all is useless. I believe you can help me with this one. So, the problem looks like this: File "C:\Users\Nikita Shuliak\Desktop\NJB\startup\orders\views.py", line 59, in checkout order = Order.objects.create(user=user, customer_name=name, customer_phone=phone, status_id=1) File "C:\Users\Nikita Shuliak\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django-2.1rc1-py3.7.egg\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) Also I include all necessery pieces of code: models.py class Order(models.Model): user = models.ForeignKey(User, blank=True, null=True, on_delete=models.PROTECT) customer_email = models.EmailField(blank=True, null=True, default=None) customer_name = models.CharField(max_length = 64, blank=True, null=True, default=None) customer_phone = models.CharField(max_length = 48, blank=True, null=True, default=None) customer_address = models.CharField(max_length = 128, blank=True, null=True, default=None) total_price = models.DecimalField(max_digits=10, decimal_places=2, default=0) #total price for all products in order comments = models.TextField(blank=True, null=True, default=None) status = models.ForeignKey(Status, on_delete=models.PROTECT) created = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) def __str__(self): return "Заказ %s %s" % (self.id, self.status.name) class Meta: verbose_name = "Заказ" verbose_name_plural = "Заказы" def save(self, *args, **kwargs): super(Order, self).save(*args, **kwargs) views.py def checkout(request): session_key = request.session.session_key products_in_basket = ProductInBasket.objects.filter(session_key=session_key, is_active=True) form = CheckoutContactForm(request.POST or None) if request.POST: print(request.POST) if form.is_valid(): print("OK") data = request.POST name = data.get("name", "34343434") phone = data["phone"] user, created = User.objects.get_or_create(username=phone, defaults={"first_name": name}) order = … -
Django: Using sessions to pass value from a page to a redirected form field on another page
A page will show photos of cars. When an authenticated user clicks on one, he will be redirected to a page containing a reservation form, where the car that was selected previously will be set by default in a form field. Can I do this without using sessions? How can I put the car_id (or whatever I want to be displayed about the selected car) in the redirected form and also as uneditable? -
i cant figure out 1.11.2 django urls
i made a website with django locally, but i used django 2.0+ so then i went to digitalocean to try deploy it but the django there is 1.11 and switching from path to url made me spend several hours unsuccessfully debugging not working urls. Could you help me with any suggestions that would fix it please, thanks in advance! 1 this is a screenshot of my code -
Submit form from a link outside the form with a variable that the link sends to the form?
I want to submit a hidden form using javascript that is activated from an external link that sends a variable to an input depending on what link is clicked. Link <a title="Go to Store" class="link_pointer" onclick="submit_form('my_emai@gmail.com');">Click Here</a> Form <form id="submit_form" action="{% url "login" %}" method="post"> <input type="text" name="email"/> </form> How can this be achieved using JavaScript where the links have different emails and when you click the link the form is submitted with the input value of the email in the link? -
Django: Display foreignkey object with multiple foreignkey fields on detail view of different model
That title is a mouthful, I hope it is clear. I have three models, PI, Sample, and Publication. In the Sample model, the PI is a foreignkey field. In the Publication model, the Sample is a foreignkey field and the PI is a ManyToMany field. Each of these models has a list view and a detail view. On the PI detail view html page, I can show a table of related samples with {% for p in pi.sample_set.all %}, then hardcode the fields in an html table. This works swimmingly. Using a similar approach, I would also like to show publications that are related to a Sample in the Sample detail view and publications that are related to a PI in the PI detail view. I can provide views, tables, models, and urls if requested. Otherwise here is a bit of code/information. On my PI detail view I have the following: {% for p in pi.publication_set.all %} ... <td><a href="{% url 'sample-detail' p.sample.pk %}">{{ p.sample }}</a> </td> <td><!-- <a href="{#%# url 'pi-detail' p.pi.pk #%#}"> --> {{ p.pi }}</a> </td> <td><a href="{#% url 'publication-detail' p.titlep.pk %#}">{{ p.titlep }}</a> </td> I have defined get_absolute_url methods for each model that are name-adjusted versions … -
Django - custom models' links
MacOS OSX 10.13.6 Django 1.11.3 I have a working Django application with many models: Customer, Product, Shop, etc. They are listed under Admin link in the app. Each model has Change and Add link, e.g. http://localhost:8000/myapp/product/, all the usual stuff. Now I would like all of those model links to point to another place (e.g. http://localhost:8000/myapp/subapp/product/); I would route them to correct views by matching in urlpatterns in urls.py file. Can this be done? Note: FORCE_SCRIPT_NAME setting in settings.py does not change those model links under Admin for me. -
HTML form inputs not working while using Bootstrap template
I have django template called product_queue.html and a header template partials/header.html, which is (mostly) this Bootstrap template. At the current state, the product_queue form won't let me enter anything in the inputs, and the submit button doesn't click. If I remove {% include 'partials/header.html' %} and add the basic html opening, the product_queue form works. What am I missing? product_queue.html: {% include 'partials/header.html' %} <title>Product Queue</title> <div class="container"> <form method="POST" action="/update" name="product_queue"> {% csrf_token %} <h1>Product Queue</h1> <table> <tr> <th><input class="save-button" type="submit" name="save" value="Save"></th> <th><div>Product</div></th> <th><div>Qty Needed</div></th> </tr> {% for product in products %} <tr> <td><div>{{ product.0 }}</div></td> <td><div>{{ product.1 }}</div></td> <td><input type="text" name="qty" class="qty-input"></td> </tr> {% endfor %} </table> </form> </div> <!-- /container --> {% include 'partials/footer.html' %} partials/header.html: {% load static %} <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors"> <meta name="generator" content="Jekyll v3.8.5"> <!-- Bootstrap core CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <style>.bd-placeholder-img {font-size: 1.125rem;text-anchor: middle;}@media (min-width: 768px){.bd-placeholder-img-lg{font-size: 3.5rem;}}</style> <link href="{% static 'css/header.css' %}" rel="stylesheet"> <!-- <link href="css/styles.css" rel="stylesheet"> --> <link rel="shortcut icon" type="image/png" href="{% static 'favicon.ico' %}"/> </head> <body> <nav class="navbar navbar-dark fixed-top bg-dark flex-md-nowrap p-0 shadow"> <a class="navbar-brand … -
Dynamically changing Model data matching outside API
I am grabbing data from JIRA and inserting the data into models in my DJANGO app. What i would like to do is everytime i'm inserting data from JIRA into my models, is to track the change from JIRA to my existing model data. For example.. i have a bug with a status of "Open" right now, and in JIRA it is now on "Closed" and my model data doesn't change with it when i go to insert data (the data set from jira will have the changes of said bug in it) Here is a snippet of my code. model_config.py class DataConfig: def get_json_data(self, url): headers = urllib3.util.make_headers(basic_auth='<username>:<password>') url = url http = urllib3.PoolManager(cert_reqs='CERT_REQUIRED', ca_certs=certifi.where()) request = http.request('GET', url, headers=headers) real_data = json.loads(request.data.decode('utf-8')) return real_data class BugModel(DataConfig): def __init__(self): self.bug_json = DataConfig.get_json_data(self,<JIRA url>) self.insert_bug_data(self.bug_json) def insert_bug_data(self, data): values = list((item['key'], # key item['fields']['customfield_10009'], # name item['fields']['status']['name'] # status ) for item in data['issues']) for bug in values: e = Bug(key=bug[0], name=bug[1], status=bug[2]) e.save() views.py class IndexView(TemplateView): template_name = 'app/index.html' def fill_models(self): BugModel() I do realize that this won't change existing model data from changes in JIRA, how would i go about accomplishing this? -
search all fields in django
I have 5 tables in my model.py and I want so search all of them with one string, i.e compare all fields in a tables with one search string. But I am nt able to find how I can do that. class Person(models.Model): mail=models.EmailField() firstName=models.CharField(max_length=200) lastName=models.CharField(max_length=200) phoneNumber=PhoneNumberField() streetAdress=models.CharField(max_length=200) zipcode=models.CharField(max_length=200) city=models.CharField(max_length=200,default="Göteborg") country=models.CharField(max_length=200,default="Sweden") def __str__(self): return "%s %s" % (self.firstName,self.lastName) class Meta: ordering = ('firstName','lastName') class Role(models.Model): role=models.CharField(max_length=200) person=models.ManyToManyField(Person) def __str__(self): return self.role class Meta: ordering = ('role',) class Name(models.Model): name=models.CharField(max_length=200) role=models.ForeignKey(Role,on_delete=models.CASCADE) def __str__(self): return self.name class Meta: ordering = ('name',) class Address(models.Model): name=models.ForeignKey(Name,on_delete=models.CASCADE) venue=models.CharField(max_length=200,default="Company AB") street=models.CharField(max_length=200) city=models.CharField(max_length=200) mail=models.EmailField() phone=PhoneNumberField(default="") def __str__(self): return str(self.venue) # def __str__(self): # return str(self.phone) class Meta: verbose_name_plural = "addreses" class Meta: ordering = ('name',) class Date(models.Model): date=models.DateField() location=models.ManyToManyField(Address) def __str__(self): return str(self.date) and doing search is done only in the name field: class Search(ListView): print("class Search") model=Person template_name='artdb/search.html' context_object_name='ans' # Pdb().set_trace() def get_queryset(self): q=self.request.GET.get('seastr') if q: qans=firstName__icontains=q return Person.objects.filter(firstName__icontains=q) else: return Person.objects.all() # SELECT ... WHERE headline ILIKE '%Lennon%'; def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['seastr'] = self.request.GET.get('seastr') return context is there anyway to do a search for all tables and fields? like a wildcard search? is there any equivalent wildcard search to __icontains? -
Is a third party package required to download HTML to a Word document in Django or can it be done natively using python?
I am trying to download a DetailView to a word document. Thanks to ruddra in another SO issue I opened up here...How To Narrow Down Django DetailView Export To CSV File can now do it via CSV and no third party packages are required. class ExportDataDetailView(LoginRequiredMixin,DetailView): model = Author context_object_name = 'author_detail' def render_to_response(self, context, **response_kwargs): user = context.get('author_detail') # getting User object from context using context_object_name response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="users.csv"' writer = csv.writer(response) writer.writerow(['username', 'First name', 'Last name', 'Email address']) writer.writerow([user.username, user.first_name, ...]) return response I'm wondering if the same option is available for a Word document. I found a similar question here and ruddra pointed it out to me as well, but it was from 2014...Generate the MS word document in django... from docx import * from docx.shared import Inches def TestDocument(request): document = Document() docx_title="TEST_DOCUMENT.docx" # ---- Cover Letter ---- document.add_picture((r'%s/static/images/my-header.png' % (settings.PROJECT_PATH)), width=Inches(4)) document.add_paragraph() document.add_paragraph("%s" % date.today().strftime('%B %d, %Y')) document.add_paragraph('Dear Sir or Madam:') document.add_paragraph('We are pleased to help you with your widgets.') document.add_paragraph('Please feel free to contact me for any additional information.') document.add_paragraph('I look forward to assisting you in this project.') document.add_paragraph() document.add_paragraph('Best regards,') document.add_paragraph('Acme Specialist 1]') document.add_page_break() # Prepare document for download … -
error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools"
C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools>pip install channels Collecting channels building 'twisted.test.raiser' extension error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": https://visualstudio.microsoft.com/downloads/ ---------------------------------------- Command "c:\users\abdulsalam\appdata\local\programs\python\python36\python.exe -u -c "import setuptools, tokenize;file='C:\Users\ABDULS~1\AppData\Local\Temp\pip-install-4freovpk\twisted\setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record C:\Users\ABDULS~1\AppData\Local\Temp\pip-record-ho0mpwc6\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\ABDULS~1\AppData\Local\Temp\pip-install-4freovpk\twisted\ -
How to return registered objects in a foreign key in Django?
As I show in my code below, I can register a post within a section to which it is assigned (such as "sport", "technology"). I'm going to make a template where I'll sort out all the sections, and as soon as I click on one, all the publications related to that section are returned to me. How can I do this? I'm using Python 3.6 and Django 2.0. My models: class Section(models.Model): section = models.CharField(verbose_name='Section name', max_length=50, blank=False, null=False, unique=True) class Publication(models.Model): section = models.ForeignKey(Section, verbose_name='Section', blank=False, null=False, on_delete=models.CASCADE, related_name='section_choice') title = models.CharField(verbose_name='Publication title', max_length=256, blank=False, null=False, unique=True) -
Windows: Python Daemon Won't Run on IIS but Runs Locally
I have a Django web application hosted on IIS. I subprocess should be consistently running alongside the web application. When I run the application locally using python manage.py runserver the background task runs perfectly while the application is running. However, hosted on IIS the background task does not appear to run. How do I make the task run even when hosted on IIS? In the manage.py file of Django I have the following code: def run_background(): return subprocess.Popen(["python", "background.py"], creationflag=subprocess.CREATE_NEW_PROCESS_GROUP) run_background() execute_from_command_line(sys.argv) I do not know how to resolve this strange issue. -
Docusign API: Tabs Wrongly Applied To Other Documents and Fields
I have been working with Docusign's API for some time now on a project for my company. The purpose is to allow for documents to be signed digitally which can put business processes into action. Recently, I have added a third document that, when a checkbox is checked, a third document is added to the envelope to be signed (this is where the acc = True comes in. However, the issue is that, specifically for this third document, anywhere on the other documents that the anchor string is, the fields get placed, resulting in tabs going not only to unintended fields, but unintended fields on unintended documents. In all of my tabs, I have set the value anchor_match_whole_word = 'true', and in the tabs for the third document, I have set the value document_id = '3'. Below is my code: signer1 = docusign.Signer(email = myClient.email, name = myClient.ainame, recipient_id = '1') signer2 = docusign.Signer(email = "myEmail@gmail.com", name = "Sam Sampleton", recipient_id = '2') sign_here1 = docusign.SignHere(document_id = '1', recipient_id = '1', anchor_horizontal_alignment = 'left', anchor_ignore_if_not_present = 'false', anchor_match_whole_word = 'true', anchor_string = "Signature of individual authorized to act on behalf of customer", anchor_x_offset = ".2", anchor_y_offset = "1.25", anchor_units = … -
Django 2.1.4 Registration Form + Login Page
Hi I am new to Django and need help with registration form and login. I am able to register and able to see the user credentials registered under admin register model. However, i tried to take the user-credentials in the database and then want to do a login, but unable to do so. models.py class register(models.Model): name = models.CharField(max_length=250) username = models.CharField(max_length=20) password = models.CharField(max_length=20) occupation = models.CharField(max_length=100) def __unicode__(self): return str(self.username) Views.py #register def registerForm(request): if request.method == 'POST': if request.POST.get('name') and request.POST.get('username') and request.POST.get('password') and request.POST.get('occupation'): reg = register() reg.name = request.POST['name'] reg.username = request.POST['username'] reg.password = request.POST['password'] reg.occupation = request.POST['occupation'] reg.save() return render(request, 'login.html') else: return render(request, 'register.html') #Login def Login(request): if request.method == 'POST': if request.POST.get('username') and request.POST.get('password'): usr_login = register() usr_login.username = request.POST['username'] usr_login.password = request.POST['password'] usr_login.user = authenticate(username=username, password=password) if usr_login.user: login(request, usr_login.user) return HttpResponseRedirect('/forum/') else: error = "Username and Password are invalid. Please try again." return render(request, 'login.html') else: return render(request, 'login.html') login.html <form method="post" action="/forum/"> {% csrf_token %} <div class="form-group"> <label for="username">Username:</label> <input type="username" class="form-control" id="username" placeholder="Enter username" required="required"> </div> <div class="form-group"> <label for="pwd">Password:</label> <input type="password" class="form-control" id="pwd" placeholder="Enter password" required="required"> </div> <div class="row"> <div class="col" align="center"> <div class="form-group form-check"> <label class="form-check-label"> … -
Tests not being found in a Django project
I'm trying to run tests in a Django project using python migrate.py test, but it doesn't seem to pick up anything. I currently have the following structure: Project dir | - MyProject - myApp - tests | - __init.py__ - test_forms.py - test_integration.py - test_models.py - test_views.py Previously I had the tests folder as a sub folder under myAPp, but the same problem arises, namely that no tests are found: python manage.py test --debug-mode Creating test database for alias 'default'... System check identified no issues (0 silenced). ---------------------------------------------------------------------- Ran 0 tests in 0.000s OK Destroying test database for alias 'default'... There's really very little in the test files at the moment - I just want to get them to run to start with! This is an example: import unittest class TestGeneric(unittest.TestCase): @unittest.skip('Skipping default nothing test for test_views') def test_bugger_all(self): self.fail("Shouldn't get here") if __name__ == '__main__': unittest.main() If I run this with python -m test_views.py, then it works just fine, but from the project root, python manage.py test picks up nothing at all. The tests are named as test_*, as are the .py files. If it's relevant, I'm running in a virtualenv. What am I missing here? -
Unknown email field with custom user
I am trying to create a custom user by following this tutorial. After starting a new project, I add in the below code and run python manage.py makemigrations and receive the following error: File "/Users/me/Desktop/cbv_users/accounts/admin.py", line 8, in <module> from .forms import UserAdminCreationForm, UserAdminChangeForm File "/Users/me/Desktop/cbv_users/accounts/forms.py", line 32, in <module> class UserAdminCreationForm(forms.ModelForm): File "/miniconda3/envs/server/lib/python3.6/site-packages/django/forms/models.py", line 262, in __new__ raise FieldError(message) django.core.exceptions.FieldError: Unknown field(s) (email) specified for User Im very confused where this error is coming from and what I am doing wrong. Any help is greatly appreciated. (note: I already set AUTH_USER_MODEL = 'accounts.User' in settings.py) Also, I am using Django 1.11. models.py # accounts.models.py from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) class User(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) # a admin user; non super-user admin = models.BooleanField(default=False) # a superuser # notice the absence of a "Password field", that's built in. USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] # Email & Password are required by default. def get_full_name(self): # The user is identified by their email address return self.email def get_short_name(self): # The user is identified by their email address return self.email def __str__(self): # __unicode__ on … -
UNIQUE constraint failed: Student_assignments.user_id
I am trying to achieve that Student is Connected to User Assignment is Connected to Student. Django Migrations Issue. django.db.utils.IntegrityError: UNIQUE constraint failed: Student_student.user_id models.py file models.py from django.db import models from django.utils import timezone from django.core.validators import MinLengthValidator,MaxValueValidator from django.contrib.auth.models import User # Create your models here. class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,primary_key=True,default=111111) student_name = models.CharField(max_length = 20) student_address = models.TextField() student_bloodgrp = models.CharField(max_length = 3) #This will be used to upload image of student in some directory not in database student_image = models.ImageField(upload_to ='profile_pic/') student_mail = models.EmailField() student_dob = models.DateTimeField() student_branch = models.CharField(max_length = 3) student_reg_no = models.IntegerField(validators=[MaxValueValidator(9999999999)]) student_mob = models.IntegerField(validators=[MaxValueValidator(9999999999)]) student_sem = models.IntegerField(validators=[MaxValueValidator(8)]) student_accom = models.CharField(max_length = 1) # y for boarders & n for non-boarders class Meta: verbose_name_plural = "Students" class Subjects(models.Model): subjectName = models.CharField(max_length=100,primary_key=True) branch = models.CharField(max_length=100) semester = models.IntegerField() class Meta: verbose_name_plural = "Subjects" def __str__(self): return self.subjectName+"--"+self.branch+"--"+str(self.semester) class Assignments(models.Model): student = models.ForeignKey(Student,on_delete=models.DO_NOTHING) subject = models.ForeignKey(Subjects,on_delete=models.DO_NOTHING) document = models.FileField(upload_to='assignments/') class Meta: verbose_name_plural = "Assignments" def __str__(self): return self.student.student_name forms.py here forms.py from django import forms from .models import Assignments class AssignmentForm(forms.ModelForm): class Meta: model = Assignments fields = ('student', 'document','subject' ) ****************************************************************** views.py here views.py from django.shortcuts import render,redirect from .forms import AssignmentForm from …