Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't send mail from page using django , SMTPAuthenticationError
I just started using python and django , I'm trying to send an email from a page directy to my email but the moment i send it the page gives me this error "SMTPAuthenticationError" , i already Less secure apps and disable captcha code this is how i configured my setting EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = '587' EMAIL_HOST_USER = 'mymail@gmail.com' EMAIL_HOST_PASSWORD = 'mypassword' EMAIL_USE_TLS = True and this is the function i coded in the views file from django.http import HttpResponseRedirect from django.shortcuts import render from django.views import View from django.core.mail import send_mail from TatooPage.models import UserRequest def email_request(request): name = request.POST['name'] email = request.POST['email'] message = request.POST['message'] send_mail( 'Message from' + name, message, email, ['mymail@gmail.com'], ) user_details = UserRequest( name=name, email=email, message=message ) user_details.save() return HttpResponseRedirect('/contact-us/') Don't know if there would be anything else i should add . -
Django celery register periodic task
I'm using Celery 4.4 with Django 2.2 I have to create a Periodic Task, I'm extending PeriodicTask ask as from celery.schedules import crontab from celery.task import PeriodicTask class IncompleteOrderHandler(PeriodicTask): run_every = crontab( minute='*/{}'.format(getattr(settings, 'INCOMPLETE_ORDER_HANDLER_PULSE', 5)) ) def run(self, *args, **kwargs): # Task definition eligible_users, slot_begin, slot_end = self.get_users_in_last_slot() map(lambda user: self.process_user(user, slot_begin, slot_end), eligible_users) Earlier to register the above task, I used to call from celery.registry import tasks tasks.register(IncompleteOrderHandler) But now there is no registry module in the celery. How can I register the above periodic task? -
How to create an API getway
I have a web server that's currently running on my local machine, backend Django. How do I create an API gateway that schedules the incoming requests to my APIs? My API currently need the use of GPUs, so it has to stagger requests to prevent the GPU from running out of memory. Any advice on what I should look for or how to implement a request scheduler? Sorry, this is the first time I'm doing a web app, I'm not familiar with the proper terms and what is available out there. Thankyou -
Static images to base64 tag failing
Got this tag code to convert some images in static folder to base64 in my templates: Tags.py: import datetime import base64 from django import template from django.conf import settings from django.contrib.staticfiles.templatetags.staticfiles import static from django.contrib.staticfiles.finders import find as find_static_file @register.simple_tag def encode_static(path, encodign='base64', file_type='image'): """ to use like this: <img src="{% encode_static 'path/to/img.png' %}" /> """ try: file_path = find_static_file(path) ext = file_path.split('.')[-1] file_str = get_file_data(file_path).decode('utf-8') return "data:{0}/{1};{2}, {3}".format(file_type, ext, encodign, file_str) except IOError: return '' def get_file_data(file_path): """ Return base 64 archivo """ with open(file_path, 'rb') as f: data = base64.b64encode(f.read()) f.close() return data This is my project folder structure: MyProject MyProject Lib Static MyApp Images Header.png And my static dirs conf in base.py : STATIC_URL = '/Static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "Lib/Static"), ] But when I call the tag from my template like this: <img src="{% encode_static '/MyApp/Images/Header.png' %}" /> I keep getting this error: The joined path (/MyApp/Images/Header.png) is located outside of the base path component (MyProject/MyProject/Lib/Static) Doesn't make any sense, it's indeed inside that location, any idea why is this happening? -
Django Runtime Error list index out of range macOS to Windows
i'm working with my Team on a Django Project and we have a Problem. So two of us, me included are working on macOS. Our Code is working just fine on macOS and we pushed it on git. But the others that are working on windows are getting a list index out of range error. Everybody have the same Version.. Is it maybe because macOS and windows have different Library's? Django: 3.0.7 Python: 3.8.3 i hope you can help us cheers guys -
How do I test that a field was set correctly in my Django many-to-many relation?
I'm using Django 2.2 with Python 3.7. I have this model set up. Note the many-to-many addresses relationship ... class Coop(models.Model): objects = CoopManager() name = models.CharField(max_length=250, null=False) types = models.ManyToManyField(CoopType) addresses = models.ManyToManyField(Address) enabled = models.BooleanField(default=True, null=False) phone = PhoneNumberField(null=True) email = models.EmailField(null=True) web_site = models.TextField() I wrote the below test to verify I can create a Coop with at least one address ... @pytest.mark.django_db def test_coop_create(self): """ Test coop serizlizer model """ name = "Test 8899" coop_type_name = "Library" street = "222 W. Merchandise Mart Plaza, Suite 1212" city = "Chicago" postal_code = "60654" enabled = True postal_code = "60654" email = "myemail@hello.com" phone = "7739441426" web_site = "http://www.1871.com" state = StateFactory() serializer_data = { "name": name, "types": [ {"name": coop_type_name} ], "addresses": [{ "formatted": street, "locality": { "name": city, "postal_code": postal_code, "state_id": state.id } }], "enabled": enabled, "phone": phone, "email": email, "web_site": web_site } serializer = CoopSerializer(data=serializer_data) serializer.is_valid() assert serializer.is_valid(), serializer.errors coop = serializer.save() assert coop.name == name type_count = 0 for coop_type in coop.types.all(): assert coop_type.name == coop_type_name type_count = type_count + 1 assert type_count == 1 assert coop.addresses[0].locality.name == city assert coop.addresses[0].locality.postal_code == postal_code assert coop.addresses[0].locality.state.id == state.id assert coop.enabled == enabled assert coop.phone == … -
Using django-webtest with BDD (behave) step definitions
How can I get the benefits of using Webtest inside BDD step definitions (using django behave), given that I don't have a TestCase to inherit the WebTest class inside the step definition? -
How to change a users language from admin site in Django?
I'm implementing Django's I18N to translate a project and works really smooth. The thing is that I'm working on someone else's project and there was a field in the users profile named "language" which is a charfield which is filled with either "esp" or "eng". Therefore it was possible to change the any users language from the admin site. Is there a way to change any users language from the django admin site using Django's I18N? Note: I'm not trying to change the admin site language. Im trying to enter to the admin site being the user A and modify the user B to change the language user B sees the site. In my setting I have the "es" and "en" language code available. -
Rendering subprocess -lilypond- to django template
I'm trying to generate music with lilypond and render it to django template. When I try to run the script in cmd, midi file is generated but I can't render it to django template. this works fine in cmd and generates music file which can be played -and rest of the code- : views.py -> lyout = subprocess.Popen(["lilypond", song_name]) out, err = lyout.communicate() return render(request, "smcs/result.html", out) this is my html template: result.html page {% for song in out %} <audio controls preload="auto" id="audio" autoplay="autoplay"> <source src="../../{{ song }}" > </audio> {% endfor %} In result page i only see the file name but player is not shown. When i delete the {% for - end%} commands player is shown but song is not playing. urls.py urlpatterns = [......] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py MEDIA_ROOT=os.path.join(BASE_DIR,"songdir") MEDIA_URL='/media/' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, "templates")], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', "django.template.context_processors.media", 'django.contrib.messages.context_processors.messages', ], }, }, ] What am I doing wrong? :( -
Removing button for users
My website has user login and registarion. I wanted to remove login and register button for a user that is logged inn and remove the logout button for a user that is logged out. Im doing this in JavaScript but i can seem to get it to work. var user = "{{ request.user }}" if (user != 'AnonymousUser'){ btn = document.getElementsByClassName('user-out'); for(i=0; i<btn.length; i++){ btn[i].remove(); //OR btn[i].classList.add('hidden'); } } if (user == 'AnonymousUser'){ document.getElementById('user-in').classList.add('hidden') } Im using Django in my backend. This is the HTML code. <a href="{% url 'login' %}"><button type="button" class="btn btn-primary user-out">Logg Inn</button></a> <a href="{% url 'reg' %}"><button type="button" class="btn btn-success user-out">Registrer deg</button></a> <a href="{% url 'logout' %}"><button id = "user-in" type="button" class="btn btn-secondary">Logg Ut</button></a> -
Django - Show foreign key value instead of object in the drop down form
I am trying to implement a form that uses two models connected through a foreign key. Below is my current setup: Primary Model: class Firstlist(models.Model): TBlname = models.CharField(max_length=100) def __str__(self): return self.name Second Model: class SecondList(models.Model): Status = models.CharField(max_length=100) Tblnameref = models.ForeignKey(Firstlist) def __str__(self): return self.name Form: class MainForm(forms.ModelForm): class Meta: model = SecondList fields = ('Tblnameref','Status') def __init__(self,*args,**kwargs): super(SecondList,self).__init__(*args,**kwargs) self.fields['Tblnameref'].empty_label = '-- Select --' Template: <form action="" method="POST">{% csrf_token %} {{form.Tblnameref}} <button>Validate</button> {{form.Status}} <button>Validate</button> </form> However when I test this, the values in drop down show up as "Tblnameref object (1)" instead of the actual value. Can someone please advise how to fix this so that the drop down shows actual value than the object. Thank you for the help -
Django - URL problem for user profile view and edit profile view
In my Django project, specifically in my accounts app, I have 2 simple views, one allows users to view their profile (or other users' profiles), and the other one allows users to edit their own profile. My account.urls looks like this from django.urls import path from accounts.views import ProfileView, EditProfileView app_name = 'accounts' urlpatterns = [ path('<slug:username>/', ProfileView.as_view(), name='profile'), path('edit/', EditProfileView.as_view(), name='edit'), ] Everything works great, but if an user creates an accounts with the word edit as their username, they will NEVER be able to edit their profile, since the first URL pattern will always be matched. What's the best way of solving this problem in Django? I know I could change my URLs to something like: urlpatterns = [ path('<slug:username>/', ProfileView.as_view(), name='profile'), path('<slug:username>/edit/', EditProfileView.as_view(), name='edit'), ] But I prefer to NOT edit my URLs. I was wondering if there is another solution I don't know. -
Django, override static path the url routes
My urls.py: urlpatterns = [ path('admin/', admin.site.urls), ] My static path: STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'public/'), ) STATIC_URL = '/' Esentially, I want urlpatterns to override static files. if a route is found in urlpatterns, go to that route, else, go to static. At the moment, all urlpatterns return 404 because they are not found in the static dir. What can I do to solve this? -
New value assign to with tag variable after deceleration in Django template
I googled but unable to find the solution. Where I went thought some answers like This answer Some official docs which I went through Trans Tag Built-In Tags Template View {% load custom_tags %} {% for each in content %} {% with tempID='' %} # It is initially empty string {% if each.contentID != tempID %} {% tempID = each.contentID %} # Want to assign new value to tempID .... .. {% endif %} {% endwith %} {% endfor %} Is there any method to assign with tag variable. I tried custom_tags filters also. Not worked. -
How to use django commands to feed a db with an external API?
I'm learning django and I want to feed my django db with https://pokeapi.co API so i can make a drop down list on HTML with every pokemon name up to date. fetchnames.py import requests as r def nameslist(): payload = {'limit':809} listpokemons = [] response = r.get('https://pokeapi.co/api/v2/pokemon', params=payload) pokemons = response.json() for line in pokemons['results']: listpokemons.append(line['name']) return listpokemons ### Function that request from API and returns a list of pokemon names (['Bulbassaur', 'Ivyssaur',...) core_app/management/commands/queryapi.py from core_app.models import TablePokemonNames from core_app.fetchnames import nameslist class FetchApi(BaseCommand): help = "Update DB with https://pokeapi.co/" def add_model_value(self): table = TablePokemonNames() table.names = nameslist() table.save() i'm pretty sure that i'm missing a lot since i'm still learning to use django and i'm still confuse on how should i use django commands, but, i tried to make a django command with nameslist() function and nothing happend on the db, there is something wrong with using a list to feed a db? -
Unable to add a comment on my Django blog
I've been trying to add comments to the forum on my website and I've managed to get to the stage of being able to see the comment form. But, when you actually submit the comment form, I get the below error. FYI, 'What Good Marketing Events are There in 2020?' is the name of the post I'm trying to add a comment too. Here are the models used: class Comment(models.Model): post = models.ForeignKey(Post, related_name='comments') user_name = models.CharField(max_length=250) email = models.EmailField() content = models.TextField() created_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.user_name class Post(models.Model): creator_id = models.ForeignKey(User, null=False, default=1) title = models.CharField(max_length=200) content = models.TextField() created_date = models.DateTimeField(auto_now_add=True) published_date = models.DateTimeField(blank=True, null=True, default=timezone.now) views = models.IntegerField(default=0) category = models.CharField(choices=CATEGORY_CHOICES, max_length=30, blank=True, null=True) image = models.ImageField(upload_to="img", blank=True, null=True) def __str__(self): return self.title Here is the view used: def comment_post_form(request, pk): """ Create a view that allows us to add a comment """ post = get_object_or_404(Post, pk=pk) if request.method == "POST": form = CommentPostForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect('forum_post_details.html', {'post': post}) else: form = CommentPostForm() return render(request, 'comment_post_form.html', {'form': form}) Here is the form used: class CommentPostForm(forms.ModelForm): class Meta: model = Comment fields = ['content'] Here is the … -
Django smart-select form with bootstrap
I'm using the chained foreign key in django to make a chained dropdown list for country then city etc... It's working fine, however when I try to add a class to it shows the changes in shape, but it remains empty, when I select the country the city dropdown remains empty, if I remove the class I works again, please help.... -
How to make a seal / badge / widget on Django
Can anyone point me to a right direction on how to make functioning trust seal / badge / widget? As I understand there should be some API included. It should be able to recognize that it's on the right website / domain. I am working with django backend framework to make this app. Examples of what I want to achieve: See gif of the function https://sectigo.com/trust-seal See gif of the function https://www.carandtruckremotes.com/ See gif of the function https://www.shopperapproved.com/ See gif of the function https://www.carcovers.com/ -
How to change/customize the input field and label fonts in Django crispy_forms?
I have an application written in python by using django. I need to know what I am missing that can't customise the form using django crispy package. This is my form: here is the code. profile.html: {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section" style="position:absolute; right:140px;"> <div class="media"> <img class="rounded-circle account-img" src="{{ user.profile.image.url }}"> <div class="media-body"> <h2 class="account-heading">{{ user.username }}</h2> <p class="text-secondary">{{ user.email }}</p> </div> </div> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Profile Info</legend> {{ u_form|crispy }} {{ p_form|crispy }} </fieldset> </form> </div> {% endblock content %} views.py: from crispy_forms.helper import FormHelper from django.contrib.auth.models import User from django import forms from crispy_forms.layout import Layout, Fieldset, ButtonHolder, Row, Column class UserUpdateForm_readonly(forms.ModelForm): email = forms.EmailField(widget=forms.TextInput(attrs={'placeholder': 'Email'})) class Meta: model = User fields = ['username', 'email'] def __init__(self, *args, **kwargs): print('here') super(UserUpdateForm_readonly, self).__init__(*args, **kwargs) # Call to ModelForm constructor self.fields['username'].widget.attrs['style'] = 'width:400px; height:35px;' self.fields['email'].widget.attrs['style'] = 'width:400px; height:35px;' self.helper = FormHelper() self.helper.layout = Layout( Row( Column('username', css_class='form-group col-md-3 mb-2'), Column('email', css_class='form-group col-md-6 mb-0'), css_class='form-row' ) ) I want to change/customize the text boxes( make read_only) and labels (bold the text)! -
DRF Multiple User with customer user model
I am implementing a custom user model which has user and nursery accounts. The registration is happening but login is not happening as I expect it to behave. Also the token authentication is not working I guess something is wrong in my views.py but I'm not being able to figure it out. Please help. It's urgent I'm getting this error while logging in: AttributeError at /api/auth/login/user Got AttributeError when attempting to get a value for field account on serializer UserSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Account instance. Original exception text was: 'Account' object has no attribute 'account'. Here is my models.py class AccountManager(BaseUserManager): def create_user(self, username, email, contact, password=None): """Create and return a `User` with an email, username and password.""" if username is None: raise TypeError('Users must have a username.') if email is None: raise TypeError('Users must have an email address.') user = self.model(username=username, email=self.normalize_email(email), contact=contact) user.set_password(password) user.save() return user def create_superuser(self, username, email, contact, password): """ Create and return a `User` with superuser (admin) permissions. """ if password is None: raise TypeError('Superusers must have a password.') user = self.create_user(username, email, contact, password) user.is_superuser = True user.is_staff = True … -
Django: after successful login() the next time the request.user page is refreshed it becomes "anonymous" again
I did custom method of authorization, and this happens with ajax This is view: class CustomLogin(LoginView): authentication_form = CustomUserAuthForm def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): email = form.cleaned_data['username'] password = form.cleaned_data['password'] needed_user = authenticate(request, email=email, password=password) if needed_user is not None: if needed_user.is_active: login(request, needed_user) request.session['night_mode'] = False request.session.save() return JsonResponse({'success': 1}) else: return JsonResponse({'errors': 'Email and password didn\'t match.'}) if form.errors: errors = [] for key, value in enumerate(form.errors): errors += form.errors[value] return JsonResponse({'errors': errors}) return super().post(request, *args, **kwargs) Form: <!-- Modal AUTHORIZATION --> <div id="auth_view" class="modal" tabindex="-1" role="dialog"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-body"> <button type="button" class="close close_model" data-dismiss="modal" aria-label="Close"> <i class="fal fa-times" style="font-size: 16px;"></i> </button> <div class="modal-body__title"> Authorization </div> <div class="modal-body__form-container"> <div class="form-container"> <form id="auth_view__form" class="form-container__form" method="post" enctype="multipart/form-data"> {% csrf_token %} <p id="error-message"></p> {% for field in auth_form %} <div class="form-group"> {{ field.label_tag }} {{ field }} </div> {% endfor %} <input type="submit" value="login"> <input type="hidden" name="next" value="{{ next }}"> <p id="password_reset"><a href="{% url 'password_reset' %}">Forgot password</a></p> <div class="or_container"> <hr> <div class="or_label">or</div> </div> <div class="auth_by_socials"> <div class="auth_by_facebook"><i class="fab fa-facebook-f"></i></div> <div class="auth_by_google"><i class="fab fa-google"></i></div> </div> <div id="registration"> <div>Sign up with e-mail</div> <i class="fal fa-long-arrow-right" aria-hidden="true"></i> </div> </form> </div> </div> </div> </div> </div> </div> … -
combining filter parameters in a FilterSet
I have created a filter for my model. How do I make it so that it filters as answered or archived? At the moment if I pass both parameters, it combines them using and - this makes sense but it is not what I am trying to achieve. I would be happy to have just one field (ie. answered_or_archived) from django_filters import rest_framework as filters from conversations.models import Conversation class ConversationFilter(filters.FilterSet): answered = filters.BooleanFilter(field_name="answered_at", lookup_expr="isnull", exclude=True) archived = filters.BooleanFilter(field_name="is_archived") class Meta: model = Conversation fields = ["answered", "archived"] -
Save Foreign Key text input in Django model form
i want to save the text input of Experience_ProForm in the Experience_Pro table (models.Experience_Pro) and Projet_realiseForm in the Projet_realise table (models.Projet_realise) in my db and reference of them as foreign key in cv table Database is SqLite3 my models.py class Experience_Pro(models.Model): annee_debut = models.IntegerField() annee_fin = models.IntegerField() description_exp_pro = models.TextField(null=True,blank=True) class Projet_realise(models.Model): annee_prjet = models.IntegerField() description_projet = models.TextField(null=True,blank=True) class Cv(models.Model): experience_Pro = models.ForeignKey('Experience_Pro' ,on_delete=models.CASCADE) projet_realise = models.ForeignKey('Projet_realise',on_delete=models.CASCADE) my forms.py class Experience_ProForm(forms.ModelForm): class Meta: model = Experience_Pro fields = ("__all__") class Projet_realiseForm(forms.ModelForm): class Meta: model = Projet_realise fields = ("__all__") class CvForm(forms.ModelForm): class Meta: model = Cv fields = ("__all__") my views.py formExperience_Pro = Experience_ProForm(request.POST,prefix='formExperience_Pro') formProjet_realise = Projet_realiseForm(request.POST,prefix='formProjet_realise') formCv = CvForm(request.POST,prefix='formCv') if request.method == 'POST': print(request.POST) if formExperience_Pro.is_valid() and formProjet_realise.is_valid(): formCv.save() print("yeeeees") else: formExperience_Pro = Experience_ProForm(prefix='formExperience_Pro') formProjet_realise = Projet_realiseForm(prefix='formProjet_realise') context = { 'formExperience_Pro' : formExperience_Pro, 'formProjet_realise' : formProjet_realise, 'formCv' : formCv } return render(request , "Cvs/createCV.html",context) -
RecursionError at /graphql. maximum recursion depth exceeded
Problem Definition: I have read the article about adding JWT authentication my project using graphene-jwt package from this official link. According to what is said in the tutorial, some changes should be applied to the project settings.py file: First of all the package should be installed: pip3 install django-graphql-jwt Add AuthenticationMiddleware to MIDDLEWARE variable. MIDDLEWARE = [ ... 'django.contrib.auth.middleware.AuthenticationMiddleware', ... ] Adding JSONWebTokenBackend backend AUTHENTICATION_BACKENDS variable: AUTHENTICATION_BACKENDS = [ 'graphql_jwt.backends.JSONWebTokenBackend', 'django.contrib.auth.backends.ModelBackend', ] Add JSONWebTokenMiddleware to GRAPEHENE variable. GRAPHENE = { 'SCHEMA': 'apps.schema.schema.schema', # Where your Graphene schema lives 'MIDDLEWARE': [ 'graphql_jwt.middleware.JSONWebTokenMiddleware', ], } After doing the 4th step, every request to localhost:8000/graphql has the following stacktrace: errorInternal Server Error: /graphql Traceback (most recent call last): File "/home/mostafa/Desktop/Work/OOD_Project/back/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/mostafa/Desktop/Work/OOD_Project/back/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/mostafa/Desktop/Work/OOD_Project/back/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/mostafa/Desktop/Work/OOD_Project/back/venv/lib/python3.6/site-packages/django/views/generic/base.py", line 62, in view self = cls(**initkwargs) File "/home/mostafa/Desktop/Work/OOD_Project/back/venv/lib/python3.6/site-packages/graphene_django/views.py", line 78, in __init__ schema = graphene_settings.SCHEMA File "/home/mostafa/Desktop/Work/OOD_Project/back/venv/lib/python3.6/site-packages/graphene_django/settings.py", line 116, in __getattr__ val = perform_import(val, attr) File "/home/mostafa/Desktop/Work/OOD_Project/back/venv/lib/python3.6/site-packages/graphene_django/settings.py", line 55, in perform_import return import_from_string(val, setting_name) File "/home/mostafa/Desktop/Work/OOD_Project/back/venv/lib/python3.6/site-packages/graphene_django/settings.py", line 69, in import_from_string module = importlib.import_module(module_path) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, … -
accessing button toggle values in django views
I am working on a django web application. In this application, I have a form with a few buttons. these buttons act like tags that a user can press. When the user submits the form I want to access the value of the buttons the user clicked in my views. How do I do that? I designed the form with Bootstrap. this is the code to the HTML form. <form> {% csrf_token %} ... <p class='details-scrape'>Select the items you want to add to the list</p> <button type="button" class="btn btn-outline-primary" data-toggle="button" aria-pressed="false" autocomplete="off"> Tomato </button> <button type="button" class="btn btn-outline-primary" data-toggle="button" aria-pressed="false" autocomplete="off"> Eggs </button> <button type="button" class="btn btn-outline-primary" data-toggle="button" aria-pressed="false" autocomplete="off"> Bread </button> <button type="button" class="btn btn-outline-primary" data-toggle="button" aria-pressed="false" autocomplete="off"> Beans </button> <button type="button" class="btn btn-outline-primary" data-toggle="button" aria-pressed="false" autocomplete="off"> Cheese </button> <button type="submit" class="btn btn-primary btn-block btn-lg mt-5">Submit</button> </form> Here is my views.py code def index(request): if request.method == 'POST': # ------------- New code will come here ----------------- #access the values of the clicked buttons here... return render(request, 'index.html') else: return render(request, 'index.html')