Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django need help to build a complex query
I’m building a school schedule management system. I have the following models/tables: ID | Teacher ———————————— 1 | John 2 | Chris 3 | George ID | Module ——————————— 1 | Math 2 | History 3 | Physics Schedule ————— Date | Teacher | Module 15/2/2022 | 1 | 1 15/2/2022 | 1 | 2 15/2/2022 | 2 | 1 16/2/2022 | 1 | 1 16/2/2022 | 3 | 1 16/2/2022 | 3 | 2 16/2/2022 | 3 | 3 I in my app, that will have different date filters/modules filters for someone to select and it will do the following: Let’s say I click on the 15/2/2022 and on Math (ID: 1). The page should display the following: Module: Math, Teacher: John, Other modules on the same day: History Module: Math, Teacher: George, Other module on the same day: None Let’s say now I click on the 16/2/2022 and on Math, I will see: Module: Math, Teacher: George, Other modules on the same day: History, Physics I am stuck on how to build the queries to get the result above in one line. Can someone help me please? -
Django: How to pass {% url 'event_manager:index' %} to template component?
So right now I hardcode to url, which is a bit annoying if you move endpoints. This is my current setup for my navbar items. # in base.html {% include 'components/navbar/nav-item.html' with title='Event Manager' url='/eventmanager/' %} # in components/navbar/nav-item.html <li> <a href="{{ url }}">{{ title }}</a> </li> See how I use the url right now? What I now want is this: {% include 'components/navbar/link.html' with title='Event Manager' url={% url 'event_manager:index' %} %} But apparently, this is invalid syntax. How do I do it? If it is not possible, how do I create an app that somehow creates a view where I can pass all the URLs with context variable? In theory, this sounds easy but I'd have to somehow insert that view in every other view. -
Renaming files with an automatically generated ID
I'm building a website for an assignment and one of the features I'd like it to have is for it to assign a unique ID for any photograph that's uploaded to it. I have created a form which takes in a photo and I'm hoping to get it so rename the photo file to the photo ID and save it in a folder associated with the user that uploaded it (eg. if the userID was 1 and the photoID was 10, the file structure would be /media/userImages/1/10.jpg) However I'm having difficulty accessing the data I would need to do this. It seems like, with the way that I've set it up, that the photoID is generated when the form is saved. Here's the code: Views.py def addimage(request): form = ImageForm(request.POST, request.FILES) print(form.is_bound) if request.method == "POST": if form.is_valid(): form.time = datetime.datetime.now() picture = form.save(commit=False) picture.image.upload_to = "/manageImages/" + str(request.user.id) + "/" + str(picture.ID) print(picture.image.upload_to) picture.save() return redirect("/closeup/") elif request.POST: print("ERROR IN FORM") print(form.errors) Models.py class Picture(models.Model): ID = models.BigAutoField(primary_key=True) image = models.ImageField(upload_to='userImages/', null=False, blank=False) name = models.CharField(max_length=100) url = models.URLField() likes = models.IntegerField(default=0) dislikes = models.IntegerField(default=0) time = models.DateTimeField(auto_now_add=True) # TODO - add 'Uploaded by' foreign key Forms.py class ImageForm(forms.ModelForm): … -
No Reverse Match in Ecommerce
When go to url "http://localhost:8000/compras/finalizando/", raise the follow error: "Reverse for 'pagseguro_view' with arguments '('',)' not found. 1 pattern(s) tried: ['compras/finalizando/(?P[0-9]+)/pagseguro/\Z']" I cant understand what cause this error, somebody can help? my checkout/urls.py: from django.urls import path from .import views urlpatterns = [ path('carrinho/adicionar/<slug>', views.create_cartitem,name='create_cartitem'), path('carrinho/', views.cart_item, name='cart_item'), path('finalizando/', views.checkout, name='checkout'), path('finalizando/<int:pk>/pagseguro/', views.pagseguro_view, name='pagseguro_view'), path('meus-pedidos/', views.order_list, name='order_list'), path('meus-pedidos/<int:pk>/', views.order_detail, name='order_detail'), ] My checkout/views.py: from pagseguro import PagSeguro from django.shortcuts import get_object_or_404, redirect from django.views.generic import ( RedirectView, TemplateView, ListView, DetailView ) from django.forms import modelformset_factory from django.contrib import messages from django.urls import reverse_lazy, reverse from django.contrib.auth.mixins import LoginRequiredMixin from catalog.models import Product from .models import CartItem, Order class CreateCartItemView(RedirectView): def get_redirect_url(self, *args, **kwargs): product = get_object_or_404(Product, slug=self.kwargs['slug']) if self.request.session.session_key is None: self.request.session.save() cart_item, created = CartItem.objects.add_item( self.request.session.session_key, product ) if created: messages.success(self.request, 'Produto adicionado com sucesso') else: messages.success(self.request, 'Produto atualizado com sucesso') return reverse_lazy('checkout:cart_item') class CartItemView(TemplateView): template_name = 'checkout/cart.html' def get_formset(self, clear=False): CartItemFormSet = modelformset_factory( CartItem, fields=('quantity',), can_delete=True, extra=0 ) session_key = self.request.session.session_key if session_key: if clear: formset = CartItemFormSet( queryset=CartItem.objects.filter(cart_key=session_key) ) else: formset = CartItemFormSet( queryset=CartItem.objects.filter(cart_key=session_key), data=self.request.POST or None ) else: formset = CartItemFormSet(queryset=CartItem.objects.none()) return formset def get_context_data(self, **kwargs): context = super(CartItemView, self).get_context_data(**kwargs) context['formset'] = self.get_formset() return context def … -
Use object from django.view in jQuery function
I have jquery function, in the function there is an if statement (see arrow in code). In stead of the hard coded "John Pietersen" i want my django view object {{user.name}} which is passed in as context in this template. How can i use {{user.name}} in the jquery function $(document).ready(function(){ setInterval(function(){ $.ajax({ type: 'GET', url : "{% url "messages" item.id %}", success: function(response){ console.log(response); $("#display").empty(); for (var key in response.messages) if (response.messages[key].name === "John Pietersen") {. <------------------- { var temp = "<div class='container manager'><b>" + response.messages[key].name + "</b><p>" + response.messages[key].text + "</p><span class='time-left'>" + response.messages[key].timestamp + "</span></div>"; $("#display").append(temp); } }else{ var temp = "<div class='container medewerker'><b>" + response.messages[key].name + "</b><p>" + response.messages[key].text + "</p><span class='time-left'>" + response.messages[key].timestamp + "</span></div>"; $("#display").append(temp); } }, error: function(response){ alert('An error occured') } }); },1000); }) -
How to call Django REST serializer inside update?
I'm trying to make my update method add a link to my list to links. The problem is, the response of the PATCH request is an OrderedDict, and I would ideally prefer it to be serialized. I have tried calling my serializer inside the update method, but I'm not sure how get information for the data field of the LinkListSerializer, so I end up getting Cannot call .is_valid() as no data= keyword argument was passed when instantiating the serializer instance. Any advice would be appreciated, here is my code: class LinkListViewSet(viewsets.ModelViewSet, generics.RetrieveUpdateDestroyAPIView): queryset = LinkList.objects.all() serializer_class = LinkListSerializer filter_backends = [IsOwnerOrPublicFilter] permission_classes = [IsOwnerOrPublic] def update(self, request, *args, **kwargs): new_link, created = Link.objects.update_or_create( link=request.data.get('links'), defaults={'link': request.data.get('link')}, ) instance = self.get_object() if created: instance.links.add(new_link) instance.save() return Response(status=status.HTTP_200_OK) Serializer: class LinkListSerializer(serializers.ModelSerializer): url = serializers.HyperlinkedIdentityField(view_name="lists-detail") owner = serializers.HiddenField(default=serializers.CurrentUserDefault()) links = LinkSerializer(read_only=True, many=True) class Meta: model = LinkList fields = ['url', 'owner', 'name', 'public', 'links', 'description'] -
Unable to runserver in django project
I am having trouble using the runserver command (and other commands for that matter)in my django project. I have activated my virtual environment (source ./venv/bin/activate) and it displays as venv in my bash. Whenever I try to runserver in this virtual environment I get the error: File "manage.py", line 17 ) from exc ^ SyntaxError: invalid syntax I have read similar questions and attempted doing python2 or python 2.7 when writing the command, and I have tried deleting the 'from exc' on line 17 of the manage.py file. Driving me crazy as this was working fine a week or so ago! only thing I can think of that changed was that I accidentally dragged the project folder into another area (not in my desktop) and then moved it back once I realised this. Does anyone have any ideas or suggestions? -
django - custom field from CharField with default args
I'm trying to use multiple custom fields in my project. For example CurrencyField. I want to give it a default arguments like verbose_name - "mena" etc. Django raises error: kwargs['verbose_name'] = kwargs['verbose_name'] or 'Mena' I guess it's because I sometimes use verbose_name as a positional argument. How can I make it "universal"? class CurrencyChoices(models.TextChoices): EUR = 'EUR' CHF = 'CHF' CZK = 'CZK' DKK = 'DKK' GBP = 'GBP' HRK = 'HRK' HUF = 'HUF' PLN = 'PLN' RON = 'RON' SEK = 'SEK' USD = 'USD' class CurrencyField(models.CharField): def __init__(self, *args, **kwargs): kwargs['verbose_name'] = kwargs['verbose_name'] or 'Mena' kwargs['max_length'] = 5 kwargs['choices'] = CurrencyChoices.choices super().__init__(*args, **kwargs) -
How to boradcast messages received from rest api over websocket connection
I'm going to create a web-app. I want to use django, DRF, channels, DCRF,... . The app works like this: User can send any request(CRUD) over the http using rest-api, and besides i have a websocket connection that every one can connect and receive events in real-time. In this case I want to use websocket just for broadcasting events not receiving users requests (post, put, delete in http terminology). Those methods are made over rest-api and if user also is connected to websocket connection can receive events. The problem is, how to inform websocket(maybe object) that we have a new message (after saving the message)? I think about below scenarios: Is it possible to push message to a place that channels looks for receive messages? Or just after saving message send instance to channels receiver for broadcast new message. Is it possible at all, or not? if yes, HOW? if no, WHY? -
Database service dependency not working properly in docker-compose
I am building a webapp in Django. I want to use Postgres instead of default sqlite and wanted to achieve this using docker-compose. Here is my docker-compose file. I expect postgres to spin up before my app but unfortunately this does not happen. Whenever I try to run the docker-compose up command, my webapp starts building first and eventually gives me an error of the database connectivity which is also attached. version: '3.7' networks: metagov_network: services: policykit_app: container_name: policykit restart: always build: context: . dockerfile: Dockerfile args: POSTGRES_DB: metagov POSTGRES_HOST: database POSTGRES_USER: postgres POSTGRES_PASSWORD: supersecretpassword ports: - "8081:8080" depends_on: - database networks: - metagov_network database: image: postgres:alpine restart: always environment: - "POSTGRES_DB=metagov" - "POSTGRES_USER=postgres" - "POSTGRES_PASSWORD=supersecretpassword" ports: - "5432:5432" networks: - metagov_network volumes: - metagov-storage:/var/lib/postgresql/data volumes: metagov-storage: I run the command: docker-compose up --build -d --force-recreate My Dockerfile looks like this: FROM ubuntu WORKDIR metagov RUN apt install postgresql-client -y RUN apt install python3-pip -y COPY policykit metagov RUN pip3 install --no-cache-dir -r metagov/requirements.txt EXPOSE 8000 ARG POSTGRES_DB ARG POSTGRES_HOST ARG POSTGRES_USER ARG POSTGRES_PASSWORD RUN python3 metagov/manage.py makemigrations RUN python3 metagov/manage.py migrate ENTRYPOINT ["python3"] CMD ["metagov/manage.py", "runserver", "0.0.0.0:8000"] And this is the error I get: django.db.utils.OperationalError: could not translate host … -
Is it possible to add Google Maps markers of locations read from a file in Django?
I'm developing a Django project and I'm trying to render a map that contains several markers of different locations. I want to read these locations from a file, but up till now I used JS and HTML to render a map that contains a single marker on it. Here is the JS code: function initMap() { const uluru = { lat: 0.0018211100000000001, lng: 0.009671981000000001 }; const map = new google.maps.Map(document.getElementById("map"), { zoom: 4, center: uluru, }); const marker = new google.maps.Marker({ position: uluru, map: map, title: "Turbine 7", }); } and the HTML code is a only a div that contains the position of the map inside of it: <div id="map"></div> and here is a picture of the final output: -
How to print all the Routes used in Django?
I want to display all the Routes in an app built with Django, something like what Laravel does with the command: php artisan route:list Is there a way to get all the Routes? -
How to use the for range loop in django admin?
I need something like forloop.counter in templates. Is this possible? -
Django - second trigger of htmx tries to load an unexpected URL gives a 403 error
I have a table of cells, each with a different object instance, and using htmx to update the objects. I've created a CBV that takes the request.post from the htmx and saves the modified object to the db. The htmx does a hx-swap and loads a new <input> tag into my form, along with some background-color style based on the saved object. I can click on many cells and update several objects this way. This is working as expected and I don't see any errors. However, the second time that I try to update the same cell/object, I get a 403 error. This error does not show in the browser. The cell just seems unresponsive. I can continue updating other cells. The error shows up in my browser console. views asessmentdetail - view that loads template and retrieves all the objects to fill in the table def assessmentdetail(request, assess_pk, class_pk): """List the current grades for the assessment""" user = request.user assessment = Assessment.objects.get(id=assess_pk) classblock = Classroom.objects.get(id=class_pk) course_pk = classblock.course.pk objective_list = Objective.objects.all().filter( assessment=assess_pk).order_by('objective_name') student_list = Student.objects.all().filter( classroom=class_pk).order_by('nickname') gra = Grade.objects.filter( assessment=assess_pk).filter(cblock=classblock.id) context = {'objective_list': objective_list} new_or_update = gra.exists() grade_report = [str(new_or_update)] grade_list = [] grade_id_array = [] grade_report.append(len(objective_list)) # print(len(objective_list)) … -
how do I update fields in django
from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserRegisterForm(UserCreationForm): email = forms.EmailField(max_length=80) first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=30) dob = forms.DateField() address = forms.CharField(max_length=100) city = forms.CharField(max_length=30) country = forms.CharField(max_length=30) class Meta: model = User fields = ['first_name', 'last_name', 'username', 'email', 'dob', 'address' , 'city' , 'country' , 'password1', 'password2'] this is my code in forms.py It is used to create a profile. when I added new fields they show when creating the user but when I try to sow them on a profile page only a couple show. <div class="media-body"> <h2 class="account-heading">{{user.profile}}</h2> <p class="text-secondary">{{user.first_name}}</a> {{user.last_name}}</p> <p class="text-secondary">{{user.dob}}</p> <p class="text-secondary">{{user.email}}</p> <p class="text-secondary">{{user.address}}</p> <p class="text-secondary">{{user.city}}</p> <p class="text-secondary">{{user.country}}</p> </div> this is my code from my profile page but when I go onto my site it only shows the fields I created at the start before adding more later. -
Function doesn't update in asyncio
I'm writing a bot in aiogram with a backend on django for postgresql (had the same issue before converting from pure psycopg2). One of the finite states I'm in, should constantly check for updates in the DB, except it doesn't happen. Here's the code for the loop in bot: @dp.message_handler(state=Current.start_state) async def func(msg: types.Message, state: FSMContext): async def res(): return await function(args) global ticket ticket = await res() while ticket == -1: ticket = await res() if ticket == -1: await asyncio.sleep(3) print(ticket) #debugging I've tried it without the function: @dp.message_handler(state=Current.start_state) async def func(msg: types.Message, state: FSMContext): global ticket ticket = await function(args) while ticket == -1: ticket = await function(args) if ticket == -1: await asyncio.sleep(3) print(ticket ) And many other combinations, including making the loop condition while = True and having a break in the loop for when the condition is met. And I can insure you, the results change, I can see that in pgAdmin4 and by running this function separately in another script while the bot is running. It seems to work sometimes if I manually change the information in DB, and even then, not always. Basically, whilst this loop is running for user A, another … -
Displaying messages through django signals
I'm looking to make a django app that uses signals. (using django signals) There I would like to run some functions, and based on which output they give, send a message within the webpage. so for example, if the function fails i want to send a message saying it failed. this is pretty much want i would want in signals.py ----- def handle_event(request, *args, **kwargs): try: --unimportant-- except: messages.error(request, 'error message') post_save.connect(handle_event, sender=Event) how would i go about doing this? -
How to enable console scripts in Django?
Running Python 3.6 on Redhat. I've installed an extremely complicated project. 5 engineers worked on this for years, but they are all gone now, so I've no one to ask. At the top level of the project: setup.py Inside of that: # Python command line utilities will be installed in a PATH-accessible bin/ entry_points={ 'console_scripts': [ 'blueflow-connector-aims = app.connectors.aims.__main__:cli', 'blueflow-connector-csv = app.connectors.csv.__main__:cli', 'blueflow-connector-discovery = app.connectors.discovery.__main__:cli', 'blueflow-connector-fingerprint = app.connectors.fingerprint.__main__:cli', 'blueflow-connector-mock = app.connectors.mock.__main__:cli', 'blueflow-connector-nessusimport = app.connectors.nessusimport.nessusimport:cli', 'blueflow-connector-netflow = app.connectors.netflow.__main__:cli', 'blueflow-connector-passwords = app.connectors.passwords.__main__:cli', 'blueflow-connector-portscan = app.connectors.portscan.__main__:cli', 'blueflow-connector-pulse = app.connectors.pulse.pulse:cli', 'blueflow-connector-qualysimport = app.connectors.qualysimport.qualysimport:cli', 'blueflow-connector-sleep = app.connectors.sleep.__main__:cli', 'blueflow-connector-splunk = app.connectors.splunk.__main__:cli', 'blueflow-connector-tms = app.connectors.tms.__main__:cli', ] }, I ran: pipenv shell to create a shell. If I try a console script: blueflow-connector-mock I get: bash: blueflow-connector-mock: command not found That goes to bash which is clearly a mistake. I also tried: python3 blueflow-connector-mock which gives me: python3: can't open file 'blueflow-connector-mock': [Errno 2] No such file or directory How do I activate these console scripts, so they will actually run? -
wagtail can't add ckeditor to blocks
I'm using wagtail and trying to use ckeditor inside blocks but seems not working the field with ckeditor not showing in admin when I try to create or edit a page I want to use ckeditor because I can use the option source to insert div and class inside text my code for blocks is : from ckeditor.fields import RichTextField class widgetBodyBlock(blocks.StructBlock): heading = blocks.CharBlock(required=False, label=_('Heading')) text = RichTextField(null=True, blank=True) image = ImageChooserBlock() class Meta: template = '_template/blocks/body_block.html' icon = 'edit' label = _('Widget Body') but in admin the field not showing like in picture it's show only heading and image -
What is the best way to include apps in INSTALLED_APPS, Django
We can add apps in settings.py like, let suppose my app name is myapp INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp.apps.AppConfig' #OR 'myapp' ] I just want know to what is the difference between them? I found myapp.apps.AppConfigis a good practice but why? And how can i do this in __init__.py file? -
How do I filter date in react component
I am using the Django rest framework to create API and it is returning 2022-03-04T05:16:07.552250Z this data how do I filter only date from this data. -
Django Modals Validation Errors
Looked a lot into a solution of my issue but didn't get it right. I want to show the errors in the Modal form and don't close until it is valid. For now I am able to get the errors in the customer.html page after the Modal closes. Forms.py class CustomerForm(forms.ModelForm): //...... Form Widget HERE ......//// class Meta: model = Customer fields =['customername','customerlogo','emailaddress','addressLine1','membership','pobox','phonenumber','emailaddress'] Views.py def customer(request): context = {} customers = Customer.objects.all() context['customers'] = customers if request.method == 'GET': form = CustomerForm() context['form'] = form return render(request, 'Mainapp/customer.html', context) if request.method == 'POST': form = CustomerForm(request.POST, request.FILES) if form.is_valid(): form.save() messages.success(request, 'New Client Added') return redirect('customer') else: messages.error(request, form.errors) return redirect('customer') return render(request, 'Mainapp/customer.html', context) HTML MODAL. <div id="create-modal" data-backdrop="static" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Customer Details</h4> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body p-4" data-backdrop="static"> <div id="error"> {% if form.errors %} {% for field in form %} {% for error in field.errors %} <div class="alert-dismissible alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endfor %} {% endif %} </div> <form action="#" action="Mainapp/customer.html" id="customerfrm" method="POST"> <!-- onsubmit="submitForm(event)"--> {% csrf_token %} <div class="row"> <div class="col-lg-9"> <div class="mb-3"> <label for="customername" class="form-label">Customer Name<span … -
How to filter in Django Rest Framework function based view?
So many documentation for filtering in Django rest framework but all the examples are in class based view. but I am trying to do the same in DRF function based view. I wanted to do multiple filter for my items queryset. I tried one way and it is working perfectly. Here first I am trying to search by item name or restaurant name in one request. then I take another keyword and try to filter restaurant name or item name based on restaurant city. It is working perfectly like if I hit this url http://localhost:8000/api/items/?keyword=lasagne&keyword1=paris then it gives me the perfect response. But What I am asking for is that now my code looks for this specific part is messy and I want to add more fields for multiple filtering. Which procedure to follow? Should I follow this one and multiple requests and trying to filter from this. Suppose now I want to filter the queryset based on dish_type, price, item_type, location and then search for items by name or restaurants by name #this is my models class Restaurant(models.Model): user = models.OneToOneField(CustomUser, related_name='restaurant', on_delete=models.CASCADE, null=False) name = models.CharField(max_length=200, blank=True, null=True) profile_picture = models.ImageField(null=True, blank=True) address = models.TextField(max_length=2000, blank=True, null=True) city … -
How to render a data frame from views.py to an html template in django?
I'm building a webapp with Django, and one of the features is that the user can upload a dataset and view it on another page. I'm currently only attempting to read a dataset from a file path and display it in another page; I've placed my test.csv in the file that I want to read from, but I keep getting the error 'list' object has no attribute 'to html'. Here is the views.py: path = r"C:/Users/user/Documents/django_saved_files/" path1, dirs, files = next(os.walk(path)) file_count = len(files) dataframes_list = [] for i in range(file_count): temp_df = pd.read_csv(path+files[i]) dataframes_list.append(temp_df) dataframes_list_html = dataframes_list.to_html(index=False) return render(request,'blog/view_datasets.html',{'Dataframe':dataframes_list_html}) and Here is the HTML Template: <body> <div class="container"> <h1 class="section-header">Datasets Available</h1><hr> <div class="content-section"> Output: {{Dataframe|safe}} </div> </div> </body> -
Django Authentication system modifications
I am new to Django Authentication system and I am unable to find the correct debugging method. I want to create a function to handle login requests and I have done the necessary steps to do the same. created a login url path in main project URLS.py file. path('members/', include('django.contrib.auth.urls')), path('members/', include('members.urls')), created a login url in members app to point to a function created in views.py urlpatterns = [ path('login/', views.login_user, name='login'),] defined what to do when user comes to specific url def login_user(request): if request.method == 'POST': print('-'*100) username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) messages.success(request, ("You are now logged in")) return redirect('index') else: messages.success(request, ("Invalid credentials")) return redirect('login') return render(request, 'registration/Login.html') I have created a Login Page in templates folder. {% extends 'Base.html'%} {% block title %} Login to the Blog Page {% endblock %} {% block content%} <h1>Members Login</h1> <div class="form-group"> <form method="POST" action=""> {% csrf_token %} <div class="mb-3"> <label for="exampleInputEmail1" class="form-label">User Name</label> <input type="text" class="form-control" name = "username"> <div id="emailHelp" class="form-text">We'll never share your email with anyone else.</div> </div> <div class="mb-3"> <label for="exampleInputPassword1" class="form-label">Password</label> <input type="password" class="form-control" name="password"> </div> <button type="submit" class="btn btn-primary">Login</button> </form> …