Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Cant creat file on desktop after hosting
I have hosted my app i have a problem with the access to desktop my django app can not creat the certain directory this problem appear only when i hosted the app befor that in the local server the file was created also in the python-anywhere i cant not find any file -
Django reset password email not sent
I'm using default django for reset my user password. Strange thing is i can send email in my code, i receive them. BUT only for the reset password from django i never receive email ... My django version is Django==3.1.2 Django settings: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER ='****@gmail.com' EMAIL_HOST_PASSWORD = '*****' My django URL : path('password_reset/', auth_views.PasswordResetView.as_view(), name='password_reset'), path('password_reset/done/', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('reset/done/', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), The HTML : <form class="form"> {% csrf_token %} {{ form.as_p }} <div class="form-group"> <button type="submit" class="btn btn-pill btn-outline-white font-weight-bold opacity-90 px-15 py-3 m-2">Reset</button> </div> </form> When i click on reset button the URL of the page changed to : http://localhost:8000/password_reset/?csrfmiddlewaretoken=MY_TOKEN&email=*******%40hotmail.com And server send : I can send email using django shell, it's working. I also tried to check if user has is_active True and if user has usable password: [(u.email, u.is_active, u.has_usable_password()) for u in get_user_model().objects.all()] I got : [('******', True, True), ('****', True, True), ('****', True, True), ('*****', True, True)] -
Django Python: Image Upload is not working not working
I am working on a Social Media Website, the base code is from an Open Source Project on GitHub. On the base project you can only post text. I was looking around the Internet and found a instruction to implement img upload. But it doesn't work, because i get a lot of error codes. Error Code: AttributeError: module 'django.forms' has no attribute 'Post' my Code: forms.py from django import forms from django.forms import fields from .models import Post, Comment class Post(forms.Post): class Meta: model = Post fields = ['name', 'Main_Img'] posts.py """ Home page with all posts """ def first(request): context = { 'posts':Post.objects.all() } return render(request, 'blog/first.html', context) """ Posts of following user profiles """ @login_required def posts_of_following_profiles(request): profile = Profile.objects.get(user = request.user) users = [user for user in profile.following.all()] posts = [] qs = None for u in users: p = Profile.objects.get(user=u) p_posts = p.user.post_set.all() posts.append(p_posts) my_posts = profile.profile_posts() posts.append(my_posts) if len(posts)>0: qs = sorted(chain(*posts), reverse=True, key=lambda obj:obj.date_posted) paginator = Paginator(qs, 50) page = request.GET.get('page') try: posts_list = paginator.page(page) except PageNotAnInteger: posts_list = paginator.page(1) except EmptyPage: posts_list = paginator.page(paginator.num_pages) return render(request,'blog/feeds.html',{'profile':profile,'posts':posts_list}) urls.py urlpatterns = [...] if settings.DEBUG: urlpatterns += static (settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) models.py """ Post model … -
How to import a random model from DB in Django
I am trying to teach myself Django and in doing so I am trying to recreate the popular Wordle game. To start I created a Model named 'Words' which contains 5 letter words. I am trying to generate one of those random words into my views.py where I can then have the user start attempting to guess the word. This is my first time asking a question in stack overflow so I will try and display what I have so far the best I can. Currently in my: Views.py from django.shortcuts import render from .models import Words def home(request): word = random.choice(Words) context = {'word', word} return render(request,'home.html', context) ----- I understand word = random.choice(Words) is not possible, What is the best way to do this? Models.py from django.db import models class Words(models.Model): word = models.CharField(max_length=5) def __str__(self): return self.word -
When to use Lazy translation in Django
When are lazy translated string objects required in Django? From the documentation they say option values like verbose_name and help_text are required to be lazy translated. What about other options like related_name and through? What is the purpose of lazy translating the options verbose_name and help_text? What is the significance of lazy translation for fields being class-level attributes? These functions store a lazy reference to the string – not the actual translation. The translation itself will be done when the string is used in a string context, such as in template rendering. This is essential when calls to these functions are located in code paths that are executed at module load time. This is something that can easily happen when defining models, forms and model forms, because Django implements these such that their fields are actually class-level attributes. For that reason, make sure to use lazy translations in the following cases: class Course(models.Model): def __str__(self): return self.title title = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') subscribers = models.ManyToManyField(User, through='Subscription') class MyThing(models.Model): kind = models.ForeignKey( ThingKind, on_delete=models.CASCADE, related_name='kinds', verbose_name=_('kind'), ) -
Problem importing data using django-import-export error NOT NULL constraint failed:
I have set up the django-import-export application in my project and have been trying to import data from an Excel spreadsheet but no luck in getting it to work. I deleted my migration files and data base and generated them again to see if that helped but still the same error. models.py: from django.db import models # Create your models here. class logTimes(models.Model): fast_finished = models.BooleanField(default=False) start_date_time = models.DateTimeField('start fast') end_date_time = models.DateTimeField('end fast') 0001_initial.py: # Generated by Django 4.0.4 on 2022-07-13 22:14 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='logTimes', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('fast_finished', models.BooleanField(default=False)), ('start_date_time', models.DateTimeField(verbose_name='start fast')), ('end_date_time', models.DateTimeField(verbose_name='end fast')), ], ), ] admin.py: from import_export.admin import ImportExportModelAdmin from django.contrib import admin from .models import logTimes @admin.register(logTimes) class logTimesAdmin(ImportExportModelAdmin): pass Line 1 and 2 from my spreadsheet: The error message in the admin site when attempting import: Line number: 1 - NOT NULL constraint failed: startandstoptimes_logtimes.start_date_time True, 05/08/2018 17:15:00, 06/08/2018 13:30:00, None Traceback (most recent call last): File "C:\Users\rlead\anaconda3\lib\site-packages\django\db\backends\utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "C:\Users\rlead\anaconda3\lib\site-packages\django\db\backends\sqlite3\base.py", line 477, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: NOT NULL constraint failed: startandstoptimes_logtimes.start_date_time The above … -
Multiple models and one serializer
I have one main model called Profile and three with relation OneToOne to the main model(ProfileFacebook, ProfileGoogle, ProfileTwitter). I would like to create ProfileSerializer, and depending of the request it will give the correct data from specific model and table. class Profile(models.Model): active = models.BooleanField(blank=True, null=True) address = models.CharField(max_length=32, null=True, blank=True) status = models.CharField(max_length=255, blank=True) category = models.CharField(max_length=255, blank=True) preferences = models.CharField(max_length=255, blank=True) class ProfileFacebook(models.Model): profile = models.OneToOneField(Profile, related_name='profile_facebook', on_delete=models.CASCADE) account_uid = models.CharField(max_length=50, blank=True) secret = models.CharField(max_length=50, blank=True) passphrase = models.CharField(max_length=50, blank=True) class ProfileGoogle(models.Model): profile = models.OneToOneField(Profile, related_name='profile_google', on_delete=models.CASCADE) account_uid = models.CharField(max_length=50, blank=True) secret = models.CharField(max_length=50, blank=True) passphrase = models.CharField(max_length=50, blank=True) class ProfileTwitter(models.Model): profile = models.OneToOneField(Profile, related_name='profile_twitter', on_delete=models.CASCADE) account_uid = models.CharField(max_length=50, blank=True) secret = models.CharField(max_length=50, blank=True) passphrase = models.CharField(max_length=50, blank=True) class ProfileSerializer(serializers.ModelSerializer): class Meta(BaseMeta): class Meta(BaseMeta): model = Profile fields = ( 'active', 'address', 'status', 'category', 'preferences' ) profile_fields = ('account_uid', 'secret', 'passphrase') -
How do I append an input from a form in a html template a url?
I have a search bar on my homepage (http://127.0.0.1:8000/wiki/) where I want users to be able to search for entries and be shown the entry through the url. So, if the user searched for css in the search bar, they would be redirected to /wiki/css (/wiki needs to be kept the same). When something is searched the url stays the same, so it is not redirected or might have been redirected to the same page. How do I append the search term to the url without using a different url? HTML: <h2>Wiki</h2> <form action="/wiki/" method="post"> {% csrf_token %} <input class="search" type="text" name="q" placeholder="Search Encyclopedia"> </form> urls.py: urlpatterns = [ ... path('<str:name>', views.wiki_lookup, name='wiki-lookup'), ] views.py: from django.shortcuts import render, redirect, HttpResponse def wiki_lookup(request): term = request.POST.get('q', 'notfound') return redirect('entry', name=term) -
Run command when worker starts on Heroku-Django
I have a Django app running on Heroku, wich consist in a web process and a worker process (running django background tasks library). My Procfile looks like this: web: gunicorn search.wsgi --log-file - worker: python manage.py process_tasks I need to run a Python management command when worker starts(and not when the web process starts), to check some issues related to the daily dyno restart of Heroku. Specifically, when worker restarts, I need to run python manage.py somescript.py, and then python manage.py process_taks (the command that starts the worker as needed by DJB library). How can I achieve this? Is there any way to run two or more commands per process in the procfile? Thanks in advance! -
Style sheets refusing to load on the browser
I have downloaded an html template online. And I have gone ahead and pasted the index.html to my templates folder, and the assets to my static files, and I have placed the '{% load static %)' tag inside my index file. Here is a snippet of the index.html {% load static %} <!DOCTYPE html> <html class="no-js" lang="zxx"> <head> <meta charset="utf-8" /> <meta http-equiv="x-ua-compatible" content="ie=edge" /> <title>ClassiGrids - Classified Ads and Listing Website Template.</title> <meta name="description" content="" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="shortcut icon" type="image/x-icon" href="{% static 'assets/images/favicon.svg' %}" /> <!-- Place favicon.ico in the root directory --> <!-- Web Font --> <link href="https://fonts.googleapis.com/css2?family=Jost:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css2?family=Lato&display=swap" rel="stylesheet"> <!-- ========================= CSS here ========================= --> <link rel="stylesheet" href="{% static 'assets/css/bootstrap.min.css' %}" /> <link rel="stylesheet" href="{% static 'assets/css/LineIcons.2.0.css' %}" /> <link rel="stylesheet" href="{% static 'assets/css/animate.css' %}" /> <link rel="stylesheet" href="{% static 'assets/css/tiny-slider.css' %}" /> <link rel="stylesheet" href="{% static 'assets/css/glightbox.min.css' %}" /> <link rel="stylesheet" href="{% static 'assets/css/main.css' %}" /> </head> <body> <!--[if lte IE 9]> <p class="browserupgrade"> You are using an <strong>outdated</strong> browser. Please <a href="https://browsehappy.com/">upgrade your browser</a> to improve your experience and security. </p> <![endif]--> <!-- Preloader --> <div class="preloader"> <div class="preloader-inner"> <div class="preloader-icon"> <span></span> <span></span> </div> </div> </div> <!-- /End … -
Django Quiz Application Storing User responses
I am creating a Django quiz application where there will be monthly quizzes. So suppose there will be a quiz for July and there will be a quiz for august. Now let's assume that we have a user who is named "Sovit". Now let's say each quiz has 42 questions. so I want to store each response that the user has chosen somewhere in the database. So like For the July test all 42 responses must be stored somewhere and the same again for august. Right Now I am thinking of having a JSON file associated with the user and then storing the responses of each quiz inside that. What it will help me do is get the data in JSON format for data analysis purposes . But I am not really liking this method of storing the responses. What could be wrong with this design? Is there any other method that I can try? current models : class Quiz(models.Model): id = models.AutoField(primary_key=True) quiz_name = models.CharField(max_length=500) month = models.CharField(max_length=250,null=True,blank=True) year = models.CharField(max_length=250,null=True,blank=True) def __str__(self): return self.quiz_name+"-"+str(self.month)+"-"+str(self.year) def save(self,*args,**kwargs): if not self.quiz_name: self.quiz_name = self.quiz_name+"-"+str(self.month)+"-"+str(self.year) super(Quiz,self).save(*args,**kwargs) class Question(models.Model): id = models.AutoField(primary_key=True) question = models.CharField(max_length=500) quiz = models.ForeignKey(Quiz,on_delete=models.CASCADE) month = models.CharField(max_length=250,null=True,blank=True) year … -
modify max_length models python django
I'm working on a python-django project. If a have a class where one of its attributes have max_length=100 how can I change to max_length=5000 ? for instance... Thank you! -
How do I pass a single value from a React front-end to a Django views file to use for filtering?
I'm currently trying to pass a single value (userid) from my React front-end to my Django back-end, so that I can use it for filtering in my Django views.py file, which I will then pass back to the front-end. I've been having trouble wrapping my head around this as I'm fairly new to working with APIs. My current Django code (which gives me everything I want it to): class WebRequestView(generics.ListAPIView): queryset = WebRequest.objects.filter(userid="testid") serializer_class = WebRequestSerializer Essentially I want to be able to pass the value "userid" from my React front-end so that it ends up like so: class WebRequestView(generics.ListAPIView): queryset = WebRequest.objects.filter(userid) serializer_class = WebRequestSerializer It can be hard-coded on the front-end, just not the back-end. This would work: const [userid, setUserId] = React.useState("testid"); To give more context: My Django backend is currently connected to an Oracle database. I would like to be able to filter for database entries based on the userid of the currently authenticated user, and nobody else's. I literally have no clue where to begin, or if this is even possible. I've tried things like: useEffect(() => { const requestOptions = { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ userid }), }; fetch("http://127.0.0.1:8000/api/add", … -
I don't understand why I keep getting ModuleNotFoundError
I have this package, setuptools, installed on my local machine as you will in the command line code attached, but I don't understand why I keep getting the modulenotfound error. PS C:\Users\MY PC\desktop\django-polls> easy_install --version setuptools 41.2.0 from c:\users\my pc\appdata\local\programs\python\python38\lib\site-packages (Python 3.8) PS C:\Users\MY PC\desktop\django-polls> python setup.py sdist Traceback (most recent call last): File "setup.py", line 1, in <module> from setuptools import setup ModuleNotFoundError: No module named 'setuptools' PS C:\Users\MY PC\desktop\django-polls> pip install setuptools Requirement already satisfied: setuptools in c:\users\my pc\anaconda3\lib\site-packages (52.0.0.post20210125) PS C:\Users\MY PC\desktop\django-polls> python setup.py sdist Traceback (most recent call last): File "setup.py", line 1, in <module> from setuptools import setup ModuleNotFoundError: No module named 'setuptools' PS C:\Users\MY PC\desktop\django-polls> -
Compare String with another string before and after the special character using python language
I am very new to python. I have two string a="he % home now" b="he came home now" Now how to compare the string a with before and after % symbol to string b. -
How to get Django to serve static files?
I built my application in a single directory and 2 subdirectories: App Directory Django Directory Vue/Nuxt3 Directory My Django project is essentially an API built using DRF My Vue/Nuxt3 project is built as an SPA, with hardcoded endpoints for localhost:8000 I ran npm build in my Vue/Nuxt3 directory, which generated a 'public' folder. I copied this folder into the Django directory (as the same level as manage.py) I installed whitenoise on my Django project I updated settings.py with the following: MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", 'whitenoise.middleware.WhiteNoiseMiddleware', ... ] ... TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'public'), os.path.join(BASE_DIR, 'staticfiles')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.0/howto/static-files/ STATIC_ROOT = BASE_DIR / 'staticfiles' STATICFILES_DIRS= [ BASE_DIR / 'public', ] STATIC_URL = "static/" STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' then I ran manage.py collectstatic which seems to have generated a collectstatic folder in my django directory my urls.py file: urlpatterns = [ re_path(r'', TemplateView.as_view(template_name='index.html')), ... ] When I run manage.py runserver and navigate to localhost:8000 - I expect to see my Vue app loaded up with all it's static assets. Instead I see a white screen and get the following errors: … -
How to get lookup field names from Django queryset?
In a QuerySet, is there a way to get the field names used to filter the query? I.E., if I try queryset = Reading.objects.get(user__email="testing@example.com", site__name="site name") is there a way to get the value ["user", "site"] or ["user__email", "site__name"]? As of right now, I have [ex.lhs.field.name for ex in queryset.query.where.get_source_expressions()] which will work properly for lookups that don't span relationships. This would be sufficient if I wasn't working in a codebase littered with them. QuerySet returned names Reading.objects.get(user=User(), site=Site()) ["user", "site"] Reading.objects.get(user__email="testing@example.com", site__name="site name") ["email", "name"] -
Can I access my website from Django admin panel?
I am trying to develop a website where I can see the homepage as it is from Django admin panel. The reason I want that is I want to edit the name of the static content like 'Home' to 'All' along with the change of slide show picture. In summary, I want to change the website layout from Django admin panel that is not accessible to users. Is that possible? I just want an idea of how to implement the process. -
Unable to create process using "" once creating a virtualenvironment using python
i a trying to build a virtual environment in python to use django framework but the problem is that once i create the virtual environment i cannot use any command and the terminal display the below error Unable to create process using 'C:\Users\LT GM\AppData\Local\Programs\Python\Python310\python.exe "F:\DJANGO\venv\Scripts\pip.exe" ' I followed these steps: create folder called django run this command Python -m pip install virtualenv create the virtual environment Virtualenv venv activate the virtual environment venv\Scripts\activate it run successfully any command after the fourth step display the above error python version 3.10.4 i tried to uninstall python and re-installed again but still the same problem what am i doing wrong ? and how to fix this -
Filter a list on a table by using a information on a context field
i'm building this app that gives sales information. It's basically a page that that shows a table with products sold and the quantities in the last couple of months. It takes from the database a list of ids and then retrieves information to a list of dictionaries that each dictionary represents info about a product. products_id = ( SalesHistory.objects.filter(store=store) .values_list("product", flat=True) .distinct() ) list_prod = Product.objects.filter(id__in=products_id, **filters).values() prod_dict = [] for item in list_prod: prod_dict.append(item) for i in range(len(prod_dict)): prod_dict[i]['prod_unit'] = SalesHistory.objects.filter(product= prod_dict[i]['id']).first().umb_product prod_dict[i]['months_first']= sum_sales(3, 4, store_id, prod_dict[i]['id']) (example of the building of the context["products"] variable) {% for product in products %} <tr id="{{ product.code }}" name="{{product.code}}"> <td style="font-size:65% !important; padding: 8px 8px 8px 15px !important;" >{{ product.code }}</td> <td style="font-size:60% !important;"> {{ product.name }} <span class="badge bg-primary"> (example on how the table is built on the front end) One of this infos is a category based on an ABC curve I implemented. How can I filter the list while using the page based on this info in the context/list of products? -
is MSAL cache preserved between calls in Django
From Django I have to call a Business Central API through Active Directory Oauth2 using package msal from Microsoft. HTML -> Django -> calls API from backend -> Business Central This is an extract of my code, based on an example from microsoft docs. It works in vanilla python import msal import requests import json # GET OAUTH2 TOKEN WITH CLIENT ID/CLIENT SECRET login_url = 'https://login.microsoftonline.com/<tenant>/oauth2/token' authority = 'https://login.microsoftonline.com/<tenant>' client_id = '<client ID from AAD>' scope = ['https://api.businesscentral.dynamics.com/.default'] client_secret = '<secret from AAD' grant_type = 'client_credentials' resource = 'https://api.businesscentral.dynamics.com' app = msal.ConfidentialClientApplication( client_id, authority=authority, client_credential=client_secret, ) result = app.acquire_token_silent(scope, account=None) if not result: print("No suitable token exists in cache. Let's get a new one from AAD.") result = app.acquire_token_for_client(scopes=scope) if "access_token" in result: token = result["access_token"] # CALL A BUSINESS CENTRAL API base_url = 'https://api.businesscentral.dynamics.com/v2.0/<tenant>/Sandbox' endpoint = base_url + "/ODataV4/Company('<company name>')/<service name>" response = requests.get(endpoint, headers={'Authorization': 'Bearer ' + token},).json() Now I'm going to add this logic in an existing Django project and reading msal.ConfidentialClientApplication code I found the comment: def acquire_token_silent( self, scopes, # type: List[str] account, # type: Optional[Account] authority=None, # See get_authorization_request_url() force_refresh=False, # type: Optional[boolean] claims_challenge=None, **kwargs): """Acquire an access token for given account, without user … -
How to cache queryset results in ListAPIView when pagination, filtering, ordering enabled?
How can I cache queryset (and invalidate cache) results in ListAPIView when there is pagination, filtering and ordering possible? Note that I need to invalidate cache per company so if any new Item object is created for a specific company I need to invalidate. from rest_framework.generics import ListAPIView from rest_framework.pagination import PageNumberPagination class CustomPaginationClass(PageNumberPagination): page_size = "30" page_size_query_param = 'perPage' max_page_size = 10000 class ItemListApiView(ListAPIView): model = Item authentication_classes = (SessionAuthentication, ) serializer_class = ItemSerializer permission_classes = (HasAccessToItems, ) pagination_class = CustomPaginationClass filter_backends = (filters.SearchFilter, DjangoFilterBackend, filters.OrderingFilter, ) search_fields = ('user__name', ) filter_fields = { 'category_type__name': ['exact'], 'item_type__name': ['exact'], 'approver__name': ['exact'], 'status': ['exact', 'in'] } ordering_fields = '__all__' def get_queryset(self): qs = Item.objects.filter(company=self.request.user.company).select_related('company') if not self.request.user.is_all_items_enabled: qs = qs.filter(approver=self.request.user) return qs.order_by('-created') def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) -
What is args in Django Class Based views?
I am a novice in Django and I want to clear for myself in Class Based View - what is self.args? What it contains? I do understand self.kwargs - it's a URL-variable captured, self.request - HTTP-request params captured. But what is self.args and where it's useful? -
update many to many relation table with db orm in django
I have two tables one is boards & the second one is customers. One Customer can have multiple boards and Once board can have multiple customers. I'm using simple DB functionality for adding and updating table. In an update, I'm giving one issue. A customer can select more boards on update and unselect existing than how can manage both new and existing boards because these boards have detail on another page where adding boards detail and on the customer update page only selecting boards. if I'm removing all boards of customers on an update then also deleting boards detail that already has been added. so due to deleting the information is also deleting I want to exist and also a new one and wanto to delete which customer will unselect. This is my code customer = db.table('customers').where('id', id).first() db.table('customers').where('id', customer.id).update({ 'username': username, 'domain': domain, 'subscription_end_date': subscription_end_date, 'updated_at': datetime.datetime.now() }) customer_boards_delete = db.table('customer_boards').where('customer_id', customer .id).delete() if request.data.get('boards') is not None: for board in request.data.get('boards'): db.table('customer_boards').where('id', board['id']).where('customer_id', user.id).update({ 'name': board['name'], 'customer_id': user.id, 'board_id': board['id'], 'updated_at': datetime.datetime.now() }) Can anyone please tell me how can manage existing and new boards and delete unselected boards? Thanks -
Django. How to realize the validation for Question object?
How to realize the validation to exist at least 1 right answer and 1 wrong answer for each Question object? from django.db import models class Test(models.Model): test_name = models.CharField(max_length=255) def __str__(self): return self.test_name class Question(models.Model): test = models.ForeignKey(Test,on_delete=models.CASCADE) question_text = models.TextField() def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question,on_delete=models.CASCADE) choice_text = models.CharField(max_length=255) is_right = models.BooleanField(null=False,blank=False) def __str__(self): return self.choice_text