Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I add additional field in DRF model instance creation
I have a classroom model in django DRF that looks like this: class Classroom(models.Model): class PublishedClassrooms(models.Manager): def get_queryset(self): return super().get_queryset().filter(status="published") options = (("published", "Published"), ("draft", "Draft")) name = models.CharField(max_length=255) code = models.CharField(unique=True, max_length=8) subject = models.CharField(max_length=255, null=True, blank=True) section = models.CharField(max_length=255, null=True, blank=True) description = models.TextField(null=True, blank=True) status = models.CharField(max_length=10, choices=options, default="draft") owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, blank=True, null=True) dateCreated = models.DateTimeField(default=timezone.now) dateUpdated = models.DateTimeField(default=timezone.now) objects = models.Manager() # default manager publishedClassrooms = PublishedClassrooms() # custom manager class Meta: ordering = ("-dateUpdated",) def __str__(self): return self.name what I want is to generate unique code field in the serializer upon creation of an instance using this code: def get_code(): codeID = shortuuid.ShortUUID().random(length=8) return codeID Can anybody guide me on this? -
Django courier logistics service shipment tracker
How can I enable a live track in Django. Like, I wanna know how to implement a shipment tracking system or model in Django, whether live track or by code number, I'm building a courier logistics service website -
Range Filter between two fields
i have TaskAdmin with list_filter: from rangefilter.filters import AdminSplitDateTime, DateTimeRangeFilter as OriginalDateTimeRangeFilter ('created_at', OriginalDateTimeRangeFilter), ('finished_at', OriginalDateTimeRangeFilter), I receive next URL: /admin/core/task/?&created_at__range__gte_0=2021-10-01&created_at__range__gte_1=10%3A50&created_at__range__lte_0=2021-10-08&created_at__range__lte_1=22%3A50 And same for finished_at: /admin/core/task/?&finished_at__range__gte_0=2021-10-01&finished_at__range__gte_1=10%3A50&finished_at__range__lte_0=2021-10-08&finished_at__range__lte_1=22%3A50 It works only with created_at and finished_at dates if they are separate, but I need to connect them, i need make one filter between created_at and finished_at dates. That is, so that the DateStart is compared with created_at, and the DateFinish is compared with finished_at. So i need receive next URL request: /admin/core/task/?&created_at__range__gte_0=2021-10-01&created_at__range__gte_1=10%3A50&finished_at__range__lte_0=2021-10-08&finished_at__range__lte_1=22%3A50 Try to do this, but not worked for me ('created_at', 'finished_at', OriginalDateTimeRangeFilter), How i can do it, maybe some of you have faced the same problem? I hope I was able to explain what I need Thanks -
How do I fix this issue with if statement being ignored in views.py?
Why is the if statement in twilio_view2 being ignored? When this is executed it just skips down to the else statement. See the TwiML response. Thanks in advance to anyone who helps. views.py from example import test1_is_valid, test2_is_valid def twilio_view2(request: HttpRequest) -> HttpResponse: digits = request.POST.get('Digits') response = VoiceResponse() if test1_is_valid(digits) and test2_is_valid(digits): gather = Gather(input='dtmf', action='/twilio_view3', method='POST') gather.say('Blah blah blah.') response.append(gather) else: response.say('Something other than Blah blah blah.') response.redirect("/twilio_view1") return HttpResponse(str(response), content_type='text/xml') TwiML response <Response> <Say>Something other than Blah blah blah.</Say> <Redirect>/twilio_view1</Redirect> </Response> -
DJango Template - Render a field from a form using a string
According to django's docs: We don’t have to let Django unpack the form’s fields; we can do it manually if we like (allowing us to reorder the fields, for example). Each field is available as an attribute of the form using {{ form.name_of_field }}, and in a Django template, will be rendered appropriately. Great! I want to make it more complicated... I want to do something to the effect of {{ form."somefield" }} so that way I can essentially do: {% for i in '012345'|make_list %} {% with y=forloop.counter|stringformat:"s" %} {% with somefield="somefield"|add:y %} {{form.somefield}} #either this {{form.somefield|add:y}} #this {{form.somefield{{i}}}} #this {{form.somefield{{forloop.counter}}}} #this #or other variations of that {% endwith %} {% endwith %} {% endfor %} Basically I need to add some variable to the end of the "somefield" attribute to be able to referrence a field that has a number at the end of it. Thank you!!! -
None typeobject in success_url django
I have a user registration form as shown by the code below. views.py class UserCreateView(CreateView): form_class = UserCreateForm model = User template_name = 'internethq/user_form.html' success_url = '/internethq/login' forms.py class UserCreateForm(UserCreationForm): first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) email = forms.EmailField(required=True) class Meta: model = User fields = [ 'first_name', 'last_name', 'username', 'email', 'password1', 'password2' ] def clean_password1(self): exp = re.compile("^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$") if exp.match(self.cleaned_data['password1']): return self.cleaned_data['password1'] else: raise ValidationError('Must contain one uppercase letter, one lowercase letter, one number and one special character.') def save(self, commit = True): user = super().save(commit = False) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] if commit: user.save() The Error Internal Server Error: /internethq/signup/ AttributeError at /internethq/signup/ 'NoneType' object has no attribute '__dict__' Traceback (most recent call last): bit of trimming here... File "/home/togi/atollaviation/env/lib/python3.6/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/home/togi/atollaviation/env/lib/python3.6/site-packages/django/python3.6/site-packages/django/views/generic/edit.py", line 113, in get_success_url url = self.success_url.format(**self.object.__dict__) I thought success_url looked correct but is there an error I'm missing? This codes runs fine in the development server. Thanks for your help. -
"List index out of range" for Django Steam API
I'm working on an app in Django that lets you see stuff about a steam user, when typing in their steam ID. I'm using the Django Steam API found at this link: https://pypi.org/project/django-steam-api/ which, unfortunately, doesn't provide some documentation / enough help on how to properly set it up. I followed the steps from there. Installed the pip package, added django-steam-api to the INSTALLED_APPS tuple, generated a STEAM_API_KEY from their official site (on "localhost", because my web app isn't hosted at this moment) and also updated the database by applying the current migrations. I'm having a view in backend/views.py, (backend being my app name created with the django-admin startapp backend command), that takes data from a form that contains a textbox called steam_user_id using the POST method. I'm trying to get everything from Steam about the user with the id steam_user_id, but when I call, inside the view, the method: Player.objects.steam_create(steam_user_id) (...) I receive the following error on my page: IndexError at {{ /link_to_my_view/ - replaced it manually here to avoid complications }} list index out of range Request Method: POST Request URL: http://127.0.0.1:8000/profile/edit/ Django Version: 3.2.7 Exception Type: IndexError Exception Value: list index out of range Exception Location: C:\Users\matea\AppData\Local\Programs\Python\Python39\lib\site-packages\django_steam_api\managers.py, … -
Django DRF Behave - How to load test fixture data into test database before testing
The documentation only mentions fixtures as part of browser setUp and tearDown. What about data? How does one load and destroy test data such as test-users.json into test database for behave tests? I understand one usually loads the test fixtures inside a testing class such as: class FooTest(LiveServerTestCase): fixtures = ['test-users.json'] I have already have my FIXTURE_DIRS set in settings file, and fixtures ready, but don't know how to implement into the behave tests. Could anyone please help, thanks in advance. Djangov3.2.7 DRFv3.12.4 Behavev1.2.6 Note that I am only using Behave and not Behave-Django -
Renaming uploaded files with django primary keys
Using the accepted and second answers in this post, I've created a rename file function which is in my models.py: class PathAndRename(object): def __init__(self, sub_path): self.path = sub_path def __call__(self, instance, filename): ext = filename.split('.')[-1] # set filename as random string if instance.pk: filename = '{}/{}'.format(instance.pk, filename) else: filename = '{}/{}.{}'.format(instance.pk, uuid4().hex, ext) # return the whole path to the file return os.path.join(self.path, filename) path_and_rename = PathAndRename("") class Post(models.Model): File = models.FileField(blank=True, null=True, upload_to = path_and_rename) So the way it's supposed to work is that it outputs to media/<object.pk>/<filename> if a primary key is found, otherwise it outputs to media/None/<hex-generated-filename> If I use my post create view to upload the file, there is no PK assigned to the record yet, so it defaults to media/None/<hex-generated-filename>. If I then edit the post with my post update view, the file gets correctly output to media/<object.pk>/<filename> So essentially the issue is that the file gets uploaded before the PK is assigned. Does anyone know how to fix it? Here are my relevant views: class PostCreateView(LoginRequiredMixin, FormView): template_name = 'trucking/post_form.html' form_class = RecordForm def post(self, request, *args, **kwargs): form = self.form_class(request.POST or None, request.FILES or None) if form.is_valid(): obj = form.save(commit=False) obj.author = User.objects.get(username=self.request.user) … -
CSRF verification failed. Request aborted - even after adding {% csrf_token %}
I am getting the CSRF verification failed. Request aborted error. I did extensive research and everything pointed out to adding {% csrf_token %} into the template tag with the POST form and I did that but still getting the same error. -
JavaScript submit not working Django From
I have a simple form that uses JavaScript to validate and submit the form using POST to the database. The script works for 2 forms but won't submit for other forms for some reason and I can't work out why. I've even copied the existing form and JS replaced it with new names and it still doesn't work and I cannot figure out why. I've tried to debug, but I'm getting http200 for every request so not throwing any errors that I can see. Working version: var investor_form = document.getElementById("add-investor"); investor_form.addEventListener("submit", function (e) { e.preventDefault(); if (validated(this)) { this.classList.add("was-validated"); var i_name = document.getElementById("investor-name").value; var i_website = document.getElementById("investor-website").value; var i_portfolio = document.getElementById("investor-portfolio").value; var i_comment = document.getElementById("ckeditor-classic").value; const csrftoken = document.getElementsByName("csrfmiddlewaretoken")[0].value; const formdata = new FormData(); formdata.append("investor_name", i_name); formdata.append("investor_website", i_website); formdata.append("investor_portfolio", i_portfolio); formdata.append("investor_comment", i_comment); const xhr = new XMLHttpRequest(); xhr.open("POST", "/apps/add_investor"); xhr.setRequestHeader("X-CSRFToken", csrftoken); xhr.send(formdata); xhr.onload = () => { window.location.reload(); }; } }) // Form validation function validated(form) { console.log(form) var i_name = document.getElementById("investor-name"); var i_website = document.getElementById("investor-website"); var i_portfolio = document.getElementById("investor-portfolio"); i_name_value = i_name.value.trim(); i_website_value = i_website.value.trim(); i_portfolio_value = i_portfolio.value.trim(); if (i_name_value === "") { message = "Please fill investor name field" setErrorFor(i_name, message); } else { setSuccessFor(i_name) } if (i_website_value … -
How to remove Image location showing in body although it is in a Meta Tag
I have a Django project and I added an Image meta tag as following in the base.html <meta property="og:image" content="{% block image %}{% endblock %}"> <meta property="og:image:type" content="image/jpeg"> <meta property="og:image:width" content="300"> <meta property="og:image:height" content="300"> in the home.html page I have added the following: {% extends 'base/base.html' %} {% load static %} {% block content %} {% block description %}{{ info.description }}{% endblock %} {% block image %}{{ info.avatar.url }}{% endblock %} My issue is that in the home page in the top the location of the image is showing as per below: I am not sure why the image link is showing and I am not sure how to remove it. My question is how to remove the location of the file from the page. -
Getting An Template Rendering Error When Using Django SocialAuth App
I installed django-socailauth app in my Django project and followed the below tutorial of setting it in the python project. https://simpleisbetterthancomplex.com/tutorial/2016/10/24/how-to-add-social-login-to-django.html But when running the Django server the site starts normally and the issue comes when I click the login button in my application. It gives me the below Template Rednering Error Reverse for 'begin' with arguments '('facebook',)' not found. 1 pattern(s) tried: ['social-auth/$login\/(?P[^/]+)\/$'] -
Django - Unit test an object has been deleted - how to use assertRaise / DoesNotExist exception
I would lioke some help to unit test a function that deletes an object in a Django app The problem I display a list of values, it includes a bin icon to delete one value, and my view seems to work fine (at least according to the test I made). How can I unit test it? I'm not able to find out the right way to do yet. I searched the web and found the DoesNotExist exception, but I'm afraid I'm not able to use it, as I got a matching query does not exist error. Could you please advise me on how to proceed? What I tried Here is my current whole code for the test: class TestAdmUsers(TestCase): def setUp(self): self.company = create_dummy_company("Société de test") self.usr11 = create_dummy_user(self.company, "user11") self.usr13 = create_dummy_user(self.company, "user13") self.usr14 = create_dummy_user(self.company, "user14") self.client.force_login(self.user_staff.user) def test_delete_user(self): test_usercomp_id = self.usr13.id url = reverse("polls:adm_delete_user", args=[self.company.comp_slug, self.usr13.id]) response = self.client.get(url, follow=True) self.assertRaises(UserComp.DoesNotExist, UserComp.objects.get(id=test_usercomp_id)) The test log is the following: Creating test database for alias 'default'... System check identified no issues (0 silenced). E ====================================================================== ERROR: test_delete_user (polls.tests_admin.TestAdmUsers) ---------------------------------------------------------------------- Traceback (most recent call last): File "D:\Mes documents\Informatique\Developpement\Votes AG\projet_votes\polls\tests_admin.py", line 136, in test_delete_user self.assertRaises(UserComp.DoesNotExist, UserComp.objects.get(id=test_usercomp_id)) File "C:\Users\Christophe\.virtualenvs\projet_votes-onIieQ0I\lib\site-packages\django\db\models\manager.py", line 82, in … -
Use phone number for authenticate user in Django
My custom user uses the mobile number as username If a user registers with a phone number, but if he does not confirm it, it stays in the database and can no longer be used. Do you have a solution for this problem? views.py def account_register(request): if request.user.is_authenticated: return redirect("store:home") if request.method == "POST": registerForm = RegistrationForm(request.POST) if registerForm.is_valid(): user = registerForm.save(commit=False) user.phone_number = registerForm.cleaned_data["phone_number"] user.set_password(registerForm.cleaned_data["password"]) user.is_active = False user.save() otp_user = f"{user.otp}" print(code_user) send_sms(otp_user, user.phone_number) return render(request, "account/verificationpage.html", {"form": registerForm}) else: return HttpResponse("Error handler content", status=400) else: registerForm = RegistrationForm() return render(request, "account/authentication.html", {"form": registerForm} -
Sempre que tento dar push no meu projeto em django me da esse erro
enter image description here ERROR: Command errored out with exit status 1: /app/.heroku/python/bin/python /app/.heroku/python/lib/pyt hon3.9/site-packages/pip/_vendor/pep517/_in_process.py prepare_metadata_for_build_wheel /tmp/tmp23725z14 Check the logs for full command output. -
Relate one table to two tables in Django
I have 'Table1' and `Table2. Both of them of them need to have a one-to-many relationship to 'Table3' ('Table1'/'Table2' one to many 'Table3'). Each row in 'Table3' should have only one relationship field to that can point to 'Table1' or 'Table2' (will be defined in the creation of each row). I thought of implementing this by using a through table that will have 3 relationship column for 'Table1', 'Table2', 'Table3'. Table1: * table1_id Table2: * table2_id Table3: * table3_id ThrougTable: * col1 = ForeignKey(table1_id, null=True) * col2 = ForeignKey(table2_id, null=True) * col3 = OneToOneField(table3_id) What is the best way to make this in Django? -
Having trouble saving an object with a foreign key in Django
This is my first question in the forum. I'm new to Django and making progress slow. The code I'm working on now throws an error when saving with an object as a foreign key reference. My code as below two models class Make(models.Model): name_text = models.CharField(max_length=100) def __str__(self): return self.name_text class Autos(models.Model): nickname = models.CharField(max_length=100) make = models.ForeignKey(Make, on_delete=CASCADE) milage = models.IntegerField(default=0) comments = models.CharField(max_length=1000) HTML form that sends the data to the view <form action="{% url 'auto:addauto' %}" method="post"> {% csrf_token %} <p> <label for="nickname">Nickname : </label> <input type="text" name="nickname" id="nickname" value="{{ autodetails.nickname }}"> </p> <p> <label for="make">Make : </label> <select name="make" id="make"> {% for item in make %} <option value="{{ item.name_text }} ">{{ item }}</option> {% endfor %} </select> </p> <p> <label for="milage">Milage : </label> <input type="text" name="milage" id="milage" value="{{ autodetails.milage }}"> </p> <p> <label for="comments">Comments : </label> <input type="textarea" name="comments" id="comments" value="{{ autodetails.comments }}"> </p> <input type="submit" name = "buttonsubmit" value="Add"> </form> View where the problem exists def addauto(request): if request.method == 'POST': obj = Autos() obj.nickname = request.POST['nickname'] name_text1 = request.POST.get('make') make = Make.objects.get(name_text = name_text1) obj.make = make obj.milage = request.POST['milage'] obj.comments = request.POST['comments'] obj.save() return redirect('/autos/listautos') else: make = Make.objects.all() context = { 'make': … -
Editing the Form in _Django_ creates new instance
I am editing the form , it loads data correctly buy when i hit save it creates new entry in database. Here is the view functions @login_required def post_edit(request, username, post_id): is_edit = True post = get_object_or_404(Post, author__username=username, id=post_id) if post.author == request.user: form = PostForm(request.POST or None, instance=post) if form.is_valid(): post = form.save() return redirect('posts:profile', username, post_id) form = PostForm(instance=post) return render(request, 'posts/post_create.html', {'form': form, 'is_edit': is_edit, 'post': post}) else: return redirect('profile') urls: path('posts/<int:post_id>/edit/', views.post_edit, name='post_edit'), post_create.html: <div class="card-body"> <form method="post" action="{% if is_edit %}{% url 'posts:post_edit' post.author.username post.id %}{% else %}{% url 'posts:post_create' %}{% endif %}"> {% csrf_token %} -
Django DRF BDD - How to properly implement Behave with DRF?
As the title suggests, and since the documented instructions are not working out of the box. I have the following environment.py file, exactly from Behave Documentation and the referenced blog # tests/acceptance/environment.py import os from behave import fixture, use_fixture import django from django.test.runner import DiscoverRunner from django.test.testcases import LiveServerTestCase from rest_framework.test import APIClient from fixtures.users import UserTestHelper os.environ['DJANGO_SETTINGS_MODULE'] = 'core.settings.test-settings' # django related fixtures @fixture def django_test_runner(context): django.setup() context.test_runner = DiscoverRunner() context.test_runner.setup_test_environment() context.old_db_config = context.test_runner.setup_databases() yield context.test_runner.teardown_databases(context.old_db_config) context.test_runner.teardown_test_environment() @fixture def django_test_case(context): context.test_case = LiveServerTestCase context.test_case.setUpClass() yield context.test_case.tearDownClass() del context.test_case def before_all(context): context.test.client = APIClient() use_fixture(django_test_runner, context) def after_all(context): context.test_runner.teardown_databases(context.old_db_config) context.test_runner.teardown_test_environment() def before_scenario(context, scenario): use_fixture(django_test_case, context) def after_scenario(context, scenario): context.test.tearDownClass() del context.test When executing $ behave on the project root, I get the following django.core.exceptions.ImproperlyConfigured: Requested setting REST_FRAMEWORK, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Even though my first line in environment.py sets the OS environment variable of DJANGO_SETTINGS_MODULE. Then I tried to bypass that error by executing the following: $ DJANGO_SETTINGS_MODULE=core.settings.test-settings behave I get the AppRegistryNotReady: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Question What am I missing to get this to run properly, doesn't seem like behave is picking … -
Why model text is not displayed in html?
The problem is that the text of the model description_text is not displayed. And sorry for my english. This is code of html {% for description_text in context_object_name %} <h1 class="description"><a href="/Homepage/{{ goods.id }}/">{{goods.description_text}}</a></h1> {% endfor %} This is code of views.py class IndexView(generic.ListView): template_name = 'Homepage/index.html' model = Goods context_object_name = 'goods.description_text' def description(self): return self.description_text def price(self): return self.price_text def get_queryset(self): """Return the last five published questions.""" return Question.objects.order_by('-pub_date')[:5] And this is code of models.py class Goods(models.Model): description_text = models.CharField(max_length=200) price_text = models.CharField(max_length=200) def __str__(self): return self.description_text def __str__(self): return self.price_text -
Using name in dropdown
i want to use the dropdown menu in the request POST query, but I cannot define the name for the dropdown menu options, how can I do this? Is there a chance to do if else according to value with POST in this query? my ex. view; def list(request): if 'Storefront' in request.POST: filtre=Alarmlar.objects.filter( Ekip__contains="Storefront" ) elif 'CAC' in request.POST: filtre=Alarmlar.objects.filter ( Ekip__contains="Cac") else: filtre=Alarmlar.objects.all() members_list=filtre paginator = Paginator(members_list, 100) page = request.GET.get('page') try: members = paginator.page(page) except PageNotAnInteger: members = paginator.page(1) except EmptyPage: members = paginator.page(paginator.num_pages) return render(request, 'list.html', {'members': members}) html; <select class="form-control" id="adsoyad" name="adsoyad" style="text-align:center" required> <option value="" disabled selected >Choose...</option> <option value="all">ALL</option> <option value="Cac">Cac</option> <option value="Storefront">Storefront</option> </select> -
How can i save external kraken API json info in my Django database?
The context I want to save json data from an external public kraken API in my Django database My view.py from rest_framework import generics from .serializers import KrakenSerializer from kraken.models import Kraken import requests class KrakenList(generics.RetrieveAPIView): serializer_class = KrakenSerializer queryset = Kraken.objects.all() def get_object(self): url = 'https://api.kraken.com/0/public/Time' r = requests.get(url, headers={'Content-Type': 'application/json'}) kraken = r.json() return kraken def seed_kraken(): for i in kraken: krakenss = Kraken( unixtime=i["unixtime"], ) krakenss.save() My urls.py from .views import KrakenList from django.urls import path app_name = 'kraken' urlpatterns = [ path('', KrakenList.as_view(), name='listkraken'), ] My serializers.py from rest_framework import serializers from kraken.models import Kraken class KrakenSerializer(serializers.ModelSerializer): class Meta: model = Kraken fields = ('unixtime',) My models.py from django.db import models class Kraken(models.Model): unixtime = models.IntegerField(default=0) This the Django REST framework with wrong empty json answer: This is how the json unixtime answer should look like in my Django REST framework The issue Do you have any suggestion of (i) how can i get the json info working accordingly, and (ii) how can i afterwards save it in my django database? -
I get a 502 Bad Gateway error with django app on AppEngine
I'm deploying a django app on Google app engine (flexible environment). The app works fine locally and the deployment (using gcloud app deploy) goes well. While the homepage loads well, I get a 502 Bad Gateway nginx error when I load some binary data (about 40Mo) using pickle from a directory in the same app directory (through a POST request). I've tried many proposed solutions (change the PORT to 8080, add the gunicorn timeout or add --preload, change n° of workers..), but still have the problem. I think that the problems comes from the fact that I load a heavy file, since I can access the django admin on the deployed version.. I'm not really knowledgeable in gunicorn/nginx (the first time I deploy an app). I'll be very thankful if you have some ideas after so much time spent on this! The log file doesn't show any error: 2021-10-30 14:38:46 default[20211030t141946] [2021-10-30 14:38:46 +0000] [1] [INFO] Starting gunicorn 19.9.0 2021-10-30 14:38:46 default[20211030t141946] [2021-10-30 14:38:46 +0000] [1] [DEBUG] Arbiter booted 2021-10-30 14:38:46 default[20211030t141946] [2021-10-30 14:38:46 +0000] [1] [INFO] Listening at: http://0.0.0.0:8080 (1) 2021-10-30 14:38:46 default[20211030t141946] [2021-10-30 14:38:46 +0000] [1] [INFO] Using worker: sync 2021-10-30 14:38:46 default[20211030t141946] [2021-10-30 14:38:46 +0000] [10] [INFO] … -
Handle select multiple on django
I have this on template <select name="document" id="document" multiple=""> <option value="2">test 1</option> <option value="3">test 2</option> </select> When I select two options when I accept the request in views.py I got correctly 2 options selected self.request.POST // It prints 'document': ['2', '3'] But when I try to select the field like this self.request.POST['document'] // It prints only '3' How can I select 2 options? Thanks