Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create dropdown menu from model in django
im currently trying to create a drop-down menu for my Post categories in my base.html so that it gets displayd on every of my templates. Later on i want that a user simply clicks on a category item and gets forwarded to the specific category. I'm a bit confused as to what I should include in my forms and how to call that form on my base.html. views.py: def category_dropdown(request): categories = Category.objects.title() return render (request, 'quickblog/base.html', {'categories': categories}) models.py ... # Categorys of Post Model class Category(models.Model): title = models.CharField(max_length=255, verbose_name="Title") description = models.TextField(max_length=10000, null=True) categorycover = fields.ImageField(upload_to='categorycovers/', blank=True, null=True, dependencies=[ FileDependency(processor=ImageProcessor( format='JPEG', scale={'max_width': 600, 'max_height': 600})) ]) class Meta: verbose_name = "Category" verbose_name_plural = "Categories" ordering = ['title'] def __str__(self): return self.title #Post Model class Post(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField(max_length=10000) category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE, null=True) ... forms.py class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title', 'text', 'tag', 'postcover', 'postattachment', 'category'] captcha = CaptchaField() Thanks :) -
how can I use 'POST' method with django_filter
I have a form using django_filter that works ok. When I click 'NEXT' button I need : 1) save the informations that are selected in the grid 2) go to the next form In my views.py i use instancia_item_filter = itemtiposervicoFilter(request.GET, queryset=instancia_item_list) Like that it´s possibile to show the informations on the grid and sum selected lines. If i change it to post method i cannot do that. See the screen bellow. views.py def servico_create(request, id=None): instance = get_object_or_404(usuario, id=id) form = itemtiposervicoForm(request.POST or None) # Seleciona a lista para ser exibida no grid instancia_item_list = itemtiposervico.objects.all().order_by('desc_itemtiposervico') instancia_item_filter = itemtiposervicoFilter(request.GET, queryset=instancia_item_list) paginator = Paginator(instancia_item_filter.qs, 100) page = request.GET.get('page') try: response = paginator.page(page) except PageNotAnInteger: # if page is not an integer, deliver first page response = paginator.page(1) except EmptyPage: # if page is out of range, deliver last pages of results response = paginator.page(paginator.num_pages) if request.method=='POST': print('save and go to the next form') context = { "filter": instancia_item_filter, "response": response, "form": form, } return render(request, 'servico/teste.html', context) my teste.html template has something like that: <form class=" bd-form-28 " action="" name="form-name" method="GET" enctype="multipart/form-data"> {% csrf_token %} <div class=" bd-select-5 form-group"> <label class="bd-form-label">Serviço</label> {{filter.form.tiposervico}} </div> </form> <table id="table" width="100%" border="0" cellspacing="0" cellpadding="0"> … -
ROUTING key found for default - this is no longer needed in Channels 2
I want to integrate Django Channels.I have installed all required dependencies,and while starting the app server starts listening on TCP address 127.0.0.1:8000. My routing is specified as follows: websocket_urlpatterns = [ url(r'^ws/chat/(?P<room_name>[^/]+)/$', consumer.ChannelConsumer), ] And the Consumer file: from channels.generic.websocket import AsyncWebsocketConsumer import json class ChannelConsumer(AsyncWebsocketConsumer): async def connect(self): # self.room_name = self.scope['url_route']['kwargs']['room_name'] # self.room_group_name = 'chat_%s' % self.room_name # # # Join room group # await self.channel_layer.group_add( # self.room_group_name, # self.channel_name # ) await self.accept() async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive message from WebSocket async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] # Send message to room group await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message } ) # Receive message from room group async def chat_message(self, event): message = event['message'] # Send message to WebSocket await self.send(text_data=json.dumps({ 'message': message })) However I cant open connection. Handshake fails -
Django ListData on DetailView from Array
here my models.py class Absent(models.Model): ... ListOfDate = models.TextField(blank=True, null=True, default='Nothing') ... in my case ListOfDate data will look like this: [datetime.date(2018, 4, 18), datetime.date(2018, 5, 15), datetime.date(2018, 5, 16), datetime.date(2018, 5, 17)] I use ListOfDate.append(value) to fill ListOfData. here my views.py class Attend(DetailView): context_object_name = 'attends' model = models.Attend on ListView commonly use {% for attend in attends %} <td>{{ attends.ListOfDate }}</td> {% endfor %} for showing list of data. but it will be all in one column. like this: [datetime.date(2018, 4, 18), datetime.date(2018, 5, 15), datetime.date(2018, 5, 16), datetime.date(2018, 5, 17)] in my case I want to list ListOfDate like above but not in one column. Like this: +-----+--------------------------------+ | # | Date | +-----+--------------------------------+ | 1 | [datetime.date(2018, 4, 18), | | | datetime.date(2018, 5, 15), | | | datetime.date(2018, 5, 16), | | | datetime.date(2018, 5, 17)] | +-----+--------------------------------+ | | v +-----+----------------+ | # | Date | +-----+----------------+ | 1 | 2018-4-18 | +-----+----------------+ | 2 | 2018-5-15 | +-----+----------------+ | 3 | 2018-5-16 | +-----+----------------+ | 4 | 2018-5-17 | +-----+----------------+ -
Uninstall Packages that aren't used by pip
Since the day I started building my website, I installed many packages sometimes to test bunch of codes, sometimes for the project itself (Later I figured out it's not the package needed). But now, when I run pip freeze I have a list of packages, It becomes hard to me to uninstall packages that aren't used. I am about to deploy my website. I'm using the latest version of pip, and running a Django Project I have virtual environment with virtualenv python 3.5 OS: Linux (Ubuntu) Many thanks you awesome people! -
How to use Celery with Django
I am trying to design a billing website but I need to update it monthly. How do I get it together using Celery. Any Useful answer would be accepted thanks. -
Changing mySQL Query to Django
I am having difficulties changing the following MySQL Query to a Django Query SELECT * FROM dashboard_db.dashboard_system ds JOIN dashboard_db.dashboard_userpreference up ON ds.id = up.system_id WHERE username = "<user>" Here are the models in my Django application class System(models.Model): system_name = models.CharField(max_length = 40) LOCATION = (('0', 'Inernal'),('1','External')) location = models.CharField(max_length=1, choices=LOCATION) def __str__(self): return self.system_name class UserPreference(models.Model): username = models.CharField(max_length = 40) system = models.ForeignKey(System, on_delete = models.CASCADE) def __str__(self): return self.username I have been trying to use unions and a few other options. I am aware that Performing a raw SQL query is an option. However I was wondering if it is possible to perform the join using a Django styled query. -
Django dynamic FileField upload_to
I'm trying to make dynamic upload path to FileField model. So when user uploads a file, Django stores it to my computer /media/(username)/(path_to_a_file)/(filename). E.g. /media/Michael/Homeworks/Math/Week_1/questions.pdf or /media/Ernie/Fishing/Atlantic_ocean/Good_fishing_spots.txt VIEWS @login_required def add_file(request, **kwargs): if request.method == 'POST': form = AddFile(request.POST, request.FILES) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.parent = Directory.objects.get(directory_path=str(kwargs['directory_path'])) post.file_path = str(kwargs['directory_path']) post.file_content = request.FILES['file_content'] <-- need to pass dynamic file_path here post.save() return redirect('/home/' + str(post.author)) MODELS class File(models.Model): parent = models.ForeignKey(Directory, on_delete=models.CASCADE) author = models.ForeignKey(User, on_delete=models.CASCADE) file_name = models.CharField(max_length=100) file_path = models.CharField(max_length=900) file_content = models.FileField(upload_to='e.g. /username/PATH/PATH/..../') FORMS class AddFile(forms.ModelForm): class Meta: model = File fields = ['file_name', 'file_content'] What I have found was this, but after trial and error I have not found the way to do it. So the "upload/..." would be post.file_path, which is dynamic. def get_upload_to(instance, filename): return 'upload/%d/%s' % (instance.profile, filename) class Upload(models.Model): file = models.FileField(upload_to=get_upload_to) profile = models.ForeignKey(Profile, blank=True, null=True) -
Simple Tests in Django failed
I'm trying to do simple tests in Django (v. 2.0.5). Since I can not see why I'm getting the '404 != 200' error, I post all relevant data. test.py from django.urls import resolve, reverse from django.test import TestCase from .views import home, board_topics from .models import Board class HomeTests(TestCase): def test_home_view_status_code(self): url = reverse('home') response = self.client.get(url) self.assertEqual(response.status_code, 200) def test_home_url_resolves_home_view(self): view = resolve('/home/') self.assertEqual(view.func, home) class BoardTopicsTests(TestCase): def setUp(self): Board.objects.create(name='Django', description='Django discussion board') def test_board_topics_view_success_status_code(self): url = reverse('board_topics', kwargs={'pk': 1}) response = self.client.get(url) self.assertEqual(response.status_code, 200) def test_board_topics_view_not_found_status_code(self): url = reverse('board_topics', kwargs={'pk': 99}) response = self.client.get(url) self.assertEqual(response.status_code, 404) def test_board_topics_url_resolves_board_topics_view(self): view = resolve('/boards/1/') self.assertEqual(view.func, board_topics) urls.py from django.contrib import admin from django.urls import include, path from boards import views urlpatterns = [ path('boards/<int:pk>/', views.board_topics, name='board_topics'), path('home/', views.home, name='home'), path('admin/', admin.site.urls), ] views.py ... def board_topics(request, pk): try: board = Board.objects.get(pk=pk) except Board.DoesNotExist: raise Http404 return render(request, 'topics.html', {'board': board}) Traceback FAIL: test_board_topics_view_success_status_code (boards.tests.BoardTopicsTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "/.../boards/tests.py", line 25, in test_board_topics_view_success_status_code self.assertEqual(response.status_code, 200) AssertionError: 404 != 200 I wonder why I'm getting this error because I can call the views and I also get a 404 error when I try to call a page that does … -
Installed Python and Django Using Chocolatey - How Do I Run Django?
Apologies if the answer seems obvious. I've installed Python3, Django, Git and an environment for said Python without a hitch. Now I'm unsure how I get Django up and running. I implemented a "C:>/workspace/local_sites" folder for my Django projects to be in, as seen below: local sites folder But I'm unsure as to where I go from here. Every tutorial I come across appears to be running Django through methods I cannot access since I used PowerShell to install the program rather than CmdPrompt. I just want to create a working, interactive website, that I can store in a folder and come back to whenever I please. Again, apologies if the answer seems obvious. Thank you for your time. -
Looping over for loop inside another for loop in Django
First see my code please : My model : class review_product_individual(models.Model): product_id = models.CharField(max_length=30) product_star = models.CharField(max_length=30) product_review_message = models.CharField(max_length=255,blank=True) product_reviewed_by = models.CharField(max_length=30) product_review_date = models.DateTimeField(auto_now_add=True, blank=True) In views : product_review = review_product_individual.objects.filter(product_id = productID).order_by('-product_review_date') Here product_star will contain 1 to 5 rating and stored as char. Now what I want to do is this I will access each product_review object in Django template in for loop and inside the for loop I will iterate product_review.product_star times.please see the template code here :` {% for product_review in product_review %} <li> <div class="review-heading"> <h5 class="name">{{product_review.product_reviewed_by}}</h5> <p class="date">27 DEC 2018, 8:0 PM</p> <div class="review-rating"> {% for i in {{product_review.product_star}} %} <i class="fa fa-star"></i> {% endfor %} <i class="fa fa-star-o empty"></i> </div> </div> <div class="review-body"> <p>{{product_review.product_review_message}}</p> </div> </li> {% endfor %} But only one star is printing as the value of {{product_review.product_star}} =3 I want 3 stars. I could not do in views because product_review contains many objects. So how can I do it ? -
how to remove --------- from django Select widgets
How do I remove the ----- in my django ModelForm widgts? documentation say to use empty_label but it is for SelectDateWidget my form class ProjectForm(forms.ModelForm): class Meta: model = Project exclude = ('copy', 'created', 'researcher', 'keywords', 'application_area', 'predominant_area') widgets = { 'title':forms.TextInput(attrs={ 'class':'form-control', 'placeholder': 'Titulo da oportunidade' }), 'conclusion_date':forms.TextInput(attrs={ 'class': 'form-control', 'type':'text', 'placeholder':'Data de conclusão' }), 'category': forms.RadioSelect(attrs={ 'class':'form-control' }), 'result':forms.Select(attrs={ 'class':'form-control' }), } -
Django celery can't get result in delay() function
After I install celery in my django app, I run the following command in the Django shell: from celery import Celery celery = Celery() @celery.task def add(x, y): return x + y add.delay(8, 8) Then, I found it never ends just keeps looping through the delay function. After I abort the command, the message is /usr/local/lib/python2.7/site-packages/celery/app/task.pyc in delay(self, *args, **kwargs) 411 celery.result.AsyncResult: Future promise. 412 """ --> 413 return self.apply_async(args, kwargs) 414 415 def apply_async(self, args=None, kwargs=None, task_id=None, producer=None, /usr/local/lib/python2.7/site-packages/celery/app/task.pyc in apply_async(self, args, kwargs, task_id, producer, link, link_error, shadow, **options) 534 link=link, link_error=link_error, result_cls=self.AsyncResult, 535 shadow=shadow, task_type=self, --> 536 **options 537 ) 538 /usr/local/lib/python2.7/site-packages/celery/app/base.pyc in send_task(self, name, args, kwargs, countdown, eta, task_id, producer, connection, router, result_cls, expires, publisher, link, link_error, add_to_parent, group_id, retries, chord, reply_to, time_limit, soft_time_limit, root_id, parent_id, route_name, shadow, chain, task_type, **options) 735 with P.connection._reraise_as_library_errors(): 736 self.backend.on_task_call(P, task_id) --> 737 amqp.send_task_message(P, name, message, **options) 738 result = (result_cls or self.AsyncResult)(task_id) 739 if add_to_parent: /usr/local/lib/python2.7/site-packages/celery/app/amqp.pyc in send_task_message(producer, name, message, exchange, routing_key, queue, event_dispatcher, retry, retry_policy, serializer, delivery_mode, compression, declare, headers, exchange_type, **kwargs) 552 delivery_mode=delivery_mode, declare=declare, 553 headers=headers2, --> 554 **properties 555 ) 556 if after_receivers: /usr/local/lib/python2.7/site-packages/kombu/messaging.pyc in publish(self, body, routing_key, delivery_mode, mandatory, immediate, priority, content_type, content_encoding, serializer, headers, compression, … -
Compilation problems with django static precompiler
I am trying to compile my scss file and this is the error I have : Exception Value: relation "static_precompiler_dependency" does not exist Here is what is in my html head : <link rel="stylesheet" type="text/css" href="{% static "css/main.scss"|compile %}"> And here in my setting.py : STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) STATIC_ROOT = os.path.join(BASE_DIR, 'static/css') I can see the COMPILED folder. But still having that exception error -
URL Patterns and Views
I have an application which requests data based on certain parameters. I use two functions to handle the requests and then create two objects from the responses. I am able to iterate through each object individually and display the data of a particular object on my webpage, but when I try to use both functions simultaneously, only one function iterates through the object. It is my understanding that this issue has something to do with URL patterns, but I am not as to what the best approach would be. Below you will find my urlpatterns, my functions, and the html I use to access the view. urlpatterns = [ path('', views.customer, name='customer'), path('', views.information, name='information'), ] def customer(request): for i, contact in enumerate(contactObj): try: contacts = contactObj context = {'contacts': contacts} except KeyError: print() return render(request, 'uccx/home.html', context) def information(request): for i, ticket in enumerate(ticketObj): try: tickets = ticketObj context = {'tickets': tickets} except KeyError: print() return render(request, 'uccx/home.html', context) <tbody> {% for ticket in tickets %} <tr class="{% cycle 'row1' 'row2'"> <td> {{ ticket.id }} </td> <td> {{ ticket.company.name }} </td> <td> {{ ticket.summary }} </td> </tr> {% endfor %} -
Unable to handle multiple user login - Django
I have ran into a small problem when trying to login 2 users in Django. I am using default authenticate function and my code as below class CustomAuthToken(ObtainAuthToken): def post(self, request, *args, **kwargs): data1 = request.data username = data1['username'] password = data1['password'] valid_user = authenticate(username=username, password=password) if valid_user is not None: login(request, valid_user) serializer = self.serializer_class(data=request.data, context={'request': request}) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] token, created = Token.objects.get_or_create(user=user) return Response({'token': token.key, 'user_id': user.pk, 'email': user.email}) else: print("invalid") return Response(status=status.HTTP_401_UNAUTHORIZED) My first login works successfully and I receive token. However if I try to login different user I am getting below response in Postman { "detail": "CSRF Failed: CSRF token missing or incorrect." } Looks like I am only able to handle one user login at a time. Please help me with this -
Avoid repeating lots of queries every time
I'm done building a website, there's a lots of views that contains many queries My question is How can I avoid repeating some queries from views that will be visited by users many time?. Here is an example of views.py @access_to(['is_admin','is_job_seeker']) def negotiationView(request,slug,id,code): obj = get_object_or_404(Group,slug=slug) nego = get_object_or_404(Negotiation,id=id,code=code) related_negos = Negotiation.objects.filter(tag=nego.tag) # New tag can be created every 2 months or more all_jobs = obj.job_offers.filter(published=True) # new job can be added every week As you can, each time I visit that page, the same query will repeat.. Any hint will be helpful, Thank you in advance! -
How to make an Email Field in form.py a required field?
I have been trying several methods but cant seem to make it work. Here are my codes: class Meta: model = User # set fields to be used in registration form fields = ['username','email','password','password2'] username = forms.CharField(required=True) email = forms.EmailField(required=True, max_length=100) <--- password= forms.PasswordInput() password2=forms.PasswordInput() # user email must be unique def clean_email(self): email = self.cleaned_data.get('email') # check if account with email exists if email and User.objects.filter(email=email).exists(): raise forms.ValidationError('Email address already exists') return email Does anyone know why the required=True does not work to make it as a required field? -
Django form - can I return any variables when raising a ValidationError
I have built a custom form, with several custom fields (containing the primary keys of my models) so I am not using clean_() methods, just clean(). I obtain data out, and if a field doesn't contain certain inputs, I raise a ValidationError. However, I would not like this to fully reset my form inputs... Is there a way to 'save' the state of the form when submitting... or return values even when you are raising a validation error? form: def clean(self): data = self.data my_data = data.getlist('my_data') ... use my_data to create pandas dataframe ... missing = df.loc[( ((df['status'] == 'report') | (df['status'] == 'toconfirm')) & (df['evidence'] == ''))] if not missing_evidence.empty: error_ids = missing_evidence['obj'].tolist() error_variants = [str(o) for o in error_ids] error_variants = "; ".join(error_variants) raise(forms.ValidationError(('%(value)s incorrect'), params={'value': error_variants}, )) ** here can I return dataframe, and re-set up my form? ** -
possible django race condition
@receiver(post_save, sender=MyRequestLog) def steptwo_launcher(sender, instance, **kwargs): GeneralLogging(calledBy='MyRequestLog', logmsg='enter steptwo_launcher').save() # remember to remove this line if instance.stepCode == 100: GeneralLogging(calledBy='MyRequestLog', logmsg='step code 100 found. launch next step').save() nextStep.delay(instance.requestId,False) I think I just witness my code losing a race condition. The backend of my application updates the status of task one, and it writes a stepCode of 100 to the log when the next task should be started. The front end of the application polls to report the current step back to the end user. It appears that after the backend created an entry with stepCode 100, the front request came in so soon after, that the if instance.stepCode == 100: was never found to be True. The GeneralLogging only reports one entry at the time of the suspected collision and does not launch the nextstep. My question is to 1) Confirm this is possible, which I already suspect. and 2) A way to fix this so nextStep is not skipped due to the race condition. -
uwsgi listen queue fills on reload
I'm running a Django app on uwsgi with an average of 110 concurrent users and 5 requests per second during peak hours. I'm finding that when I deploy with uwsgi reload during these peak hours I am starting to run into an issue where workers keep getting slowly killed and restarted, and then the uwsgi logs begin to throw an error: Gracefully killing worker 1 (pid: 25145)... Gracefully killing worker 2 (pid: 25147)... ... a few minutes go by ... worker 2 killed successfully (pid: 25147) Respawned uWSGI worker 2 (new pid: 727) ... a few minutes go by ... worker 2 killed successfully (pid: 727) Respawned uWSGI worker 2 (new pid: 896) ... this continues gradually for 25 minutes until: *** listen queue of socket "127.0.0.1:8001" (fd: 3) full !!! (101/100) *** At this point my app rapidly slows to a crawl and I can only recover with a hard uwsgi stop followed by a uwsgi start. There are some relevant details which make this situation kind of peculiar: This only occurs when I uwsgi reload, otherwise the listen queue never fills up on its own The error messages and slowdown only start to occur about 25 minutes after … -
django file uploaded for processing- how to correctly specify output-download file-type?
I have a simple django platform where I can upload text files. Ultimately I want to return a downloadable mp3 audio file made from the text in the uploaded file. My problem currently is that I cannot seem to correctly specify the type of file that the website outputs for download. As practice I originally tried to have the downloadable output of the website as the content of the uploaded file written to a new file called 'result.txt': views.py (code adapted from https://github.com/sibtc/simple-file-upload) def simple_upload(request): if request.method == 'POST' and request.FILES['myfile']: myfile = request.FILES['myfile'] print(str(request.FILES['myfile'])) x=str(myfile.read()) #print(x) new_file=open("/path/simple-file-upload/media/result.txt", "w") new_file.write(x) new_file.close() with open('/path/simple-file-upload/media/result.txt', 'r') as pdf: response = HttpResponse(pdf.read()) response['content_type'] = 'text' response['Content-Disposition'] = 'attachment;filename=result.txt' return response return render(request, 'core/simple_upload.html') While writing the content of the uploaded file to a 'result.txt'- returning the file in a downloadable text file is problematic..... Rather than being returned as a txt file it is returned as an HTML file- 'result.txt.html'. Inspecting the content of this HTML file shows the original text content of the uploaded file but in an HTML format and the text is encased in b''. I then tried to make the downloadable output of the website an mp3 file: from … -
Efficient way of optaining a number of items based on foreign key
Here's an example: Models.py Class Category(models.Model): name = models.Charfield(max_length=120 blank=True, null=True, default=None) Class Product(models.Model): category = models.Foreignkey(Category) How can i optain a list containing 6 products per category without using 'for'? This is what i made previously: products = [Product.objects.filter(category_id=i.id)[:6] for i in Category.objects.all()] -
Django: need Dynamic login using info from database redirect after login, using built-in login
After I login, I need to redirect to another page while adding URL parameters to the URL of the next page. I get the value of these parameters after the user is authenticated because they need to be accessed from the user database table. I heard about using the next parameter but I don't know how I would use it since I need to access the database table and I can't do that from urls.py. This is my url.py line for login right now: url(r'^$',auth_views.login, name='login',kwargs={ 'authentication_form':loginPlaceHolderForm, }), I'm not really sure what other info you need so just ask for it in the comments and I'll be sure to add it. -
Django: Form is not valid
I am currently struggling to get my form to work properly. I created the form manually (template.html) and I can see all the data when I call it with print(request.POST) (in views.py - checkout) however form.is_valid(): (in views.py - checkout) doesn't work. Means my form is not valid. I think the issue is, that I created the form manually and combined it with a model form where I want after validating my data with form.valid() save it in. Can anyone of you guys help me with my problem, why it's not valid? template.html <form action="{% url 'checkout:reserve_ticket' %}" method="post"> {% csrf_token %} {% for ticket in event.tickets.all %} <p> {{ ticket.name }} for {{ ticket.price_gross }} with quantity: <input type="hidden" name="order_reference" value="123456af"> <input type="hidden" name="ticket" value="{{ ticket.id }}"> <input type="hidden" name="ticket_name" value="{{ ticket.name }}"> <input type="number" name="quantity" max="{{ ticket.event.organiser.max_quantity_per_ticket }}" placeholder="0"> </p> {% endfor %} <button type="submit" class="btn btn-primary">Continue</button> </form> models.py class ReservedItem(models.Model): order_reference = models.CharField( max_length=10, unique=True ) ticket = models.ForeignKey( Ticket, on_delete=models.PROTECT, related_name='reserved_tickets' ) ticket_name = models.CharField(max_length=100) quantity = models.IntegerField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) forms.py class ReserveForm(forms.ModelForm): class Meta: model = ReservedItem fields = ['order_reference', 'ticket', 'ticket_name', 'quantity'] views.py - events # Create your views here. …