Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am working on django project when i run >> python manage.py sqlmigrate travello 0001 command it show the following error help on this
enter image description here python manage makemigrations python manage.py sqlmigrate travello 0001 please find the image and provide the solutions -
I've deleted my .sock file - Django, Nginx, Gunicorn
When I was trying to pull from Git, I accidentally deleted the sock file. What am I supposed to do now? My websites showing "502 Bad Gateway" and nothing's working. I need help, fast. Could you tell me what to do now? -
django migrations and git branches while working on multiple features simultaneously
In django, when working on multiple new features simultaneously, what is the best way to handle migrations with git? I’m in middle of working on feature1, on its own branch. Now I need to create feature2 and push it to production. Should I: fork new feature2 branch off of production, create feature2, merge back to prod, migrate. fork new feature2 branch off of production, create feature2, migrate, merge back to prod. Or some other way? And when I go back to feature1, what do i do to insure everything will be up to date? -
Django ORM: Excluding Specific Record in Many-to-Many Relationship
I have a many-to-many relationship between two models Profile and Conversation like this: class Profile(models.Model): # ... class Conversation(models.Model): members = models.ManyToManyField(Profile, related_name="conversations") Now I want to select all the conversations that a specific profile is a member in it, I tried this which worked but I'm not sure if it's the right way: conversations = Conversation.objects.filter(members='<profile_pk>') Also, I want to exclude that member's data from the result because I already have it, or should I exclude his data on the client side? -
I'm trying host Django prj with xampp
I have set up all the necessary steps such as installing mod_wsgi (including copying to apache's modules folder), c++ tool build, but when I run xampp, it fails.1 and what's keeping it from running is this line of code LoadModule wsgi_module modules/mod_wsgi.so located in the file httpd.conf -
Django not showing images in admin's editor (404 error)
I'm try create post and add to this post images. And i'm use for this Django-summernote in Django 3.0. Picture upload to folder on hard disk, but not showing in editor. Console show 404 Error. Please, give me advice how to fix it? Thank you! settings.py STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' ADMIN_MEDIA_PREFIX = STATIC_URL + "grappelli/" X_FRAME_OPTIONS = 'SAMEORIGIN' SUMMERNOTE_THEME = 'bs4' # Show summernote with Bootstrap4 MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' urls.py urlpatterns = [ path('admin/filebrowser/', site.urls), path('summernote/', include('django_summernote.urls')), path('admin/', admin.site.urls), path('', include('blog.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) image = models.ImageField(upload_to="", blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def get_absolute_url(self): return "/api/article/%i/" % self.id def __str__(self): return self.title Console screenshoot -
how to fix typeError: sequence item 1: expected a bytes-like object, str found
i'm trying to create an object in database with django. my configuration is below. 'nucoin' : { 'ENGINE': 'mysql.connector.django', 'NAME': "db_name", 'USER': 'db_user', 'PASSWORD': 'db_password', 'HOST': 'db_host', 'PORT': '3306', 'SSL': True, }, and i'm getting the following trackback.. Original exception was: Traceback (most recent call last): File "/home/ahmed/gitclones/clone-beru/web_push/backend/envNotifer/lib/python3.8/site-packages/rest_framework/serializers.py", line 939, in create instance = ModelClass._default_manager.create(**validated_data) File "/home/ahmed/bitbucket/notification_platform_sdk/backend/projects/managers.py", line 23, in create project.save(using="nucoin") File "/home/ahmed/gitclones/clone-beru/web_push/backend/envNotifer/lib/python3.8/site-packages/django/db/models/base.py", line 726, in save self.save_base(using=using, force_insert=force_insert, File "/home/ahmed/gitclones/clone-beru/web_push/backend/envNotifer/lib/python3.8/site-packages/django/db/models/base.py", line 763, in save_base updated = self._save_table( File "/home/ahmed/gitclones/clone-beru/web_push/backend/envNotifer/lib/python3.8/site-packages/django/db/models/base.py", line 868, in _save_table results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw) File "/home/ahmed/gitclones/clone-beru/web_push/backend/envNotifer/lib/python3.8/site-packages/django/db/models/base.py", line 906, in _do_insert return manager._insert( File "/home/ahmed/gitclones/clone-beru/web_push/backend/envNotifer/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/ahmed/gitclones/clone-beru/web_push/backend/envNotifer/lib/python3.8/site-packages/django/db/models/query.py", line 1270, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) File "/home/ahmed/gitclones/clone-beru/web_push/backend/envNotifer/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1410, in execute_sql cursor.execute(sql, params) File "/home/ahmed/gitclones/clone-beru/web_push/backend/envNotifer/lib/python3.8/site-packages/django/db/backends/utils.py", line 98, in execute return super().execute(sql, params) File "/home/ahmed/gitclones/clone-beru/web_push/backend/envNotifer/lib/python3.8/site-packages/django/db/backends/utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/home/ahmed/gitclones/clone-beru/web_push/backend/envNotifer/lib/python3.8/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers return executor(sql, params, many, context) File "/home/ahmed/gitclones/clone-beru/web_push/backend/envNotifer/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/home/ahmed/gitclones/clone-beru/web_push/backend/envNotifer/lib/python3.8/site-packages/mysql/connector/django/base.py", line 149, in execute return self.cursor.execute(query, new_args) File "/home/ahmed/gitclones/clone-beru/web_push/backend/envNotifer/lib/python3.8/site-packages/mysql/connector/cursor_cext.py", line 263, in execute stmt = RE_PY_PARAM.sub(psub, stmt) TypeError: sequence item 1: expected a bytes-like object, str found if you need more detail. … -
UserProfileInfo matching query does not exist Django
I need to have extra information about a person, more than the default User model provides. That's why I've created the UserProfileInfo model that's supposed to hold all this extra info, such as house_number, phone_number, full_name, and community. Now, an instance of UserProfileInfo is created whenever a user registers. But when I run this route called all_books in views.py, I get an error: UserProfileInfo matching query does not exist. Here's my all_books view: def all_books(request): if request.user.is_authenticated: context = { "books": Book.objects.all(), "request": request, "user_profile": UserProfileInfo.objects.get(user=request.user), } else: context = { "books": Book.objects.all(), "request": request, "user_profile": False, } if request.GET.get("context") == "mail_sent": context["mail_sent"] = True return render(request, 'main/all_books.html', context) This error happens only when I've signed in, and not when I'm not signed in. When I head over to the admin, I see that the profile has been created. But I don't understand why this isn't able to get that. -
docker + REST API in django
i have API project with python that work OK. after building a docker image it return this error: module 'keras.backend' has no attribute 'get_session' and then it doesn't work anymore. does anybody have an idea what should i do? I am on Ubuntu with python=3.8.10 requirments: tensorflow==2.4.0 tensorflow-gpu==2.4.0 keras==2.4.3 numpy==1.19.3 pillow==8.1.1 scipy==1.4.1 h5py==2.10.0 matplotlib==3.3.2 keras-resnet==0.2.0 Django==3.2.10 djangorestframework==3.13.0 opencv-python imageai -
Django to Heroku, How to migrate sqlite3 data to postgres
I tried to host a website on heroku but I keep getting this error File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: relation "home_product" does not exist LINE 1: ...home_product"."price", "home_product"."slug" FROM "home_prod... whenever I tried to use heroku run python manage.py migrate -a appname I mainly used this video as a reference to hosting: https://www.youtube.com/watch?v=UkokhawLKDU&t=964s and also these articles which didn't really help tbh: Heroku Django Database Error https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Deployment Here's my settings.py Django settings for Corbett_Jewelry project. Generated by 'django-admin startproject' using Django 3.1.7. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path import os import django_heroku import dj_database_url from decouple import config import psycopg2 # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = os.environ.get('DJANGO_DEBUG', '') != 'False' ALLOWED_HOSTS = ['127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', … -
How to prevent form update conflict among multiple users in Django?
I have a form like a student form. It can be updated by a function in view. There are multiple users that have the update permission for this form. The problem is when 2 users open the form of a student(id=1) at the same time. They can change fields and save the form. All changes of a user will be ignored and lost. How to prevent this conflict. I want if a user opens a specific student form, other users can not open it until the first user close the form or it's time for the update be expired. -
How to convert javascript object to python readable
I'm trying to parse below object from javascript post data into python using ast.literal_eval(obj) but ending up into below error Error: malformed node or string: <_ast.Name object at 0x7fb484eb8070> Object Value: '[{"dose":"1","duration":"2","name":"Item1","code":"pharma2","usage":{"morning":true,"afternoon":false,"evening":false,"night":false,"sos":false}},{"dose":"1","duration":"4","name":"Item2","code":"pharma1","usage":{"morning":false,"afternoon":false,"evening":false,"night":true,"sos":false}}]' -
How to choose one item in many to many relationship as special?
What is the best practice to choose one item from a m2m relationship? Lets say I've got an album of photos: class Photo(models.Model): img = models.FileField() class Album(models.Model): photos = models.ManyToManyField("Photo") But now I also want to pick one photo as a cover. I could use a Foreign Key in Album to one Photo, but then I'd always need to check whether this photo is actually in the photos of that album. Is there a better way? Sorry for the basic question I just somehow can't find the right words to google it. Thanks, Michael -
How to pass Django InMemoryUploadFile to serializer in case with images?
I'm creating an API using Django Rest Framework to save images from file directly or from url. I've got no problem with first case but with second. So, my models looks like this: class Image(models.Model): picture = models.ImageField(upload_to="site_media", blank=True) url = models.URLField(null=True, blank=True, max_length=255) parent_picture = models.IntegerField(null=True, blank=True) @property def name(self): return os.path.split(self.picture.name)[-1] @property def width(self): return self.picture.width @property def height(self): return self.picture.height Next, my serializer class: class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image fields = [ 'id', 'name', 'url', 'picture', 'width', 'height', 'parent_picture' ] The main idea is if you pass the URL while post request, API needs to download image from this URL and store it in database. To do this I overwrote create method in Django Rest Framework ModelViewSet class: from io import BytesIO import urllib import os from django.core.files.uploadedfile import InMemoryUploadedFile from PIL import Image as PILImage from rest_framework import status from rest_framework import viewsets from rest_framework.response import Response from .models import Image from .serializers import ImageSerializer class ImageViewSet(viewsets.ModelViewSet): serializer_class = ImageSerializer queryset = Image.objects.all() def create(self, request, *args, **kwargs): if request.data["url"]: url = request.data["url"] image_extensions = { ".jpg": "JPEG", ".jpeg": "JPEG", ".png": "PNG", ".gif": "GIF" } image_path = urllib.parse.urlparse(url).path image_filename = image_path.split("/")[-1] extension = os.path.splitext(image_filename)[-1] … -
Django Admin Templates - How to add a "back to list" button?
Working with Django admin - still pretty new. I need to add a button to the footer (that appears when editing or adding an object) that sends the user back to the list page for that object. I am able to add the button itself to the footer by adding templates/admin/submit_line.html: {% load i18n admin_urls %} <div class="submit-row"> {% if show_save %}<input type="submit" value="{% trans 'Save' %}" class="default" name="_save" {{ onclick_attrib }}/>{% endif %} {% if show_delete_link %}<p class="deletelink-box"><a href="{% url opts|admin_urlname:'delete' original.pk|admin_urlquote %}" class="deletelink">{% trans "Delete" %}</a></p>{% endif %} {% if show_save_as_new %}<input type="submit" value="{% trans 'Save as new' %}" name="_saveasnew" {{ onclick_attrib }}/>{%endif%} {% if show_save_and_add_another %}<input type="submit" value="{% trans 'Save and add another' %}" name="_addanother" {{ onclick_attrib }}/>{% endif %} {% if show_save_and_continue %}<input type="submit" value="{% trans 'Save and continue editing' %}" name="_continue" {{ onclick_attrib }}/>{% endif %} <input type="submit" value="{% trans 'Go Back' %}" {{???}}/> </div> But I don't know where to go from there. Presumably it is possible because Django breadcrumbs exist (and the relevant page is always the most recent link in the breadcrumbs), but I don't know how I'm supposed to get the link to the relevant page. -
when ever i am adding def str function to name it the model gives error
def __str__(self): return self.category_name when ever i am adding this str function in my model class Category(models.Model): category_name = models.CharField(max_length=50, unique=True,blank=True,null=True) slug = models.SlugField(max_length=100, unique=True,blank=True,null=True) description = models.TextField(max_length=255, blank=True,null=True) cat_image = models.ImageField(upload_to='photos/categories', blank=True,null=True) class Meta: verbose_name = 'category' verbose_name_plural = 'categories' def get_url(self): return reverse('core:category', args=[self.slug]) then it gives me error TypeError at /admin/core/product/ str returned non-string (type NoneType) -
Passing Django view data to JavaScript Chart
I have some data that is returned via Django view, I'm trying to render the data in an Apex Pie Chart. So I need to pass the data into JavaScript as this is where the data series is. var pieColors = getChartColorsArray("#pie_chart"), options = { chart: { height: 320, type: "pie" }, series: [44, 55, 41, 17, 15], labels: ["Series 1", "Series 2", "Series 3", "Series 4", "Series 5"], colors: pieColors, legend: { show: !0, position: "bottom", horizontalAlign: "center", verticalAlign: "middle", floating: !1, fontSize: "14px", offsetX: 0 }, responsive: [{ breakpoint: 600, options: { chart: { height: 240 }, legend: { show: !1 } } }] }; (chart = new ApexCharts(document.querySelector("#pie_chart"), options)).render(); How do I pass the data in as it needs to be dynamic in the sense that the data in the pie chart could change based on other actions within the app? Should just embed the JS into my HTML template and then set the series values to series: [{{ value.1 }}, {{ value.2 }}, ...], Thanks -
LeaderboardAPI : I want to show only Today's record by comparing it with the created date
My Modely.py I am storing playername, TotalPoints, created_date by POST API from django.db import models from django.utils.translation import ugettext as _ # Create your models here. class leaderboard(models.Model): name = models.CharField(_("playername"), max_length=255) TotalPoints = models.IntegerField(_("TotalPoints")) created_date = models.DateTimeField(auto_now_add=True) My Serializers.py file: This is my Searializer: from rest_framework import serializers from .models import leaderboard class leaderboardSerializers(serializers.ModelSerializer): class Meta: model = leaderboard fields = [ 'name', 'TotalPoints', ] class lwithcdateSerializers(serializers.ModelSerializer): class Meta: model = leaderboard fields = [ 'name', 'TotalPoints', 'created_date', ] My Views class Leaderboard(APIView): def get(self, request, formate=None, **kwargs): today = datetime.date.today() serializer = lwithcdateSerializers(leaderb.objects.all().order_by('-TotalPoints') [:40], many=True) return Response(serializer.data) Please check the above code and let me know how can I display only Today's record -
Django - Changed DB from Sqlite3 to Postgres - do I need to do something else to reflect changes?
In my server, I changed the DB to Postgres from SQlite3. Because this is a new website and doesn't have much data yet (except test stuff) I didn't have to do DB migration or whatever else it is called. I just changed settings.DATABASES to include Postgres. Here's my settings.DATABASES in settings.py: from sys import platform if platform == 'darwin': # OSX DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR + '/db.sqlite3', } } else: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'pfcbookclub', 'USER': 'admin', 'PASSWORD': 'g&zy8Je!u', 'HOST': '127.0.0.1', 'PORT': '5432', } } I develop on an M1, and psycopg2 doesn't seem to work for me, how many ever times I try to install libq or openssl with Homebrew on Rosetta, which is why I decided to use Sqlite on my Mac and Postgres on my server. Now, when I pulled these changes with git onto my server, I refreshed the page on my domain, but all the test data I had filled in my Sqlite3 database still showed. I thought it would be empty because I haven't filled up the Postgres DB with anything and I didn't do any sort of migration that would convert db.sqlite3 into Postgres … -
This page isn’t working right now. If the problem continues, contact the site owner. HTTP ERROR 405
I am getting the following error message when I fill the form: This page isn’t working right now. If the problem continues, contact the site owner. HTTP ERROR 405. Kindly advise. views: from django.shortcuts import render, get_object_or_404 from .models import Post from django.http import HttpResponseRedirect from django.urls import reverse from django.views.generic import ListView from .forms import CommentForm from django.views import View class UltimatePostView(View): def get(self, request, slug): post = Post.objects.get(slug=slug ) context = { "post": post, "post_tags" : post.tag.all(), "comment_form" : CommentForm() } return render(request, "gold-blog/post-detail.html", context ) def post(self, request, slug): comment_form = CommentForm(request.POST) post = Post.objects.get(slug=slug ) if comment_form.is_valid(): comment = comment_form.save(commit=False) comment.post = post comment.save() return HttpResponseRedirect(reverse("post-detail-page", args=[slug])) context = { "post": post, "post_tags" : post.tag.all(), "comment_form" : comment_form } return render(request, "gold-blog/post-detail.html", context) -
Django admin is very slow when loading from the OneToOne user model
I think I am doing admin model wrong because it is taking like 30 seconds to load and I think its because my sql queries are too inefficient and there may be creating more look ups than needed. Is there a way that I can speed this up? class UserInformationAdmin(admin.ModelAdmin): list_display = ( 'user_username', 'user_first_name', 'user_last_name', 'major' ) @admin.display(description='user.username') def user_username(self, obj): try: return obj.user.username except Exception: return None @admin.display(description='user.first_name') def user_first_name(self, obj): try: return obj.user.first_name except Exception: return None @admin.display(description='user.last_name') def user_last_name(self, obj): return obj.user.last_name``` -
how to trigger email to admin panel in django through contact form using form.is_valid()?
Whenever a user sends email through the contact form, it should be displayed to the admin in the admin panel. Now, when I click submit, it goes back to "contact.html" as stated in function, what are the possible reasons it is not being valid when it is saved? I'm pretty sure I'm filling the form correctly from the web. here is the model: class Contact(models.Model): name = models.CharField(max_length=100) email = models.EmailField(default="default") subject = models.CharField(max_length=100) message = models.CharField(max_length=100) def __str__(self): return self.name the function in views.py: def display3(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): form.save() return render(request, 'success.html') form = ContactForm() context = {"form": form} return render(request, 'contact.html', context) lastly, this is in forms.py: class ContactForm(ModelForm): class Meta: model = Contact fields = '__all__' -
Unable to fetch row elements values using Javascript
I'm little new to Javascript. This is using django as backend. I'm trying to capture data from table columns like 'dose', 'duration' and 'usage' which uses text box and checkbox. Whenever I hit the button with id='qty', then I'm able to see correct value for first click but when I click the button for another element it still submits same previous data instead of data on the same row. Below is the sample output that I captured from console log #Item 1 Log [Log] Object (e28c8d12-1a95-44e5-9813-dfc2f4bf3bb1, line 502) code: "" dose: "1" name: "PARACIP" price: undefined quantity: "2" total: NaN usage: {morning: false, afternoon: false, evening: false, night: false, sos: false} #Item 2 Log [Log] Object (e28c8d12-1a95-44e5-9813-dfc2f4bf3bb1, line 502) code: "" dose: "1" name: "Paracetamol" price: undefined quantity: "2" total: NaN usage: {morning: false, afternoon: false, evening: false, night: false, sos: false} Object Prototype HTML Code <table id="example" class="table table-striped table-bordered" style="width:100%"> <thead> <tr> <th>Item</th> <th>Dose</th> <th>Duration</th> <th>Usage</th> <th>Action</th> </tr> </thead> <tbody> {% for item in inventory %} <tr> <td>{{ item.brand }} {{ item.item_name }}</td> <td> <input type="text" class="form-control" name="dose", id="dose"> </td> <td> <input type="text" class="form-control" name="duration" id="duration"> </td> <td> <div class="form-check form-check-inline"> <input class="form-check-input" type="checkbox" id="morning" name="morning"> <label class="form-check-label" … -
Error in DRF only! UNIQUE constraint failed: questions_question.id
Here is the model, serializer and view. When I try to create a new question with the API endpoint It's showing the UNIQUE constraint failed: questions_question.id but It's going to be saved into the admin panel. Please share an idea to solve the error! models.py class Question(models.Model): author = models.ForeignKey( User, on_delete=models.CASCADE, related_name='all_questions') title = models.CharField(max_length=225) desc = models.TextField() slug = models.SlugField(max_length=225, # unique=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self) -> str: return f"{self.title}" serializers.py class QuestionsSerializer(serializers.ModelSerializer): author = serializers.StringRelatedField(read_only=True) class Meta: model = Question fields = "__all__" view.py class QuestionCreateAPI(generics.CreateAPIView): model = qs_models.Question queryset = qs_models.Question.objects.all() serializer_class = own_serializers.QuestionsSerializer permission_classes = (permissions.IsAuthenticated, ) def perform_create(self, serializer): return super().perform_create(serializer.save(author=self.request.user)) Terminal Error return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: UNIQUE constraint failed: questions_question.id But it still saving on the admin panel -
Django Button Handling
I only want to display 2 buttons which should submit on click. If the buttons are clicked it should only display form 2 on the User button or else another form on Doctor button(add field to form 2). Currently it does work if I used radios if I used another submit button but I'd like for button click handling in the wizard which I'm unsure of. flow: form1-> show_message_form_condition {'is_doctor': True} for both buttons clicks and for radio it's is_{'is_doctor': True} and {'is_doctor': False}-> display form 2 if value is false. forms.py class PickUserType(forms.Form): is_doctor = forms.BooleanField(required=False) class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=False, help_text='Optional.') last_name = forms.CharField(max_length=30, required=False, help_text='Optional.') email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') class Meta: model = Profile fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', ) Both of them {% block content %} <form method = "POST" action='.' enctype="multipart/form-data"> {% csrf_token %} <!-- A formwizard needs this form --> {{ wizard.management_form }} <!-- {{form_as_p}} --> <button type="submit" value="Doctor" name="0-is_doctor">Doc</button> <button type="submit" value="User" name="0-is_doctor">User</button> <!-- {% for field in form.visible_fields %} {{ field.errors }} {% for radio in field %} <div class="form-check form-check-inline"> {{ radio }} </div> {% endfor %} {% endfor %} <input type="submit" …