Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
save extra field values into the database from django signup page
I manage to get a extra field (state name) on Sign-Up page (using forms.ModelForm) but I am struggling to save it in the database. I have 2 database connections, the default database is to keep Django tables and project_db to keep program tables wondering if this is causing the issues? or with forms.py file. below is forms.py file. class UsersRegisterForm(forms.ModelForm): class Meta: model = User fields = [ "username", "state_name", "email", "confirm_email", "password", ] username = forms.CharField() state_name = forms.ModelChoiceField(queryset=SchPartneredStates.objects.all(),empty_label=None) email = forms.EmailField(label="Email") confirm_email = forms.EmailField(label="Confirm Email") password = forms.CharField(widget=forms.PasswordInput) def __init__(self, *args, **kwargs): super(UsersRegisterForm, self).__init__(*args, **kwargs) self.fields['username'].widget.attrs.update({ 'class': 'form-control', "name": "username"}) self.fields['state_name'].widget.attrs.update({ 'class': 'form-control', "name": "state_name"}) self.fields['email'].widget.attrs.update({ 'class': 'form-control', "name": "email"}) self.fields['confirm_email'].widget.attrs.update({ 'class': 'form-control', "name": "confirm_email"}) self.fields['password'].widget.attrs.update({ 'class': 'form-control', "name": "password"}) def clean(self, *args, **keyargs): email = self.cleaned_data.get("email") confirm_email = self.cleaned_data.get("confirm_email") username = self.cleaned_data.get("username") state_name = self.cleaned_data.get("state_name") password = self.cleaned_data.get("password") if email != confirm_email: raise forms.ValidationError("Email must match") email_qs = User.objects.filter(email=email) if email_qs.exists(): raise forms.ValidationError("Email is already registered") username_qs = User.objects.filter(username=username) if username_qs.exists(): raise forms.ValidationError("User with this username already registered") if len(password) < 8: # you can add more validations for password raise forms.ValidationError("Password must be greater than 8 characters") return super(UsersRegisterForm, self).clean(*args, **keyargs) -
Validating reCAPTCHA v3 in Django
In reCAPTCHA V2, I could verify in the views.py itself. However in V3 I don't know how to proceed. Now I'm using it in development with 127.0.0.1. First I have generated the site key and the secret key. In settings.py I have added secret key, GOOGLE_RECAPTCHA_SECRET_KEY = 'my_secret_key_here' Then in my signup.html I have, <script src='https://www.google.com/recaptcha/api.js?render=my_site_key_here'></script> Unlike previous there is no < div > tag to add the checkbox. The script itself is rendering the recaptcha symbol in the side of my browser. My question is, How can I validate using grecaptcha.execute. Do I have to add the script with my site key to every page I want to protect from spam or is there any simple way -
AssertionError: URL name is needed to resolve correct wizard URLs django 2,1
class ListingWizard(LoginRequiredMixin , StaffuserRequiredMixin,NamedUrlSessionWizardView): # class attribute named : form_list form_list = ( ('listing_data',ListingForm), ('images',ListingImageForm), ('attributes',AttributeListingForm), ) TEMPLATES = { 'listing_data':'admins/step1.html', 'images':'admins/step2.html', 'attributes':'admins/step3.html' } please some one can help me , i'm try to add wizard for to my django project , i dont know how define its url in new version of django 2.1 , thanks for advice -
override UserCreationForm in django
I want to create users (up to 1000) with default password. so how can i override django base UserCreationForm ? I tried this (for possibility) in base django UserCreationForm but passwords get erased when form tries to cleaned_data... self.base_fields['password1'].default = "Xyz@1234" self.base_fields['password2'].default = "Xyz@1234" -
Why the safe filter is affected by the bootstrap design (rich text)!
I use ckeditor as a text editor in the Django application along with Bootstrap The problem is that the design of the bootstrap before the filter safe {{td.snippet1 }} is working normally, but when the filter is added {{td.snippet1|safe }}, the design is affected terribly and badly, i don't know why <!-- container --> {% for td in three %} {{td.title}} {{td.snippet1|safe }} {{ td.article_author }} {{ td.posted_on}} {% endfor %} -
How to make cron time editable for django admin
I have to allow the admin the set the cron time from admin view in django. Like i have an configuration model , where admin can put the time as record 2 am (record 1) 4 pm (record 2) So on each record i have to run the cron. But cron time is in setting.py CRONJOBS = [ ('*/5 * * * *', 'myapp.cron.my_scheduled_job') ] https://pypi.org/project/django-crontab/ How to make this setting available for admin. -
Loading and parse xlsx file
How can I continue working with the downloaded file? parse it into the model views.py def model_form_upload(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('home') else: form = DocumentForm() return render(request, 'core/model_form_upload.html', { 'form': form }) my model.py class Document(models.Model): description = models.CharField(max_length=255, blank=True) document = models.FileField(upload_to='documents/') uploaded_at = models.DateTimeField(auto_now_add=True) class Parameters(models.Model): par_time = models.DateTimeField('date') par_recipe = models.CharField(max_length=200) par_machine = models.CharField(max_length=200) par_fa = models.CharField(max_length=200) par_ag_typ = models.CharField(max_length=200) par_rollennr = models.IntegerField(default=0) par_definition_id = models.IntegerField(default=0) par_name = models.CharField(max_length=200) par_value = models.IntegerField(default=0) Used for download Excel files (xlsx). Fields in xlsx are represented as described in the model. As soon as I didn’t try, I’m new to Django and I’ve got nothing -
how to add path in div/style using jinja
I have this code. <div class="g-fullheight--xs g-bg-position--center swiper-slide" style="background:{% static'/img/1920x1080/02.jpg' %}"> but it's doesn't work. how to add path in style. As correct using Jinja The origin code is <div class="g-fullheight--xs g-bg-position--center swiper-slide" style="background: url('img/1920x1080/01.jpg');"> -
Django: Accessing value of a field of one form into another form
Following are my django models:- class VisitorInfo(models.Model): username = models.CharField(max_length=120,null=True,blank=False) items_searched = models.ManyToManyField(ItemsSearched,blank=True) pages_visited = models.ManyToManyField(Page,blank=True) class Page(models.Model): page = models.CharField(max_length=120) def __str__(self): return self.page class ItemsSearched(models.Model): visitor = models.ForeignKey('VisitorInfo',on_delete=models.CASCADE,null=True,blank=True) itemssearched = models.CharField(max_length=120) def __str__(self): return self.itemssearched class TestPersona(models.Model): name = models.CharField(max_length=120,primary_key=True,default='Persona1') def __str__(self): return self.name class TestPersonaKey(models.Model): key_label = models.CharField(max_length=100,null=True,blank=True) persona = models.ForeignKey('TestPersona',on_delete=models.CASCADE) persona_key = models.CharField(max_length=120,primary_key=True,default='Key1') def __str__(self): return self.persona_key class KeyValue(models.Model): persona_key = models.ForeignKey('TestPersonaKey',on_delete=models.CASCADE) keyvalue = models.CharField(max_length=120,null=True) def __str__(self): return self.keyvalue Following are django forms. class PersonaNameForm(forms.ModelForm): name = forms.CharField(label='Person Name',max_length=100) class Meta: model = TestPersona fields = ["name",] class KeyForm(forms.ModelForm): key_label = forms.CharField(label='Give Label',max_length=100) persona_key = forms.ChoiceField(label='KEY',choices=(('itemssearched','ITEMS SEARCHED'),('username','USERNAME'),('pages','PAGES VISITED'))) class Meta: model = TestPersonaKey fields = ['key_label','persona_key',] I want your help here class KeyValueForm(forms.ModelForm): #if persona_key selected in KeyForm is ITEMS SEARCHED: #value = forms.MultipleChoiceField(label='Value', choices= all the items in ItemsSearchedModel) #if persona_key selected in KeyForm is USERNAME: #value = forms.ChoiceField(label='Value',choices= all the usernames in VisiterInfo model) #if persona_key selected in Key Form is PAGES VISITED: #value = forms.MultipleChoiceField(label='Value',choices= all the pages in Page model) I learnt the way to write views and template in this type of situation from this answer Get Django form field from model field . Please let me know whether view and … -
Javascript: Print on HTML browser the updated GPS value on a new line after 1 second interval
How do I print on HTML browser the updated value of the watchPosition() or getAccurateCurrentPosition() method on a new line after every 1 second interval? The updated value consists of Time | Latitude | Longitude | Accuracy to be shown on the HTML browser. Below is my code which only prints the location to the browser only once. How could I modify this code? I used a variation of getCurrentPosition(), the getAccurateCurrentPosition() to return a better result below. Would it be possible to insert a timer and loop the code through? How could I prevent the HTML page from erasing the previous lines of GPS result and only add new lines to the browser? Thank you for any assistance, I sincerely appreciate it. location.html <p>Click the button to add coordinates.</p> <button onclick="getLocation()" class="btn btn-primary">Get Your Location</button> <p id="result"></p> <form method='POST' action="" enctype="multipart/form-data"> <p>{{ form | crispy }}</p> {% csrf_token %} <button type="submit" id="btn_submit" class="btn btn-primary form-control" disabled>Submit</button> </form> script.js function progress(position) { $("#result").text(`In progress. Please wait for 15 seconds.`); } function error(err) { console.warn(`ERROR(${err.code}): ${err.message}`); } function showPosition(position) { console.log(position); var latitude = position.coords.latitude; var longitude = position.coords.longitude; var accuracy = position.coords.accuracy; $('#id_latitude').val(latitude); $('#id_longitude').val(longitude); $('#id_accuracy').val(accuracy); $("#result").html(`Latitude: ${latitude}<br>Longitude: ${longitude}<br>Accuracy: ${accuracy}`); $("#btn_submit").attr("disabled", … -
hello_world() missing 1 required positional argument: 'request'
Please assist figuring out solution to this error. courses/ views.py from django.http import HttpResponse from django.shortcuts import render from .models import Course def course_list(request): courses = Course.objects.all() return render(request, 'courses/course_list.html',{'courses':courses}) admin/ views.py from django.shortcuts import render def hello_world(request): return render(request, 'home.html') admin urls.py from django.contrib import admin from django.urls import path from courses import views from django.conf.urls import include from . import views urlpatterns = [ path('admin/', admin.site.urls), path('admin/', views.hello_world()), path('courses/', include('courses.urls')), path('courses/', views.course_list(), name='listofcourses'), ] courses/ urls.py from django.urls import path from . import views urlpatterns=[ path('',views.course_list, name="listofcourses"), ] Now on running server, i am getting this error hello_world() missing 1 required positional argument: 'request' I wish to publish homepage on running server at 127.0.0.1:8000 and courses page on 127.0.0.1:8000/courses Thank you in advance -
How do I query objects of all children and their chield with Django mptt?
I have created a model but when i am trying to access all child and also their child. parent child 1 child 1-1 child 2 child 2-1 Is there way to get all child node. I am doing like this but not able to all child. 1st Query query_set = Category.objects.get(name='parent').get_family().order_by('tree_id', 'lft') 2nd Query query_set = Category.objects.get(name='parent').get_descendants().order_by('tree_id', 'lft') But I am unable to get all object that is associate with parent and their child. I need record should be [child 1, child 1-1, child 2, child 2-1] -
Django users created through proxy can't login
I created a model inheriting from django.contrib.auth.models.User, and extended it with more fields, and then created a proxy that overrides save() method to hash the password, but users created through this proxy can't login. I traced the process and found that user.check_password() always fails, but I don't know the reason. This is my model and its proxy: class UserExtended(User): albums = models.ManyToManyField(Album, null=True, blank=True, verbose_name='Albums') class Meta: verbose_name = _("User") verbose_name_plural = _("Users") def __str__(self): return "[{}] {} ({})({}{})".format(self.id, self.email, self.username, self.first_name, self.last_name) class UserExtendedProxy(UserExtended): class Meta: proxy = True def save(self, *args, **kwargs): if not self.id: try: user = User.objects.get(email=self.email) except: pass else: raise Exception('eMail already in use.') self.set_password(self.password) super(UserExtendedProxy, self).save(*args, **kwargs) Token.objects.create(user=self) And this is my ModelBackend: class EmailBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwars): UserModel = get_user_model() try: user = UserModel.objects.get(email=username) except UserModel.DoesNotExist: return None else: if user.check_password(password): return user return None I can see in my database that users created through this proxy actually exist in *django.contrib.auth.models.User** model, so I can't figure out why they can't log in. Another issue is that superuser created through python manage.py createsuperuser doesn't exist for UserExtendedProxy. -
How to return data from nested serializers inside serializers built on the fly?
Recently I have been trying out new things with Django, to try and simplify writing responses in the views, might not be worth doing in the end, but I'm still interested to see if it can be done. So typically, we would have the following serializer for returning back information; # serializers.py class SomeDefinedSerializer(serializers.ModelSerializer): extra_model = SomeExtraModelSerializer() greet_name = serializers.SerializerMethodField() class Meta: model = SomeDefinedModel fields = ('name', 'age', 'field1', 'field2') def get_greet_name(self, obj): return f"Hello {obj.name}" Now with this defined serializer, we can return just the fields we want, and then assumming in SomeExtraModelSerializer() we have defined a subset of fields, we get back a nice dictionary of values with calling .data. But doing this, with large-scale apps, we will end up writing loads and loads of serializers that just get used for specific tasks, resulting in a lot of code that is almost virtual similar. Of course, we dont HAVE to do it this way, we could make more general serializers, but that means that all the different tasks from the frontend end up getting a huge surplus of information, that in reality only a small percentage of the data gets used. So my original thought was to … -
How to send data back to Android app from django rest framework using asynchttp?
Model.py class Server(models.Model): label = models.TextField(max_length=200,null=True) #compare this upload1 = models.FileField(null=True, blank=True) Image1 = models.TextField(upload1, null=True) class Android(models.Model): label=models.TextField(max_length=200,null=True) #with this imagestring=models.TextField(null=True,blank=True) returnlabel=models.TextField(null=True,blank=True) So in my serializer class i am comparing labels from Android model and server model in (def get_returnlabel),and i want to return this label back to my android app.Any suggestons on how to do it.On my android app I am using async http. Serializer.py class FoodSerializers(serializers.HyperlinkedModelSerializer): class Meta: model=Server fields=('url','label','Image1','upload1') class AndroidSerializers(serializers.ModelSerializer): class Meta: model = Android fields = ('label', 'imagestring', 'returnlabel') (<--returnlabel back to android app) #Compare label from Server and Android def get_return_label(self, obj): queryset = Server.objects.filter( labelServer=obj.label) queryset_serializer = FoodSerializers( queryset, many=True, read_only=True) return queryset_serializer.data Views.py class FoodViewSet(viewsets.ModelViewSet): queryset = Server.objects.all() serializer_class =FoodSerializers class Androids(viewsets.ModelViewSet): queryset =Android.objects.all() serializer_class = AndroidSerializers -
Dynamic django model
I have ProjectCategoryCountPartition model. And 3 classmethod to create partition model. class ProjectCategoryCountPartition(models.Model): city_slug = models.CharField(verbose_name=_('City slug'), max_length=255, db_index=True) domain = models.CharField(verbose_name=_('Site name'), max_length=255) category_id = models.PositiveIntegerField(verbose_name=_('Category id')) name = models.CharField(verbose_name=_('Category project name'), max_length=255) count = models.PositiveIntegerField(default=0) class Meta: db_table = "wbtm_projects_category_partition" class DefaultMeta: db_table = "wbtm_projects_category_partition" ATTRIBUTE = { 'city_slug': models.CharField(verbose_name=_('City slug'), max_length=255, db_index=True), 'domain': models.CharField(verbose_name=_('Site name'), max_length=255), 'category_id': models.PositiveIntegerField(verbose_name=_('Category id')), 'name': models.CharField(verbose_name=_('Category project name'), max_length=255), 'count': models.PositiveIntegerField(default=0) } @classmethod def check_partition(cls, city_slug): city_slug = cls.check_city_slug(city_slug) default_db_table = cls.DefaultMeta.db_table new_db_table = "{}_{}".format(default_db_table, city_slug) if new_db_table in connection.introspection.table_names(): return True return False @classmethod def check_city_slug(cls, city_slug): city_slug = city_slug.replace('-', '_') if not re.match('^[a-zA-Z0-9_]+?$', city_slug): raise Exception('Unsupported city_slug') return city_slug @classmethod def create_partition(cls, city_slug): city_slug = cls.check_city_slug(city_slug) default_db_table = cls.DefaultMeta.db_table new_db_table = "{}_{}".format(default_db_table, city_slug) if cls.check_partition(city_slug): return new_db_table queries = [ """ CREATE TABLE {}() INHERITS ({}); """.format(new_db_table, default_db_table), ] cursor = connection.cursor() for query in queries: cursor.execute(query) return new_db_table @classmethod def get_city_model(cls, city_slug): city_slug = cls.check_city_slug(city_slug) model_name = city_slug.replace('_','') db_table = cls.create_partition(city_slug) attrs = cls.DefaultMeta.ATTRIBUTE.copy() attrs.update({ '__module__': ProjectCategoryCountPartition.__module__, 'Meta': type( 'Meta', (), dict( # managed=False, db_table=db_table, ) ), }) return type("ProjectCategoryCountPartition{}".format(model_name), (models.Model,), attrs) When I use for an error occurs. The model apparently starts caching in memory or the fields … -
In Django REST Framework, why do serializers properly handle field-level validation exceptions in models but not object-level validation?
To illustrate my problem, let's say I have a simple Person model defined like this: from django.db import models from django.core.validators import MinLengthValidator, MaxLengthValidator, ValidationError class Person(models.Model): first_name = models.CharField(max_length=100, null=False, blank=False, validators=[MinLengthValidator(limit_value=1), MaxLengthValidator(limit_value=100)]) last_name = models.CharField(max_length=100, null=True, blank=True, validators=[MinLengthValidator(limit_value=1), MaxLengthValidator(limit_value=100)]) def clean(self): self.validate() super().clean() def save(self, *args, **kwargs): self.full_clean() super().save(*args, **kwargs) def validate(self): """The first and last names cannot be the same strings.""" if (self.first_name and self.last_name and self.first_name.lower() == self.last_name.lower()): raise ValidationError('First and last names, if both are provided, cannot be the same.', code='invalid', params={'first_name': self.first_name, 'last_name': self.last_name}) Notice that both the first_name and last_name fields have field-level validation associated with them. (My dev database is SQLite, and it does not do length validation. So I had to add validators. But that is not my question.) I defined two simple APIView-based classes: from rest_framework import generics from ..models import Person from ..serializers import PersonSerializer class PersonDetailView(generics.RetrieveUpdateDestroyAPIView): name = 'person-detail' queryset = Person.objects.all() serializer_class = PersonSerializer lookup_field = 'id' class PersonListView(generics.ListCreateAPIView): name = 'person-list' queryset = Person.objects.all() serializer_class = PersonSerializer lookup_field = 'id' I defined a serializer based on Django REST Framework's ModelSerializer: from rest_framework import serializers from ..models import Person class PersonSerializer(serializers.ModelSerializer): class Meta: model = Person fields … -
Incorrect schema in DRF documentation for custom ViewSet action
I have such ViewSet: class CarViewSet(ModelViewSet): """ Работа пользователя с его машинами. """ serializer_class = CarSerializer permission_classes = [IsUser] filter_fields = '__all__' ordering_fields = '__all__' def perform_create(self, serializer): serializer.save(user=self.request.user.useraccount) def get_queryset(self): return Car.objects.filter(user=self.request.user) @action(methods=['POST'], detail=True) def set_default(self, request, pk=None): """ Установить указанную машину по умолчанию """ car = get_object_or_404(self.get_queryset(), pk=pk) car.is_default = True car.save() return Response() And in rest_framework.documentation page I see such form for a "set_default" action: The problem is "set_default" actually don't need to provide all of these fields, it requires(and uses) only id! What can I do with this? -
vuejs + drf - unable to get data from drf api in vuejs using http/axios
enter image description here Unable to get data in Vue js from drf api using http / axios ? I am not getting any error also -
Spotify API {'error': 'invalid_client'} Authorization Code Flow [400]
This is one of my many attempts at making a POST request to https://accounts.spotify.com/api/token. Scope was set to 'playlist-modify-public, playlist-modify-private'. I'm using Python 3.7, Django 2.1.3. No matter what I do, response_data returns {'error': 'invalid_client'} I've tried many things, including passing the client_id/client_secret inside the body of the request as per the official Spotify documentation for this particular request... to no avail. Please help! def callback(request): auth_token = request.GET.get('code') # from the URL after user has clicked accept code_payload = { 'grant_type': 'authorization_code', 'code': str(auth_token), 'redirect_uri': REDIRECT_URI, } auth_str = '{}:{}'.format(CLIENT_ID, CLIENT_SECRET) b64_auth_str = base64.b64encode(auth_str.encode()).decode() headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': 'Basic {}'.format(b64_auth_str) } post_request = requests.post(SPOTIFY_TOKEN_URL, data=code_payload, headers=headers) response_data = json.loads(post_request.text) # ==> {'error': 'invalid_client'} -
Django and Celery to send requests to external API "remote end closed"
To collect data into my Postgres database I run a collection of requests to an external API every 10 minutes or so. This system has worked without a hitch for a few weeks but now about half of the requests timeout with the error: raise ConnectionError(err, request=request) requests.exceptions.ConnectionError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response',)) I can't really share much of the code as it is sensitive but I can share the vague structure of it. def getData(): for thing in things: response = requests.request("POST", url, data=payload, headers=headers) and then getData() is run every 10 minutes by Celery. I would say the size of things is roughly 100 elements and typically it would finish in 50 seconds. -
Django - Return empty value from select tag of html
There's a form for students to register . Each of the students are in a school. And by using forms.ModelChoiceField the name of schools will be shown in the template using a 'select' tag. ( a dropdown list ) The main problem is, After choosing one 'option' of the 'select' tag , I can't get the select's value in views.py . models.py class School(models.Model): name = models.CharField(max_length=40) def __str__(self): return self.name class Student(models.Model): name = models.CharField(max_length=40) school = models.ForeignKey(School) def __str__(self): return self.name forms.py class SchoolForm(forms.ModelChoiceField): def label_from_instance(self, obj): return obj.name class StudentForm(forms.ModelForm): student_school = SchoolForm(queryset = School.objects.all()) class Meta: model = Student fields = ('name', 'school') views.py def student_register(request): if request.method == 'POST': form = StudentForm(request.POST) form.school = request.POST['school'] if form.is_valid(): form.save else: form = StudentForm() return render(request, 'index.html', {'form': form}) index.html <form method="post" action={% 'student_register' %}> {% csrf_token %} {{ form.name }} <select id="id_school" name="school"> {% for name in form.student_school %} <option value={{ name }}> {% endfor %} </select> </form> -
Saving data in rows in a Config table vs. saving as keys in a Postgres JSONField--which is better?
Since Postgres supports JSON fields, is that more preferential than say saving each config item in a row in some table the way WP still does? Full disclosure: I'm asking as a Django user new to postgres. -
I get a 'Forced update did not affect any rows' error when overriding save() method of Django Model
I have a model and a corresponding proxy: class UserExtended(User): albums = models.ManyToManyField(Album, null=True, blank=True, verbose_name='Albums') class Meta: verbose_name = _("User") verbose_name_plural = _("Users") def __str__(self): return "[{}] {} ({})({}{})".format(self.id, self.email, self.username, self.first_name, self.last_name) class UserExtendedProxy(models.UserExtended): class Meta: proxy = True def save(self, *args, **kwargs): from django.contrib.auth.hashers import make_password if not self.id: try: user = User.objects.get(email=self.email) except: pass else: raise Exception('eMail already in use.') self.password = make_password(self.password) super(UserExtendedProxy, self).save(args, kwargs) I think my logic is flawed because I get a Forced update did not affect any rows error when creating a new instance, but I can't find what causes the error. -
Cart in bootstrap navbar disappears after login
The cart icon on my navbar diasappears once the user logs in. I have tried to debug it but i cannot figure it out. What am I doing wrong? Do I need to authenticate the user similar to the login icon in the toolbar? <ul class="navbar-nav ml-auto"> {% if user.is_authenticated %} <li {% if 'dashboard' in request.path %} class="nav-item active mr-3" {% else %} class="nav-item mr-3" {% endif %} > <a class="nav-link" href="{% url 'profile' %}"> Welcome {{ user.username }}</a> </li> <li class="nav-item mr-3"> <a href="javascript:{document.getElementById('logout').submit()}" class="nav-link"> <i class="fas fa-sign-out-alt"></i> Logout </a> <form action="{% url 'logout' %}" method="POST" id="logout"> {% csrf_token %} <input type="hidden"> </form> </li> {% else %} <li {% if 'register' in request.path %} class="nav-item active mr-3" {% else %} class="nav-item mr-3" {% endif %} > <a class="nav-link" href="{% url 'register' %}"> <i class="fas fa-user-plus"></i> Register</a> </li> <li {% if 'login' in request.path %} class="nav-item active mr-3" {% else %} class="nav-item mr-3" {% endif %} > <a class="nav-link" href="{% url 'login' %}"> <i class="fas fa-sign-in-alt"></i> Login</a> <li {% if 'cart' in request.path %} class="nav-item active mr-3" {% else %} class="nav-item mr-3" {% endif %} > <a class="nav-link" href="{% url 'cart' %}"> <i class="fas fa-cart-plus"></i> Cart</a> </li> Before I …