Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make Django show hint's in case password doesn't meet requirements during registration?
Can anyone please tell me how to make Django actually display hints\messages\errors or whatever in case during registration process user's password doesn't meet standart requirements? Because now it is just absolutely silent about that. Here's my form class Registration(UserCreationForm): class Meta: model = User fields = ['username', ] and here's my view def register(request): if request.method == 'POST': form = Registration(request.POST) if form.is_valid(): user = form.save() login(request, user) return redirect('upload') else: form = Registration() return render(request, 'testapp/temp1.html', {'form': form}) Thank you in advance! -
Reverse comments list in descending order to get the last n (2) objects in django template
I've searched a lot and couldn't find anything to reverse the comment's list in descending order so that I can get the last two comments of each post in the template. Here is my model: class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') commented_by = models.ForeignKey(User, on_delete=models.CASCADE) comment = models.CharField(max_length=128) views.py: posts = Post.objects.all().order_by("date_posted").reverse() return render(request, "cs50gram/explore.html", {"posts": posts}) template.html: {% for post in posts %} {% for comment in post.comments.all|slice:":2" reversed %} <div style="color: gray"> <b> {{ comment.commented_by }} </b> {{ comment.comment }} </div> {% endfor %} {% endfor %} The problem here is that it slices first and then reverse.. What have I tried? How to reverse a for loop in a Django template and then slice the result Using the solution presented in the answer, it didn't work for some reason. This is exactly how I tried it in my code. {% for post in posts %} {% for comment in post.comments.all.reverse|slice:":2"%} <div style="color: gray"> <b> {{ comment.commented_by }} </b> {{ comment.comment }} </div> {% endfor %} {% endfor %} The output is that it only slice it without reversing. Any help in reversing the comment's list in descending order and getting the last n (2) comments of … -
OuterRef not looking into outer query
I have the following model schema (only putting here the important variables): class Department(models.Model): name = models.CharField(max_length = 64) class User(AbstractUser): departments = models.ManyToManyField(Department, related_name = 'users', blank = True) date_left = models.DateTimeField(null = True, blank = True) ## date_joined = This is set by default on AbstractUser class Office(models.Model): department = models.ForeignKey(Department, related_name = 'offices', on_delete = models.CASCADE) class Invoice(models.Model): office = models.ForeignKey(Office, related_name = 'invoices', on_delete = models.CASCADE) date = models.DateField(null = True, blank = True) ## nr_workers = The annotation i'm trying to create below And i want to retrieve, for every Invoice date, the number of active users. For example, invoice.date = '2021-04-01' -> nr_workers should be equal to the number of users from that invoice.office.department who joined before 2021-04-01 and, either left after that date, or never left at all. What i've tried so far: from django.db.models import Max, Min, Q, F, Subquery, OuterRef, Value, Count qs = Invoice.objects.all() qs = qs.annotate( dep_pk = F('office__department__pk') ) ## Works fine until here qs.annotate( nr_workers = Count( Subquery( User.objects.filter( departments__pk__in = [OuterRef('dep_pk')] ).values('pk') ) ) ) ## Error - "Cannot resolve keyword 'dep_pk' into field. Choices are: ..." The OuterRef('dep_pk') it's not looking into the qs (it's … -
How to get another related result in a django model
Let's say I have this model in django: class DeviceSensorChange(models.Model): device = models.ForeignKey(Device, on_delete=models.CASCADE, db_index=True) sensor = models.ForeignKey(DeviceDigitalSensor, on_delete=models.CASCADE, db_index=True, related_name='sensorchanges') time = models.DateTimeField(auto_now_add=True) value = models.BooleanField(default=False) it describes how and when some "sensors" changes in time (a history of binary buttons: on and off). Then there is a ListView filtered by device or by sensor or by time. I want to add another column in the view, that shows the elapsed time since the last change of the same sensor in the same device: it means I should to go back in the table looking for the same device, same sensor, get the time and make the subtraction. Where is the right place to do that? I must not change the model and the information is needed just in the view to help the user, no need to store it. Is it possbile to add a elapsed() function in the model? Or this is something that has to be done in the template? Or in the ListView itself? -
Failing to load static CSS from Django on Azure
I followed this tutorial from DigitalOcean and have this in my settings.py. STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') However, after deploying my app, I find that the CSS file's request is canceled as seen in Chrome tools. I still get this error even after running: $ python manage.py collectstatic which gives me files in staticfiles directory for admin and app. Note that I can run all this on localhost with no issue. I tried the suggestion in this answer by switching from /static/ to static/ but ran into the same issue. Given that I want to retain this structure of static files in their respective app directories and don't have CSS files that are not tied to any app, I can't use STATICFILES_DIRS as the documentation says. Your project will probably also have static assets that aren’t tied to a particular app. In addition to using a static/ directory inside your apps, you can define a list of directories (STATICFILES_DIRS) in your settings file where Django will also look for static files. -
Pass a GET parameter from HTML and receive in Django View
I'm trying to pass a start date and end date from my html href to my views.py But I can't get the data related the passed date Example: {{ date }} = 2021-05-13 {{ date1 }}= 2021-05-14 HTML: <a href="{% url 'pba_defect_xls' %}? date = {{ date }}, date1 = {{ date1 }}" class="btn btn-success" style="float:right;">Export Excel</a> View: def pba_defect_xls(request): if request.method == 'GET': date = request.GET.get('date') date1 = request.GET.get('date1') print(date) print(date1) URLS: path('pba_defect_xls', pba_defect_xls, name="pba_defect_xls"), Howerver it's printing: date = None, date1 = None The correct output should be: date = 2021-05-13, date1 = 2021-05-14 The aim of this code is retrieve the date to export to excel by xlwt in django Any ideal about this issue? -
How do I solve a Django NoReverseMatch Error?
How do I solve a Django NoReverseMatch Error? When I visit basic_list, I get the error "Reverse for 'manage_account' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['manage_account/(?P[0-9]+)/$']" but all the other links are working. models.py from django.db import models class Wine(models.Model): name = models.CharField(max_length=300) year = models.IntegerField() objects = models.Manager() def __str__(self): return str(self.pk) + ": " + self.name class Account(models.Model): username = models.CharField(max_length=20) password = models.CharField(max_length=20) objects = models.Manager() def __str__(self): return str(self.pk) + ": " + self.username urls.py from django.urls import path from . import views urlpatterns = [ path('login', views.view_login, name='view_login'), path('basic_list', views.view_basic_list, name='view_basic_list'), path('manage_account/<int:pk>/', views.manage_account, name='manage_account'), ] views.py from django.shortcuts import render, redirect, get_object_or_404 from .models import * from django.core.exceptions import ObjectDoesNotExist def view_login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') account = Account.objects.get(username=username) if password == account.password: return redirect('view_basic_list') else: return render(request, 'myapp/login.html', {'warning': "Invalid login"}) else: return render(request, 'myapp/login.html') def view_basic_list(request): wine_objects = Wine.objects.all() return render(request, 'myapp/basic_list.html', {'Wines':wine_objects}) def manage_account(request, pk): a = get_object_or_404(Account, pk=pk) return render(request, 'myapp/manage_account.html', {'a': a}) basic_list.html {% extends 'myapp/base.html' %} {% load static %} {% block content %} <div class="container"> <div class="row"> <div class="col-12"> <table class="table table-striped"> <thead> <th scope="col"> Name </th> <th … -
JsonField in Django for MySQL
I currently use django 3.2 and MySQL as database, I want use MySql Json Field. For this reason use django-mysql third party package in my project. After create model got this Warning: (django_mysql.W004) django_mysql.models.JSONField is deprecated. HINT: Use django.db.models.JSONField or django-jsonfield-backport instead. If i use django.db.models.JSONField as json field, django use specific MySQL's JsonField ? Dose any effect on preformance? Which one has best performance on database? -
How to change the URL structure of already Google Indexed Django Website?
I have a Website built in Django. The blogs posts of my website have the url https://saralgyaan.com/posts/. But due to extensive posting on Facebook, it banned the url https://saralgyaan.com/posts/ (I still can post https://saralgyaan.com on Facebook). So, I was wondering, if I could remove the posts from my URL, I would be able to share my posts on Facebook. I need to change the URL structure to this effect. But my website is already indexed on Google and I get organic search landing on almost 10 pages, so I don't want to disrupt that. I was wondering If somehow I could use the RedirectView to redirect https://saralgyaan.com/ to https://saralgyaan.com/posts/. Is it possible? Will Facebook allow me to post or it will detect the redirect URL and again stop me from posting it. My urls.py of application is from django.urls import path, re_path from .views import( posts_search, posts_create, posts_detail, posts_edit, posts_delete, show_category, tag_posts, posts_publish, category_create ) urlpatterns = [ path('', posts_search, name='search'), path('create/', posts_create, name='create'), path('category/', category_create, name='category_create'), re_path(r'^category/(?P<hierarchy>.+)/$', show_category, name='category'), # path('category/<slug>/', show_category, name='category'), path('<slug>/', posts_detail, name='detail'), path('<slug>/edit/', posts_edit, name='edit'), path('<slug>/publish/', posts_publish, name='publish'), path('<slug>/delete/', posts_delete, name='delete'), path('tags/<tag>/', tag_posts, name='tag_posts') ] And the urls.py of the project is urlpatterns = [ … -
ValueError at /profile/ ModelForm has no model class specified. Error django
Iam coding in django and trying to figure how to update profile of a user in my app Please help me Iam trying to learn how to code and this is a big barrier for me to learn here's models.py: from django.db import models from django.contrib.auth.models import User # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete= models.CASCADE) image = models.ImageField(default='default.jpg',upload_to="profile_pics") def __str__(self): return f'{self.user.username} Profile' here's my views.py: from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get("username") messages.success(request, f'Yor account has been created! You are now able to login') return redirect('/login') else: form = UserRegisterForm() return render(request, 'users/register.html',{'form': form}) @login_required def profile(request): u_form = UserUpdateForm(instance = request.user) p_form = ProfileUpdateForm(instance= request.user.profile) context = { 'u_form': u_form, 'p_form': p_form } return render(request, 'users/profile.html', context) Iam getting error at 'u_form':u_form, and This is my forms.py: from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email','password1','password2'] class UserUpdateForm(forms.ModelForm): email = forms.EmailField() class Meta: model = … -
What is the best way to conditionally set the choices of a `serializers.ChoiceField` based on the value given to another field
Let's assume I have a choice field named chart. If the user inputs 'line' for the chart field, the following operations should be accepted: min, max, avg, and sum. If the user inputs 'pie' for the chart field, the following operations should be accepted: count and top-count. from rest_framework import serializers CHARTS = ['line', 'pie'] CHART_OPERATIONS = { 'line': ['min', 'max', 'avg', 'sum'], 'pie': ['count', 'top_count'], } class ChartDataSerializer(serializers.Serializer): chart = serializers.ChoiceField(choices=CHARTS) # operation = serializers.ChoiceField(choices=CHART_OPERATIONS[chart]) -
How to access heroku config vars using javascript in order to pass to Square Payment?
I am trying to add Square's Web Payment SDK to my site. I am using latest python, Django and hosting on Heroku. I need to access the APPLICATION_ID and LOCATION_ID which will be stored in Heroku Config Vars. These are required in order to display the card payment form on my site. I know javascript cannot access them and the only solution I have seen requires setting up a templatetag and having the input="hidden" in the HTML. How to access environment variable from html or js in Django Square provides the following code to include in my HTML however, I cannot simply replace APPLICATION_ID with its value in the text as it must be kept secret and I dont want it in the DOM. <body> <form id="payment-form"> <div id="card-container"></div> <button id="card-button" type="button">Pay</button> </form> <!-- Configure the Web Payments SDK and Card payment method --> <script type="text/javascript"> async function main() { const payments = Square.payments(APPLICATION_ID, LOCATION_ID); const card = await payments.card(); await card.attach('#card-container'); async function eventHandler(event) { event.preventDefault(); try { const result = await card.tokenize(); if (result.status === 'OK') { console.log(`Payment token is ${result.token}`); } } catch (e) { console.error(e); } }; const cardButton = document.getElementById('card-button'); cardButton.addEventListener('click', eventHandler); } main(); </script> … -
Variables reset when render a piece of html
i´m very new using django and in programming itself and i'm having some trouble rendering properly my templates. I managed to create a live search from my oracle DB using Ajax and JQuery. Currently i'm trying to add the names that my live search brings into an array and then pass it to the back end and do some more stuff with it but each time i search a new name, my array is emptied. Also if my livesearch brings more than one result, each time i try to add it to my array, it creates a new one instead of adding it This are my templates: base.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script></script> <title></title> </head> <body> {% block content %} {% endblock %} </body> {% load static %} <script src="{% static "jquery/jquery.js" %}"></script> <script src="{% static "jquery/plugins/jquery.cookie.js" %}"></script> <script> $(document).ready(function () { $("#livesearch").on('input', function (e) { e.preventDefault(); search_text = $("#livesearch").val() // console.log(search_text) $.ajax({ method: 'post', url: 'livesearch/', data: { text: search_text }, beforeSend: function (xhr, settings) { xhr.setRequestHeader("X-CSRFToken", $.cookie('csrftoken')); }, success: function (res) { $("#results").html(res); console.log(res) } }) }) $("#agregar_usuario").click(function (e) { e.preventDefault(); let user_picked = $("#users option:selected").text(); var users_to_be_added … -
How to capture a field instance during django-import-export upload
I'd like to import data into my resource minus the school field because the logged in user already belongs to a specific school. How would I do it without having the school field in my excel??? class uploadStudents(LoginRequiredMixin,View): context = {} def get(self,request): form = UploadStudentsForm() self.context['form'] = form return render(request,'upload.html',self.context) def post(self, request): form = UploadStudentsForm(request.POST , request.FILES) data_set = Dataset() if form.is_valid(): file = request.FILES['file'] extension = file.name.split(".")[-1].lower() resource = ImportStudentsResource() if extension == 'csv': data = data_set.load(file.read().decode('utf-8'), format=extension) else: data = data_set.load(file.read(), format=extension) result = resource.import_data(data_set, dry_run=True, collect_failed_rows=True, raise_errors=True) if result.has_validation_errors() or result.has_errors(): messages.success(request,f'Errors experienced during import.') print("error", result.invalid_rows) self.context['result'] = result return redirect('import_students') else: result = resource.import_data(data_set, dry_run=False, raise_errors=False) self.context['result'] = None messages.success(request,f'Students uploaded successfully.') else: self.context['form'] = UploadStudentsForm() return render(request, 'upload.html', self.context) The resource class ImportStudentsResource(resources.ModelResource): school = fields.Field(attribute = 'school',column_name='school', widget=ForeignKeyWidget(School, 'name')) klass = fields.Field(attribute = 'klass',column_name='class', widget=ForeignKeyWidget(Klass, 'name')) stream = fields.Field(attribute = 'stream',column_name='stream', widget=ForeignKeyWidget(Stream, 'name')) class Meta: model = Student fields = ('school','student_id','name','year','klass','stream') import_id_fields = ('student_id',) import_order = ('school','student_id','name','year','klass','stream') -
Elasticsearch scoring on multiple indexes: dfs_query_then_fetch returns the same scores as query_then_fetch
I have multiple indices in Elasticsearch (and the corresponding documents in Django created using django-elasticsearch-dsl). All of the indices have these settings: settings = {'number_of_shards': 1, 'number_of_replicas': 0} Now, I am trying to perform a search across all the 10 indices. In order to retrieve consistent scoring between the results from different indices, I am using dfs_query_then_fetch: search = Search(index=['mov*']) search = search.params(search_type='dfs_query_then_fetch') objects = search.query("multi_match", query='Tom & Jerry', fields=['title', 'actors']) I get bad results due to inconsistent scoring. A book called 'A story of Jerry and his friend Tom' from one index can be ranked higher that the cartoon 'Tom & Jerry' from another index. The reason is that dfs_query_then_fetch is not working. When I remove it or substitute with the simple query_then_fetch, I get absolutely the same results with the identical scoring. I have tested it on URI requests as well, and I always get the same scores for both search types. What can be the reason for it? -
Django and HTMLcalendar
I have created a calendar in django using HTMLcalendar. I also created a model with a 'date' field which is a datetimefield.Now, i was wondering if it was possible to add a link to each day of the calendar, so that when clicked renders the template with all the objects queried. -
How to include html template into another html with javascript
I have an html page called main.html that is extended with base.html. I like to find a solution how can I include another html template (individual_sum.html) into it with the javascript too. individual_sum.html has lots of javascript codes in the file. I don't use external javascript file because I don't know how if there any way to use Django Template Language in js. I have queries in my view that pushes data dynamically so I need DTL. I included the individual_sum.html into the main.html and the content appears but charts and other javascript stuff are blank. main.html {% extends 'stressz/base.html' %} {% block body%} content of main.html {% include 'stressz/individual_sum.html' %} {% endblock %} Is there any solution to have fully (with javascript) working individual_sum.html in main.html? Or can I use external javascript file that has Django's for and if/elif statements working in it? My aim is to have smaller separated files and not one giant. -
What is the use of "created" attribute of django post_save() signal?
Is there any use of created attribute in django's post_save() signal as it is always returning true. The post_save() will be called only when an object has been created, so what's the need for verifying it with created attribute? -
ModuleNotFoundError: No module named 'models' and TypeError: argument of type 'PosixPath' is not iterable
I tried the previous fixes in other tutorials but they didn't work. Here's what I have: ... from models import Tutorial #crashes from backend.restApis.tutorials.serializers import TutorialSerializer @api_view(['GET', 'POST', 'DELETE']) def tutorial_list(request): # GET list of tutorials, POST a new tutorial, DELETE all tutorials if request.method == 'GET': tutorials = Tutorial.objects.all() title = request.GET.get('title', None) if title is not None: tutorials = tutorials.filter(title__icontains=title) tutorials_serializer = TutorialSerializer(tutorials, many=True) return JsonResponse(tutorials_serializer.data, safe=False) ... I have tried renaming the reference but it doesn't work, here's the file structure Project File Structure I am new to django and appreciate any help ! -
Django. Admin. Upload image from database
How can I select images for ImageField in admin from those already loaded earlier in the database? -
Test Django ImageField with Pytest
I am trying to write a test for the following model class Person(models.Model): name = models.CharField(max_length=100) image = models.ImageField(upload_to='images') The fixture for it is as below: @pytest.fixture def generate_img(): root = join(dirname(__file__), 'imgs') return [join(root, "test_image.png")] @pytest.fixture def person_single(generate_img): return {'name':'test name', 'image': open(generate_img[0], 'rb')} How do I test the image upload correctly? -
Getting error ModuleNotFoundError: No module named 'rest_framework_sso'
I am following https://pypi.org/project/djangorestframework-sso/ tutorial for sso authentication in django, In first step they added 'rest_framework_sso' in INSTALLED_APPSin settings.py without installing any such liberary. When I tried to do the same I got: ModuleNotFoundError: No module named 'rest_framework_sso' Then I tried pip/pip3 install 'rest_framework_sso' but I got: ERROR: Could not find a version that satisfies the requirement rest_framework_sso (from versions: none) ERROR: No matching distribution found for rest_framework_sso Then I installed django rest framework but it is stil not working. I want to know why is it not working and how can I solve this, I didn't found anything that can help me related to this. -
Exception with django-awesome-avatar, ModuleNotFound
I am trying to install and use awesome avatar for my user from awesome_avatar.fields import AvatarField class MyUser(models.Model): image = AvatarField(upload_to='users/%Y/%m/%d/', width=100, height=100) but when i trying to start my project i had an problem with module name "StringIo" from StringIO import StringIO ModuleNotFoundError: No module named 'StringIO' I tried to install it but it has not a proper version of it Here full text of error Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\andre\AppData\Local\Programs\Python\Python38-32\lib\site-packages\awesome_avatar\fields.py", line 8, in <module> from cStringIO import StringIO ModuleNotFoundError: No module named 'cStringIO' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\andre\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\andre\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\andre\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\andre\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "C:\Users\andre\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\andre\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "C:\Users\andre\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\andre\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\andre\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\andre\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\apps\config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "C:\Users\andre\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen … -
Django issue with post_delete signal when deleting a object having child objects of the same model
When the post_delete signal is used to send a notification alert to user about comment deletion the following error occurs only when there is replies associated with it. If the comment has no replies it works fine. Comment models.py partial code user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, default=None) parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True) content = models.TextField() So, the comment without a parent is main comment and with a parent is reply. signals.py partial code def CommentDelete_handler(sender, instance, **kwargs): print(instance) post_delete.connect(CommentDelete_handler, sender=Comment) Here just accessing the instance will generate an error Comment matching query does not exist. I am not clear with the working mechanism inside this process, and why it works with a single comment but when it has replies inside it generates errors. Note: I fixed this case using the pre_delete signal instead of the post one which works fine in both cases. If anyone suggests the working mechanism and why post_signal fails on this or is there any update I can do to make it work in post_signal. Thank you for the support. -
How do I solve a Django NoReverseMatch Error?
When I visit basic_list, I get the error "Reverse for 'manage_account' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['manage_account/(?P[0-9]+)/$']" but all the other links are working. models.py from django.db import models class Wine(models.Model): name = models.CharField(max_length=300) year = models.IntegerField() objects = models.Manager() def __str__(self): return str(self.pk) + ": " + self.name class Account(models.Model): username = models.CharField(max_length=20) password = models.CharField(max_length=20) objects = models.Manager() def __str__(self): return str(self.pk) + ": " + self.username urls.py from django.urls import path from . import views urlpatterns = [ path('login', views.view_login, name='view_login'), path('basic_list', views.view_basic_list, name='view_basic_list'), path('manage_account/<int:pk>/', views.manage_account, name='manage_account'), ] views.py from django.shortcuts import render, redirect, get_object_or_404 from .models import * from django.core.exceptions import ObjectDoesNotExist def view_login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') account = Account.objects.get(username=username) if password == account.password: return redirect('view_basic_list') else: return render(request, 'myapp/login.html', {'warning': "Invalid login"}) else: return render(request, 'myapp/login.html') def view_basic_list(request): wine_objects = Wine.objects.all() return render(request, 'myapp/basic_list.html', {'Wines':wine_objects}) def manage_account(request, pk): a = get_object_or_404(Account, pk=pk) return render(request, 'myapp/manage_account.html', {'a': a}) basic_list.html {% extends 'myapp/base.html' %} {% load static %} {% block content %} <div class="container"> <div class="row"> <div class="col-12"> <table class="table table-striped"> <thead> <th scope="col"> Name </th> <th scope="col"> Year </th> </thead> <tbody> {% for d …