Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
You don’t have permission to view or edit anything - only super users is able to do everything
I have a model registered in Django admin. Then I created two users superuser and a normal user. This normal user was given the read and change rights by the superuser @admin.register(News) class NewsAdmin(admin.ModelAdmin): pass What needs to be done? I am using Django 3.2 -
Trying to build a custom Django file upload form field
I am trying to get a file upload form field working in Django and the part I am having problems with is dynamically changing the form field required attribute. I have tried using "self.fields['field_name'].required=True' in the init method of the form but that isn't working for me. I have looked at Django dynamically changing the required property on forms but I don't want to build several custom models and a custom render function for one form as surely it must be easier than that. The reason I am trying to do this is because when a django form validates and has errors it doesn't pass any uploaded files back to the browser form for reediting. It will pass text areas and text inputs that didn't validate back to the form for reediting but not file uploads. I thought if I made the file upload fields mandatory for the first time the record is created mandatory and for subsequent times make them optional. That is basically what I am trying to do. -
heroku error when trying to create superuser
I'm a beginner to Django and am trying to create my app w/ Heroku however I'm stuck on this error: sqlite3.OperationalError: no such table: auth_user Error I have seen some information on heroku not being able to use sqllite so I've been trying to update to postgres but not sure why that's not reflected here. settings.py DB Any help would be greatly appreciated! -
Python: How to send terminal output to html
I am currently working on a project using OpenCV, I have it so the program detects circles in a live video and outputs the amount of circles into the terminal every 10 seconds using (len(circles[0, :])), and time.sleep(10) I would now like to send this data to my html file (using eel) but i am not sure how to do this, aswell as having it automatically updating every 10 seconds i heard that you can use packages such as django and flask but i have been trying them all and none seem to work.. any help/advice would be appreciated, thanks! -
Django Rest Framework Endpoint Request Fails with Error Cross-Origin Request Blocked
I have a django rest application back end with an angular front end. All the endpoints work perfectly locally but when I deploy it to google cloud all endpoints works except one which keeps on displaying the error Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at url (Reason: CORS request did not succeed). I have tried to connect the database on the cloud with the local application, all the endpoints requests are displayed on the IDE console except the one, and the browser displays the request is not yet finished. Any ideas on what is causing the issue will be highly appreciated -
How do you take an id from a django model form, use it as the url, and get all the data from that value from the form?
I am doing CS50 Project 2 and need to make a webpage that takes in the id through the url and retrieves all of the information about that particular item from the database to display on the webpage. def listing(request, id): id = Listings.objects.get(id=2) return render(request, "auctions/listing.html",{ "listings": Listings.objects.all() }) This is my current code. I am trying to get the id that is in the url parameter through the variable, and I want the listings variable to only get the objects for that item, but I am not exactly sure how to do that. Let me know if you need any more of the code. Thank you so much for all your help! -
Manipulate multiple forms generated with an input value in Django
I want to manipulate mltiple forms according to an input value. I use the code below to generate a number of forms : $(function() { var input = $('<div><br><table class="form-table">\ <tr>\ <td><label for="type">Type</label></td>\ <td>\ <select name="type" id="type">\ <option value="">----- Choose Type -----</option>\ <option value="A">Service</option>\ <option value="B">Supply</option>\ <option value="C">Work</option>\ </select>\ </td>\ </tr>\ <tr>\ <td><label for="serviceStartDate">Start Date</label></td>\ <td><input type="date" id="serviceStartDate" name="serviceStartDate"></td>\ </tr>\ <tr>\ <td><label for="serviceEndDate">End Date</label></td>\ <td><input type="date" id="serviceEndDate" name="serviceEndDate"></td>\ </tr>\ <tr>\ <td><label for="serviceContract">Contract</label></td>\ <td><input type="file" id="serviceContract" name="serviceContract"></td>\ </tr>\ <tr>\ <td><label for="serviceClassOrder">Class Order</label></td>\ <td><input type="file" id="serviceClassOrder" name="serviceClassOrder"></td>\ </tr>\ <tr>\ <td><label for="serviceAcceptanceReport">Acceptance Report</label></td>\ <td><input type="file" id="serviceAcceptanceReport" name="serviceAcceptanceReport"></td>\ </tr>\ </table><br><hr></div>'); var newFields = $(''); And this is my view : def becomePartner(request): if request.method=="POST": if request.FILES['serviceContract'] or request.FILES['serviceClassOrder'] or request.FILES['serviceAcceptanceReport']: type = request.POST['type'] start_date = request.POST['serviceStartDate'] end_date = request.POST['serviceEndDate'] contract = Contract.objects.create(start_date=start_date, end_date=end_date, type=type, client=partnerClient) if request.FILES['serviceContract']: Document.objects.create(type='A', file=request.FILES['serviceContract'], contract=contract) if request.FILES['serviceClassOrder']: Document.objects.create(type='B', file=request.FILES['serviceClassOrder'], contract=contract) if request.FILES['serviceAcceptanceReport']: Document.objects.create(type='C', file=request.FILES['serviceAcceptanceReport'], contract=contract) return redirect('/ClientManagement') When I submit , It manipulates just the last form ,and I want to manipulate all the forms. How Can I solve this ? -
How to have multiple dynamic forms on the same page?
I have multiple of the same inline formsets on the same page. On other pages I already have a single formset with dynamic "add" and "remove" buttons. However the javascript starts acting strange and I am unable to reuse variables among the different inline formsets. In order to have a single dynamic from I am using: <script> document.addEventListener('click', (event) => { if (event.target.id === "add") { add_form(event) } if (event.target.id === "remove") { remove_form(event) } }) function add_form(event) { if (event) { event.preventDefault() } const totalNewForms = document.getElementById('id_form-TOTAL_FORMS') const currentForms = document.getElementsByClassName('form') const currentFormCount = currentForms.length // + 1 const formCopyTarget = document.getElementById('formset') const copyEmptyFormEl = document.getElementById('empty-form').cloneNode(true) copyEmptyFormEl.setAttribute('class', 'form') copyEmptyFormEl.setAttribute('id', `form-${currentFormCount}`) const regex = new RegExp('__prefix__', 'g') copyEmptyFormEl.innerHTML = copyEmptyFormEl.innerHTML.replace(regex, currentFormCount) totalNewForms.setAttribute('value', currentFormCount + 1) // now add new empty form element to our html form formCopyTarget.append(copyEmptyFormEl) } function remove_form(event) { if (event) { event.preventDefault() } const totalNewForms = document.getElementById('id_form-TOTAL_FORMS') const currentForms = document.getElementsByClassName('form') const currentFormCount = currentForms.length //const regex = new RegExp(`id_form-${currentFormCount-1}`) const deleteFormTarget = document.getElementById(`form-${currentFormCount - 1}`) totalNewForms.setAttribute('value', currentFormCount - 1) deleteFormTarget.outerHTML = ""; } </script> I have attempted to create django context variables that are unique to each inline formset (all same parent model, different child model). … -
Is there away to encapsuate the context of a django template in one place?
I have a template file for the header of a website which will be included in all pages, it takes a list as a context and renders items based on that list as follows: {% for category in categories %} <li><a class='text-primary' href=" {% url 'category-url' category.id%}">{{category.name | title}}</a></li> {% endfor %} Now my problem is that every view that renders any page in the website needs to pass the categories list in order for the header to work (the header is included in all pages). and thus almost all of my views have this code return render(request, ..., 'categories':Category.objects.all()) so is there away to have a code that passes the categories to the header once and just rely on that for every other view? -
Is it better to have an explicit django model field or calculate on demand?
If I have a django model that has an field called 'order' (integer field that tracks the modifiable order of a specific model instance amongst all model instances), and I also want to track the position of the model instance based on that order ('first'/'mid'/'last'), is it better to have another model field called 'position', which I recalculate and store each time there is a change to order, or should I have a model method called 'get_position' which I call each time I need a position. I'm trying to work out which is more efficient. Whilst I won't need the position information each time I create/delete/modify a instance order, I will need that position field quite a bit within my templates. -
Django Resize Image Before Saving
Goal: Upload a resized image (with same file name and aspect ratio) to AWS S3. Problem: Currently upon saving, the original image is uploaded and not the resized one. What have I tried?: I've tried multiple different ways to accomplish this but I run into various issues such as not the correct aspect ratio, poor image quality (when using django-resize) etc. The code below seems really close but I just can't seem to find where I am going wrong. models.py class Profile(BaseModel): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def save(self, commit=True, *args, **kwargs): #Edited if commit: img = Image.open(self.image) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.name, optimize=True, quality=100) super().save() -
Get request with django returns None for the user
I'm trying to get the details of the user who makes a get request in django. I'm using postman to perform the get request but when I try to print request.user and type(request.user): #In the view class SomeView(APIView): .... .... def get(self, request, pk, format=None): print(f'request: {request.user}, {type(request.user)') I get None and None for the user and the type. I've looked though many stackoverflow posts but I'm struggling finding out the reason. From: Django username is empty in a GET request https://www.django-rest-framework.org/api-guide/authentication/ I thought perhaps I'm not performing the get request with a user, but if that is the case, I should be getting an Anonymous object as the type for user right? But instead it's telling me it's None I should mention from postman I'm under the Authorization tab, I've tried using a Bearer Token which I know I had the correct token as well as (separately) using basic auth by having the username and the password. Either method results in request.user being None. If I just print out request I get: <rest_framework.request.Request: GET '/test/number/33574677/'>, I'm not sure what the issue here is, does it have something to do with the way I'm using postman to send the request? … -
Django - strange browser behavior cause broken pipe
I noticed a strange behavior for a long time that cause my server do extra work. For Safari browser. Whenever you touch the address bar and start to edit the existing URL, the browser sends the same get request to the server and close the connection before the server return the response. When you finish editing the address and hit enter it will send the new request. This behavior can happen multiple times while you edit your URL in the address bar. This cause the server to fully process the response and when it return the result it through Broken pipe. This happen on both cases for DEBUG = True/False. So I can see it on local debug server and I can see a request happening on my NGINX production server. Is there a way to identify this request so to not serve results and save the server processing power? Thanks -
DisallowedHost at /admin -- Django, Gunicorn, NGINX -- Error first showed when changed to HTTPS only instead of just HTTP
This is a screenshot of the error when you access my domain, insa-analytics.com/admin Here is a text dump of that image for those who cannot access the image: DisallowedHost at /admin Invalid HTTP_HOST header: 'insa-analytics.com'. You may need to add 'insa-analytics.com' to ALLOWED_HOSTS. Request Method: GET Request URL: http://insa-analytics.com/admin Django Version: 4.0.2 Exception Type: DisallowedHost Exception Value: Invalid HTTP_HOST header: 'insa-analytics.com'. You may need to add 'insa-analytics.com' to ALLOWED_HOSTS. Exception Location: /usr/local/lib/python3.8/dist-packages/django/http/request.py, line 135, in get_host Python Executable: /usr/bin/python3 Python Version: 3.8.10 Python Path: ['/home/django/django_project', '/usr/bin', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/usr/local/lib/python3.8/dist-packages', '/usr/lib/python3/dist-packages'] Server time: Mon, 18 Apr 2022 22:33:43 +0000 The /admin is the administrator control panel for the Django service. Previously, this webserver was working perfectly via HTTP (no SSL, 80 instead of 443). When I used certbot with letsencrypt to generate and configure an SSL certificate -- this issue came into play. Note that I redirect all HTTP connections to HTTPS. My webservice will be only accessible over 443. settings.py: """ Django settings for django_project project. Generated by 'django-admin startproject' using Django 2.2.12. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os import netifaces # Build … -
How to upload files with DRF and React?
I'm learning Django Rest Framework, everything was going well until I had to create a service to upload files to my application.As much as I read the documentation, I can't understand it. First I want to clarify that I am not a programming expert, I am a newbie but I am here learning more every day. From what I've managed to understand so far: Documents and photos are not stored in the database. These files are stored in a folder. This is correct ? I have a form where it allows me to upload multiple files example: file.txt, document.doc, photo.png etc... My view (Frontend): import { useState } from "react"; import axios from "axios"; const Form = () => { const [state_files, setState_Files] = useState(null); const UploadFiles = function (event) { setState_Files(event); }; const InsertFiles = async function () { const formData = new FormData(); for (let index = 0; index < state_files.length; index++) { formData.append("files", state_files[index]); } await axios .post("http://127.0.0.1:8000/api/v1/upload/", formData) .then((response) => { console.log(response.data); }) .catch((error) => { console.log(error); }); }; return ( <> <input type="file" name="files" multiple onChange={() => InsertFiles(event.target.files)} /> <button>Upload All files</button> </> ); }; export default Form; Backend url.py path("upload/", Storage_View.as_view(), name="storage-index"), storage/view.py from … -
Django WebSockets
I want to send the connected user list from my Comment Consumer class to ListTicket consumer. Just want to show the connected user name in each room on the main page of the application. ListTicketConsumer class: class ListTicketConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = 'list_ticket' # Join room group await self.channel_layer.group_add( self.room_name, self.channel_name, ) await self.accept() async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.room_name, self.channel_name ) async def update_table(self, event): comment = event['comment'] await self.send(text_data = json.dumps({ 'comment' : comment })) async def send_userinit(self, event): print('---user in func----') userinit = event['userinit'] id = event['ticket_id'] print(userinit, 'user in func----') await self.send(text_data = json.dumps({ 'ticket_id' : id, 'userinit' : userinit })) CommentConsumer class: class CommentConsumer(AsyncWebsocketConsumer): async def connect(self): self.comment_room = self.scope['url_route']['kwargs']['comment_room'] user_list.append(self.scope["session"]["userinit"]) # Join room group await self.channel_layer.group_add( self.comment_room, self.channel_name, ) channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send( 'list_ticket', {'type': 'send_userinit', 'ticket_id' : id,'userinit': user_list} )) print(user_list) await self.accept() async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.comment_room, self.channel_name ) user_list.remove(self.scope["session"]["userinit"]) channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send( 'list_ticket', {'type': 'send_userinit', 'ticket_id' : id,'userinit': user_list} )) print(user_list) This is what I'm trying to do, but it's not working, if anybody knows Please Help. -
Django - Filter Queryset With Another Modal's Field
I have two modals: Group and GroupContents. GroupContents Modal: class GroupContents(models.Model): group = models.ForeignKey(Group, on_delete=models.CASCADE, null=True, blank=True) content= models.TextField(max_length=180) Group Modal: class Group(models.Model): name = models.CharField(max_length=255, unique=True) description = models.TextField(blank=True, max_length=80, default='') private= models.TextField(blank=False, default='0') I want to filter my GroupContents queryset as releated Group object not private. I don't know how to solve that. I tried this but didn't work: class GroupContentsViewSet(viewsets.ModelViewSet): serializer_class = GroupContentsSerializer authentication_classes = (JSONWebTokenAuthentication,) permission_classes = (IsAuthenticatedOrReadOnly,) def get_queryset(self): queryset = GroupContents.objects.filter(self.group.secret=0) return queryset I don't know how to approach. Thanks a lot... -
Ajax response into django
I have a map with some markers on them and im using AJAX to bring up the latest measures from the database. Problem is when i assign my called information it messes up with the marker positioning . If i put the Popup outside of the ajax call i cant access my measurements. If i assign them in my ajax call it ruins the gui but i get the correct results. for (i in motePos) { mote[i] = L.marker(motePos[i], { icon: SensorIcon }); mote[i].name = motePosName[i]; mote[i].id = motePosId[i]; markers.addLayer(mote[i].on('click', function(e) { alert(this.id); var sID = this.id; $.ajax({ type : 'GET', url : "{% url 'agriculture:sensor_ms' %}", data : {"sID" : sID}, success: function(response){ var measurement = JSON.parse(response["measurement"]); var fields = measurement[0]["fields"]; console.log(fields) var sensorID = "href='{% url 'agriculture:tree_sensor' 12345 %}'"; var url_mask = sensorID.replace("12345", fields["sensor"]); mote[i].bindPopup("<h3>Tree Sensor: " + motePosName[i] + "</h3>" + "<hr>" + "Soil Moisture (50 cm): " + fields["soil_moisture_depth_1"] + "cbar" + "<br>" + "<b>Soil Moisture (20 cm): " + fields["soil_moisture_depth_2"] + "cbar" + "<br>" + "Temperature: " + fields["soil_temperature"] + "°C" + "<br>" + "<br><a class='popup_button small_text' "+url_mask+" ><span>Sensor Page</span></a>").openPopup(); } }) })); } map.addLayer(markers); view : def Sensor_Measurements(request): if request.is_ajax and request.method == "GET" … -
Need help adding a count to the queryset model
Im trying to add a count to the following queryset code in django. query.communityRating = int(query.communityRating) + value query.communityCount = query.communityCount + 1 query.save() and then when we pass the score, to the template if query.communityRating != 0: comRating = query.communityRating / query.communityCount else: comRating = query.communityRating -
Getting the error <class 'blog_app.admin.RequestDemoAdmin'>: (admin.E109) The value of 'list_display[6]' must not be a ManyToManyField
I have been getting this error when trying to migrate my models. However, i am getting this error <class 'blog_app.admin.RequestDemoAdmin'>: (admin.E109) The value of 'list_display[6]' must not be a ManyToManyField. Any help would be much appreciated. models.py from django.db import models from taggit.managers import TaggableManager # Create your models here. class IpModel(models.Model): ip = models.CharField(max_length=100) def __str__(self): return self.ip class Blog_Post(models.Model): slug = models.SlugField(max_length=1000, editable=False, null=True) post_title = models.CharField(max_length=100, editable=True, blank=False, null=True) blog_content = models.TextField(max_length=10000, blank=False, editable=True, null=True) files = models.FileField(blank=True, null=True, upload_to=True) date = models.DateTimeField(blank=False, null=True, auto_now=True, editable=False) likes = models.ManyToManyField(IpModel, related_name="post_likes", blank=True) def save(self, *args, **kwargs): self.slug = self.slug super().save(*args, **kwargs) def total_likes(self): return self.likes.count() -
How to inherit a django class method from views.py into tasks.py to schedule jobs with Celery
I am trying in django with Celery to schedule jobs. The problem is that i cannot make my @shared_task function in tasks.py inherit the class method from views.py. I installed Celery together with Flower and Beat, and the configuration is working well when i write just a standalone function in tasks.py. Do you have any suggestions how to solve this inheritance challenge? Thanks for your help. my views.py from rest_framework import generics from .serializers import TickerSerializer from ticker.models import Ticker import requests import logging from itertools import chain from importlib import reload import sys logger = logging.getLogger(__name__) class TickerList(generics.ListAPIView): serializer_class = TickerSerializer queryset = Ticker.objects.all() class TickerRetrieve(generics.RetrieveAPIView): serializer_class = TickerSerializer queryset = Ticker.objects.all() lookup_field = 'id' def get_object(request, **args): url = 'https://api.kraken.com/0/public/Ticker?pair=1INCHEUR,1INCHUSD' response = requests.get(url) data = response.json() Ticker.objects.all().delete() for key in data['result']: if isinstance(data['result'][key], int): continue crypto_data =data['result'][key] ticker_data = Ticker(crypto = (key), a_0 = (crypto_data.get('a')[0]), a_1 = (crypto_data.get('a')[1]), ) ticker_data.save() my tasks.py from __future__ import absolute_import, unicode_literals from celery.utils.log import get_task_logger import sys from celery import shared_task from ticker.views import TickerRetrieve from django.core.management import call_command a = TickerRetrieve() @shared_task(name="updatemy_ticker") def updatemy_ticker_task(ticker_data): return a.get_object(ticker_data) The Flower and the local servers show the scheduled tasks working without bugs, however i … -
django multitenant architecture options: what influence on database performance?
I m designing a website where security of data is an issue. I ve read this book : https://books.agiliq.com/projects/django-multi-tenant/en/latest/index.html I'm still thinking about the right database structure for users. And im hesitating between shared database with isolated schemas, isolated databases in a shared app, or completely isolated tenants using docker. As security of data is an issue, i would like to avoid to put all the users in the same table in the database or in different schemas in the same database. However i dont understand well if i should put each user in a separate database (create a database per user, sqlite for example but i dont know if it would communicate well with postgres). What is the best practice for this in terms of security? Im wondering how these options affect database speed compared to a shared database with a shared schema, which was the basic configuration of the course i attended on django. I dont have good knowledge on databases so your help on the performance issue would be very appreciated! Also, if I want to do some stats and use tenants data, how difficult is it to query completely isolated tenants using docker or isolated databases, … -
Django rest framework: Unit testing post request gets status code 400
I'm doing some unit tests in this restaurant app, and the API request to cancel orders returns code 400 when running "manage.py test" command, but doing the same request on Postman works fine (with the server also running on my local machine with the "manage.py runserver" command). I think it's something I'm doing wrong with the unit test, but I'm not sure. In settings, Debug = True and ALLOWED_HOSTS = ['*'] (but I also tried ALLOWED_HOSTS = []). Here's the code: tests.py class CancelOrderAPITest(APITestCase): def setUp(self): test_product = Products.objects.create(id=1, name='testProduct', description='-test-', price=2.56) test_product.save() test_order = Order.objects.create(table=1, status='WA') test_order.save() test_order.product.add(test_product) self.user = User.objects.create(username='test') self.user.set_password('passtest') self.user.save() Payments.objects.create(value=0.0, user=self.user) Token.objects.create(user=self.user) def test_CancelWithCredentials(self): check_login = self.client.login(username='test', password='passtest') self.assertTrue(check_login) token = Token.objects.get_or_create(user=self.user) self.client.credentials(HTTP_AUTHORIZATION=f'Token {token[0].key}') data = {"table": 1} order = Order.objects.filter(table=data['table']).order_by('date')[0] response = self.client.post(reverse('cancel-order'), data=data, content_type='application/json') self.assertEqual(response.status_code, status.HTTP_200_OK) # returning 400. Investigate further self.assertEqual(order.status, Order.Status.CANCELED) views.py class CancelOrder(APIView): # REST API view for waiters to cancel orders. The waiter must be an authenticated user permission_classes = (IsAuthenticated,) parser_classes = (JSONParser,) def post(self, request): data = request.data try: order = Order.objects.filter(table=data['table']).order_by('date')[0] order.status = Order.Status.CANCELED order.save() resp = {"status": "Order canceled!"} except ObjectDoesNotExist: resp = {"exception": "Couldn't find requested product!"} return Response(resp) models.py class Order(models.Model): class Status(models.TextChoices): … -
Can I obfuscate CSS class names in Django?
I'm currently using "Django Compressor" to compress HTML, JS, and CSS files. These are the filters I use COMPRESS_FILTERS = { 'css': ['compressor.filters.yuglify.YUglifyCSSFilter'], 'js': ['compressor.filters.yuglify.YUglifyJSFilter'] } I really like the way it obfuscates my variables in js files. I don't know is it possible to obfuscate class names in CSS files too? -
The value of 'list_display[0]' refers to 'answer_text', which is not a callable when using TabularInline
I am new to Django and making my Quiz app. Unfortunately I face The value of 'list_display[0]' refers to 'answer_text', which is not a callable error while registering my models on the admin.py. Here are the codes models.py from django.db import models from django.utils.translation import gettext_lazy as _ class Category(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class Updated(models.Model): date_updated = models.DateTimeField(auto_now=True) class Meta: abstract = True class Quizzes(models.Model): class Meta: verbose_name = _("Quizz") verbose_name_plural = _("Quizzes") ordering = ['id'] category = models.ForeignKey( Category, default=1, on_delete=models.DO_NOTHING) title = models.CharField(max_length=255, default=( 'New Quiz'), verbose_name=_('Quiz Title')) date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Updated(models.Model): date_updated = models.DateTimeField( verbose_name=_("Last Updated"), auto_now=True) class Meta: abstract = True class Question(Updated): class Meta: verbose_name = _("Quizz") verbose_name_plural = _("Quizzes") ordering = ['id'] SCALE = ( (0, _('Fundamental')), (1, _('Beginner')), (2, _('Intermediate')), (3, _('Advanced')), (4, _('Expert')), ) TYPE = ( (0, _('Multiple Choice')), ) quiz = models.ForeignKey( Quizzes, related_name='questions', on_delete=models.DO_NOTHING) technique = models.IntegerField(verbose_name=_( "Type of Question"), choices=TYPE, default=0) title = models.CharField(verbose_name=_('Title'), max_length=255) difficulty = models.IntegerField(verbose_name=_( "Difficulty"), choices=SCALE, default=0) date_created = models.DateTimeField( auto_now_add=True, verbose_name=_('Date Created')) is_active = models.BooleanField( default=False, verbose_name=_('Active Status')) def __str__(self): return self.title class Answer(Updated): question = models.ForeignKey( Question, related_name='answers', on_delete=models.DO_NOTHING) class Meta: verbose_name = …