Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
upstream prematurely closed connection while reading response header from upstream, Django + uWSGI + nginx, React as frontend
I am getting this error(upstream prematurely closed connection while reading response header from upstream) in nginx's error.log when sending post request to Django on send_mail, as the response it returns 502 Bad Gateway and also cors error(has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource), cors is enable on django, less secure apps is turned on on gmail. Thanks -
Serializer does not return all fields when saving
I have following serializer: class ClientSerializer(serializers.ModelSerializer): projects_count = serializers.ReadOnlyField() currency = CurrencySerializer(read_only=True) class Meta: model = Client fields = ('id', 'owner', 'name', 'icon_color', 'projects_count', 'hourly_rate', 'currency', ) def get_projects_count(self, obj): if hasattr(obj, 'projects_count'): return obj.projects_count return 0 And this is the view for getting and creating Client objects: class ClientListView(APIView): http_method_names = ['get', 'post'] authentication_classes = (authentication.SessionAuthentication, ) permission_classes = [IsAuthenticated] def post(self, request, format=None): serializer = ClientSerializer( context=dict(request=request), data=request.data ) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def get(self, request, format=None): qs_clients = Client.objects.filter( owner=request.user, ).annotate( projects_count=Count('project'), ) client_serializer = ClientSerializer( qs_clients, many=True, ) data = dict( clients=client_serializer.data, ) return Response( data, status=status.HTTP_200_OK, ) When calling POST, data returned does not contain project_count field: POST: {"id":9,"owner":1,"name":"zzz xxx","icon_color":"a45ac8","hourly_rate":null,"currency":null} But for GET, there is everything ok: GET: {"clients":[{"id":9,"owner":1,"name":"zzz xxx","icon_color":"a45ac8","projects_count":0,"hourly_rate":null,"currency":null}]} I need to have projects_count included in the POST response. Why is it missing? Thanks! -
apscheduler and django, but when i runserver,it's error,why?
eror info you can see error message is: UnicodeEncodeError: 'utf-8' codec can't encode character '\udc80' in position 156: surrogates not allowed -
how to save context without sessions in django
I am developing a multi channel chatbot in django where users can interact with facebook, whatsapp, and website. i am asking for user details one by one eg:- if user said "book test drive", bot will ask for name, address and other details one by one. I need to store those details which will obviously different for different users and respond accordingly, and finally save them. i have implemented that on website through sessions, but whatsapp and facebook won't support session without webview, is there any way to achieve this? -
Multiple fields update in a model using radio boxes
I am trying to make a page where admin can mark attendance for each student using absent and present radio boxes present besides each student My ClassRoom and ClassRoomStudents Model class ClassRoom(models.Model): # standard = models.CharField(max_length=50) classSection = models.CharField(max_length=50) teacher = models.OneToOneField(Teacher, on_delete = models.CASCADE) class ClassRoomStudent(models.Model): classRoom = models.ForeignKey(ClassRoom, on_delete=models.CASCADE) roll_number = models.IntegerField() student = models.OneToOneField(StudentInfo, on_delete=models.CASCADE) def save (self, *args, **kwargs): <logic to update roll number automatically for each classroom_student> model.py in my attendence app, status will store absent or present class StudentAttendence(models.Model): student = models.OneToOneField(ClassRoomStudent, on_delete=models.CASCADE) status = models.CharField(max_length=50) date = models.DateField() class TeacherAttendence(models.Model): teacher = models.OneToOneField(Teacher, on_delete=models.CASCADE) status = models.CharField(max_length=50) date = models.DateField() I have option in my template to search students using class. My views.py in attendence app def student_attendence(request): if request.method == "GET": if "add_no" in request.GET: add_no = request.GET["add_no"] students = ClassRoomStudent.objects.filter(classRoom__classSection__icontains = class_name) return render(request, 'attendence/student.html', {"students":students}) My question is how can I mark each student as absent or present using radiobox or something and store that in StudentAttendence model for each student? -
Access python script from one project to another
Main folder |-project1 |-project2 I have the above structure for django projects. When I am in project1 in a script i used os.chdir(to_project2) to project 2 I want to access project2's settings.py and fetch some attributes. Is it possible? -
Django logging module with TimedRotatingFileHandler logging to default logfile after restart
While using TimedRotatingFileHandler for logging in my Django project, the logger logs to the default file at the start and after midnight is reached, it will start logging to a new file with the date attached at the end. Ex: if the file name I have given is server_logs, it will log to this default file until midnight and then start logging in the new file, say: server_logs.2019-12-09. So far so good. But if restart the server, it will again start logging to server_logs file instead of the latest file with current date. I want it to continue logging to the latest file, even after the server restart. How do I resolve this issue? Also, in the log file, while logging, I want just the folder name and file name which is logging to the file. If I use %pathname, I get a path name like: "/some/log/path/appFolder/file.py". And if I use %filename, I get just "file.py". Ex: 2019-12-10 06:37:42,010, ERROR, views.py, get, LineNo 13 : This is the message. or 2019-12-10 03:54:47,173, ERROR, /some/long/path/name/that/I/want/to/avoid/testApp/views.py, get, LineNo 13 This is the message. I want to format it to "testApp/views.py". Ex: 2019-12-10 06:37:42,010, ERROR, testApp/views.py, get, LineNo 13 : This is the … -
Static files are not served during production in Django. How to solve the issue?
I want to deploy a Django app in my Linux server. I followed the Django docs and even configured the Apache config file as well but when running the Django server, none of my CSS and JS files are seen for: my website, Django admin interface and rest_framework as well. This is what I had done so far: A 'static' folder was created after initating the 'collectstatic' command and contains the following: blog_app (my website) rest_framework (my APIs) admin (Default Django Admin interface) settings.py: DEBUG = False [.] #all default settings # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_AUTHENTICATION_CLASSES' : [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ], } Apache config file (I named it as 'django_app.conf'): #django_app is the root folder for my Django project Alias /static /var/user/django_app/static <Directory /var/user/django_app/static> Require all granted </Directory> <Directory /var/user/django_app/django_app> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /var/user/django_app/django_app/wsgi.py WSGIDaemonProcess my_django_app python-path=/var/user/django_app python-home=/var/user/django_app/venv WSGIProcessGroup my_django_app After this, I typed: sudo a2ensite django.conf #to allow my Apache config file instead of 000-default.conf And: sudo a2dissite 000-default.conf #to disallow original Apache2 config file Then I included www-data user permission for my root project folder: … -
Table alignment in django template
I created a django template and the page contains a collapsible field but since I have added the collapsible field it shifts the rest of the row in the next line. Here's an image for better understanding: Earlier the edit and delete button were in the same row Here's the code: <div class="card"> <table class="table mb-0"> <thead> <tr> <th>Kit Name</th> <th>Kit Info</th> <th>Components per Kit</th> <th>Kit client</th> <th>Products</th> </tr> </thead> <tbody> {% for kit in kit %} <tr> <td class="align-middle">{{ kit.kit_name }}</td> <td class="align-middle">{{ kit.kit_info }}</td> <td class="align-middle">{{ kit.components_per_kit }}</td> <td class="align-middle">{{ kit.kit_client }}</td> <td class="align-middle"> <button class="btn" type="button" data-toggle="collapse" data-target="#multiCollapse{{ kit.pk }}" aria-expanded="false" aria-controls="multiCollapse{{ kit.pk }}"><img src="{% static 'img/cardopen.svg' %}" width="30" height="30" alt="card open"></button> </td> <tr class="collapse multi-collapse" id="multiCollapse{{ kit.pk }}"> <td colspan="7"> <table class="table table-bordered itemstable"> <thead> <tr> <th>Product Name</th> <th>Product Quantity</th> </tr> </thead> <tbody> {% if kit.product1 and kit.product1_quantity %} <tr> <td class="align-middle" id="p1">{{ kit.product1 }}</td> <td class="align-middle" id="pq1">{{ kit.product1_quantity }}</td> </tr> {% endif %} {% if kit.product2 and kit.product2_quantity %} <tr> <td class="align-middle" id="p2">{{ kit.product2 }}</td> <td class="align-middle" id="pq2">{{ kit.product2_quantity }}</td> </tr> {% endif %} {% if kit.product3 and kit.product3_quantity %} <tr> <td class="align-middle" id="p3">{{ kit.product3 }}</td> <td class="align-middle" id="pq3">{{ kit.product3_quantity }}</td> </tr> {% endif %} … -
Download multiple files in Django without creating zip
Is there a way to download multiple files in Django without creating zipfile on single click/request. For downloading single file I am using the following code in views.py: def download_file(request): the_file = '/some/file/name.png' filename = os.path.basename(the_file) chunk_size = 8192 response = StreamingHttpResponse(FileWrapper(open(the_file, 'rb'), chunk_size), content_type=mimetypes.guess_type(the_file)[0]) response['Content-Length'] = os.path.getsize(the_file) response['Content-Disposition'] = "attachment; filename=%s" % filename return response Also the code should be capable of downloading large files in size of 100GB max as I am dealing with video files with high resolution -
Django test resolves by for loop
I am doing some test in Django. I use fixtures to pre load some data and test API POST. In my POST, I want to link some data by foreign key. The test behavior is odd. I need to place a for loop in order for it to succeed. Here's my example for my fixtures: [ { "model": "apps.track", "pk": 1, "fields": { "name": "Love Song # 1", "album": null } }, { "model": "apps.track", "pk": 2, "fields": { "name": "Love Song # 2", "album": null } } ] Here's my test: class TestPost(TestCase): fixtures = ['fixtures/sample'] def setUp(self): self.album = { 'name': 'Love Songs Album', 'tracks': [ {'id': 1}, {'id': 2} ] } def test_post(self): c = Client() response = c.post( '/admin/login/', {'username': 'admin', 'password': 'passwordpassword'}) response = c.post('/apps/albums/', data=json.dumps(self.album), content_type='application/json') album = Album.objects.latest('id') tracks = Track.objects.filter(album=album).all() self.assertEqual(tracks[0].id, 1) self.assertEqual(tracks[1].id, 2) The test fails and only finds tracks id=2 but not tracks id=1. However when I add a for loop before the test assertions, the test succeeds. Here's the magic for loop: for track in tracks: print("TRACK", track.id) I want to know if there is any reason behind this. -
How can I make this query in Django?
I have theese fields(test_type, status, begin_time, and_time).The 'status' field has three state(0, 1,or 2). I want to make a queryset where: test_type = 'difficult') and (if status==1 and begin_time + 2x(end_time - begin_time) < timezone.now()) and (if status==2 and end_time < timezone.now()) then select theese fields. If the status state=0 I dont want to select that field. How can i make this queryset with Django ORM? -
best way to optimize django critical render path
I have a view which for every request will do some calculations about 1 second and then send result to render template function (return an html response). As noted here the html header section should be sent as early as possible to let browser start downloading other blocking assets (CSS) while downloading rest of html. It also minimizes time of showing First Paint, FCP which will improve user experience. In django by using render function we will send entire result after all calculation is done: from django.shortcuts import render def view(request): # calculate context (it may take about 1 seconds) return render(request, 'result.html', context) What is the best way to send html header response as early as possible? I know about StreamingHttpResponse but I'm not sure if it's a good fit for this problem (django docs: You might want to do this if generating the response takes too long or uses too much memory. For instance, it’s useful for generating large CSV files.) -
Initial data creation fails with data migration
It's my intent to create some initial model instances through a data migration with some JSON data. Upon calling json.load() on the JSON file, I'm iterating over each dictionary and its keys. Any key with white space is supposed to be replaced with a new string containing underscores. This is being done to unpack the dictionary when creating an model instance with Model.create(). What should be refactored to get the expected result? Actual outcome: Not all keys that have white space get replaced with new strings that contain underscores. Expected outcome: All keys that have white space get replaced with new strings that contain underscores. #models.py from django.db import models # Create your models here. class Item(models.Model): name = models.CharField(unique=True, max_length=255) image_filename = models.ImageField() category_type= models.CharField(max_length=255, blank=True) color = models.CharField(max_length=255, blank=True) current_condition = models.CharField(max_length=255, blank=True) def __str__(self): return self.name #data migration # Generated by Django 2.2.7 on 2019-11-30 23:21 import json from django.db import migrations def create_minerals(apps, schema_editor): Mineral = apps.get_model('minerals', 'Mineral') with open('my_file', 'r', encoding='utf-8') as data_file: uploaded_minerals_data = json.load(data_file) for mineral_dict in uploaded_minerals_data: mineral_name_data = mineral_dict.keys() for name in mineral_name_data: if " " in name: value = mineral_dict.pop(name) new_name = name.replace(" ", "_") mineral_dict[new_name] = value else: continue … -
Django: html not displaying form using block content
enter image description here //form.html {% load crispy_forms_tags %} {% block content %} <form {% if form_id %} id='{{ form_id }}' {% endif %} class='form' method='POST' action="{% if action_url %}{{ action_url }}{% endif %}"> {% csrf_token %} {{ form|crispy }} <input class="btn btn-primary" type="submit" value="{{ btn_title }}" /> </form> {% endblock %} //list_view.html {% extends "base.html" %} {% block content %} <div class="row"> <div class='col-sm-3 col-xs-12' style='background-color:red;'> <h1>{{ request.user }}</h1> </div> <div class='col-sm-9 '> {% if not request.GET.q %} <div class=""> {% include "tweets/form.html" with form=create_form action_url=create_url btn_title='Tweet' form_id='tweet-form' %} </div> <hr> {% endif %} <div id="tweet-container"> </div> </div> </div> {% endblock content %} For some reason when I try to use the form.html within the block content of list_view.html it only returns {% include "tweets/form.html" with form=create_form action_url=create_url btn_title='Tweet' form_id='tweet-form' %} as you can see in the photo I posted. im trying to make it a text area with a submit button. Does anyone have any suggestions -
How to upload multiple files (images) using django-rest-framework?
I'm writing a REST API, I haven't tried and have no clue how to upload multiple photos using django. Is there a separate serializer that I have to use or can I just use the serializer with the param 'many=True' similar to bulk data insertion? A python snippet would really be useful. Thanks in advance! -
Reverse access to OneToOne field in an abstract model
Suppose I have the following database structure: class Building(models.Model): # ... class AbstractBuilding(models.Model): building = models.OneToOneField(Building, on_delete=models.CASCADE, primary_key=True) # ... class Meta: abstract = True class Office(AbstractBuilding): # ... class Lab(AbstractBuilding): # ... class PowerPlant(AbstractBuilding): # ... If I have an Office object, it's easy to get the corresponding Building through the one-to-one field (e.g. office_object.building returns a Building). However, suppose I have a Building instead. How can I get the corresponding Office (or Lab or PowerPlant) from the Building object? -
No module named 'django.contrib.staticfiles.templatetags'
I have been breaking my head over this for a full day but can't figure out the problem. It happened after I copied my Django project from one PC to another. Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/username/opt/anaconda3/lib/python3.7/threading.py", line 926, in _bootstrap_inner self.run() File "/Users/username/opt/anaconda3/lib/python3.7/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/Users/username/opt/anaconda3/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Users/username/opt/anaconda3/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/Users/username/opt/anaconda3/lib/python3.7/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception raise _exception[1] File "/Users/username/opt/anaconda3/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "/Users/username/opt/anaconda3/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Users/username/opt/anaconda3/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/username/opt/anaconda3/lib/python3.7/site-packages/django/apps/registry.py", line 122, in populate app_config.ready() File "/Users/username/opt/anaconda3/lib/python3.7/site-packages/django/contrib/admin/apps.py", line 24, in ready self.module.autodiscover() File "/Users/username/opt/anaconda3/lib/python3.7/site-packages/django/contrib/admin/__init__.py", line 26, in autodiscover autodiscover_modules('admin', register_to=site) File "/Users/username/opt/anaconda3/lib/python3.7/site-packages/django/utils/module_loading.py", line 47, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "/Users/username/opt/anaconda3/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/saitohiromasa/opt/anaconda3/lib/python3.7/site-packages/django_summernote/admin.py", line 5, in <module> from django_summernote.widgets import SummernoteWidget, … -
How can i reduce my coding length in my below code?
Because i am a newbie so its really hard to understand code having much length..If i can reduce the length of code then how can i reduce it please explain someone in the below code. class Attachments(models.Model): created_by = models.ForeignKey( User, related_name='attachment_created_by', on_delete=models.SET_NULL, null=True) file_name = models.CharField(max_length=60) created_on = models.DateTimeField(_("Created on"), auto_now_add=True) attachment = models.FileField( max_length=1001, upload_to='attachments/%Y/%m/') lead = models.ForeignKey( 'leads.Lead', null=True, blank=True, related_name='lead_attachment', on_delete=models.CASCADE) account = models.ForeignKey( 'accounts.Account', null=True, blank=True, related_name='account_attachment', on_delete=models.CASCADE) contact = models.ForeignKey( 'contacts.Contact', on_delete=models.CASCADE, related_name='contact_attachment', blank=True, null=True) opportunity = models.ForeignKey( 'opportunity.Opportunity', blank=True, null=True, on_delete=models.CASCADE, related_name='opportunity_attachment') case = models.ForeignKey( 'cases.Case', blank=True, null=True, on_delete=models.CASCADE, related_name='case_attachment') task = models.ForeignKey('tasks.Task', blank=True, null=True, related_name='tasks_attachment', on_delete=models.CASCADE) invoice = models.ForeignKey('invoices.Invoice', blank=True, null=True, related_name='invoice_attachment', on_delete=models.CASCADE) event = models.ForeignKey('events.Event', blank=True, null=True, related_name='events_attachment', on_delete=models.CASCADE) def file_type(self): name_ext_list = self.attachment.url.split(".") if (len(name_ext_list) > 1): ext = name_ext_list[int(len(name_ext_list) - 1)] if is_document_file_audio(ext): return ("audio", "fa fa-file-audio") if is_document_file_video(ext): return ("video", "fa fa-file-video") if is_document_file_image(ext): return ("image", "fa fa-file-image") if is_document_file_pdf(ext): return ("pdf", "fa fa-file-pdf") if is_document_file_code(ext): return ("code", "fa fa-file-code") if is_document_file_text(ext): return ("text", "fa fa-file-alt") if is_document_file_sheet(ext): return ("sheet", "fa fa-file-excel") if is_document_file_zip(ext): return ("zip", "fa fa-file-archive") return ("file", "fa fa-file") return ("file", "fa fa-file") def get_file_type_display(self): if self.attachment: return self.file_type()[1] return None @property def created_on_arrow(self): return … -
Migrating to Django 2.2 from 1.11 -- old migrations without on_delete in ForeignKey break everything
I'm working on upgrading my legacy application from Django 1.11.13 to 2.2.8. I've dutifully addressed every compatibility issue, but I've hit one I can't figure out how to resolve. When I try to start the webserver in my local environment, I get this error (only showing the end of the full error trace that appears): File "/Users/me/my_app/my_model/migrations/0001_initial.py", line 37, in Migration ('entry', models.ForeignKey(to='my_model.Entry')), TypeError: __init__() missing 1 required positional argument: 'on_delete' I understand why on_delete is now required -- I just spent a while updating my models everywhere to accommodate this change -- but I have no idea how to fix this particular issue without going through dozens of old migrations files to make them conform?! I tried squashmigrations to at least collapse the number of places I have to clean up, but I got the same exact TypeError. I tried to use the old version of Django for squashmigrations. I was successful in avoiding the TypeError, but ended up with a huge mess of circular import errors. Since I don't actually need the migration history to roll back, I tried to follow these instructions (scenario 2) to clear the migration history while keeping the existing database, but I couldn't … -
Can I post the javascript array to the database in django framework?
I am new to django, I am having an users table and designs table as given below class designs(models.Model): id=models.IntegerField(primary_key=True) image = models.ImageField(upload_to='images') content = models.CharField(max_length=50,default='0000000') > class users(models.Model): email = models.CharField(max_length=50,default='0000000') password = models.CharField(max_length=50,default='0000000') design = models.ManyToManyField(designs) The user will click the designs he want it is a multi select and after clicking every the every design i wrote a javascript array to store the details of every design clicked by the user like this styles=[2, "../static/images/2.jpg", "Rustic & Warm", 3, "../static/images/3.jpg",…] So,in the form I took hidden input of design_id like this <form action="{% url 'car:user_register' %}" method="POST"> > {% csrf_token %} > <div class="form-group"> > <label for="design_id"></label> > <input type="hidden" name="design_id" class="form-control" value="styles"required> > </div> > > And my views.py def user_register(request): if request.method == 'POST': design_id=request.POST.GET('styles[]') email = request.POST['email'] password = request.POST['password'] user = users(password=password,email=email,design_id=design_id) user.save() return render(request,'home.html') Is that a correct way of getting and posting that javascript array in the database -
How to populate initial values of form from queryset
I have a FormView with a get_initial method which I am trying to use to populate the form. I am trying to get the EmployeeTypes of the receiver of the memo as values in the form. def get_initial(self): initial = super(NotificationView, self).get_initial() users = Memo.objects.filter(id=self.kwargs['pk']).values('receiver__employee_type') initial['receiving_groups'] = users return initial There are 2 issues here.. This returns a Queryset which looks like: <QuerySet [{'receiver__employee_type': 'Bartender'}, {'receiver__employee_type': 'Supervisor'}]> when I really need the fields in the form to be the EmployeeType itself. Most importantly - the form isn't even rendering these fields. Here is the form just in case: class MemoNotificationForm(forms.Form): class Meta: fields = [ 'receiving_groups' ] receiving_groups = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple) How do I populate the fields of the form? -
Error while updating mongodatabase collections from django app using djongo
I am facing an error. I am trying out the polls tutorial as provided in the django documentation. The problem is with the django 'F' function. I am trying to update the number of votes for a choice. If I load the choice object into python memory and do the normal numeric addition it is working. But if I use choice.update(votes=F('votes')+1) then it is giving me the following error. djongo.sql2mongo.SQLDecodeError: FAILED SQL: UPDATE "poll_choice" SET "question_id" = %(0)s, "choice_text" = %(1)s, "votes" = ("poll_choice"."votes" + %(2)s) WHERE "poll_choice"."id" = %(3)s Params: (1, 'huntress', 1, 3) If we observe %(2)s is supposed to be a number and not a string. But it is going as a string. Please help how I can resolve this . I am using djongo 1.2.38 with sqlparse version 0.2.4. -
Django Model seeking alternative to many to many fields
I am writing an exam system, below is my model: class Exam(models.Model): name = models.CharField( max_length=100 ) class Topic(models.Model): name = models.CharField( max_length=50 ) class Question(models.Model): title = models.CharField( max_length=100 ) topic = models.ForeignKey( Topic ) class Choice(models.Model): question = models.ForeignKey( Question, on_delete=models.CASCADE ) choice_text = models.CharField( max_length=200 ) is_right_answer = models.BooleanField( default=False ) I want when I create an exam, i can give multiple topics like math, physics, business etc and then i can query all the questions related that topics and show in the frontend. My problem only in exam creation, i am not getting should I use ManyToManyField or there is any alternative solution I just want to select multiple topic during i create an exam. Can anyone help me in this case? -
Why is my Django form is not displaying anything?
I am following a tutorial in which we will create a form to hold simple object parameters. Here's the code: forms.py from django.forms import ModelForm from .models import Item class ItemForm(ModelForm): class Meta: model = Item fields = ['item_name', 'item_desc', 'item_price', 'item_image'] models.py from django.db import models class Item(models.Model): def __str__(self): return self.item_name item_name = models.CharField(max_length = 200) item_desc = models.CharField(max_length= 200) item_price = models.IntegerField() item_image = models.CharField(max_length=500, default ="https://i.jamesvillas.co.uk/images/jvh/holiday-destinations/resort/food-placeholder.jpg" ) urls.py from . import views from django.urls import path urlpatterns = [ path('', views.index, name = 'index'), path('item/', views.item, name = 'item'), path('info/', views.info, name = "info"), path('<int:item_id>/', views.detail, name = "detail" ), #add form path('add', views.create_item, name = "create"), ] views.py from django.shortcuts import render, redirect from django.http import HttpResponse from .models import Item from django.template import loader from .forms import ItemForm #Some code here def create_item(request): form = ItemForm(request.POST or None) if (form.is_valid()): form.save() return redirect('food/index') return render(request, 'food/item-form.html', {'form': form}) food/item-form.html <form method = "POST"> {% csrf_token %} {{ form }} <button type= "Submit" >Save</button> </form> Now when I go to http://localhost:8000/food/add, it displays an empty page! I have followed the tutorial the exact same way then why is My project not working?