Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Objects not shown in view when filtering
I've a model called: "Sample", It reference my Sample products. I want to show all my Samples in a page: shop/muestras.html This model has a ForeignKey reference to my Category model. I use this field called category to filter all the samples by doing: c_slug = 'muestras' muestras = Sample.objects.filter(category__slug=c_slug) I could also just do: muestras = Sample.objects.all() Becuase all my samples have that category 'Muestras'. Either way my Samples are not been shown. However, If I filter my other model Products by it's category 'Muestras' all the items with this category are shown: muestras = Product.objects.filter(category__slug=c_slug) Just to be sure, I've tested filtering the Sample model in Shell and I'm getting the expected objects: from shop.models import Sample samples = Sample.objects.filter(category__slug = 'muestras') samples <QuerySet [<Sample: Cinta de embalaje personalizada de muestra>, <Sample: Etiquetas personalizadas de muestra>, <Sample: Imanes personalizados de muestra>, <Sample: Paquete d e muestra>, <Sample: Stickers personalizados de muestra>]> What could be wrong? views.py: def SamplePackPage(request): # La categoria es necesaria para mostrar el video de c/categoria categoria_muestras = Category.objects.get(slug='muestras') # Productos que pertenecen a la categoria muestras muestras = Sample.objects.filter(category__slug=c_slug) c_slug = 'muestras' muestras = Sample.objects.all() # # muestras = Sample.objects.filter(category__slug=c_slug) # # muestras = … -
Visual Studio Test Explorer For Python Django Tests with Database Access
Starting test runs from Visual Studio Test Explorer doesn't call database creation and Django setup() before running the test(s). My current workaround is to call something like this, which I keep in config.settings.test def setUpTestingWithDatabase(): import os from django.test.utils import setup_test_environment from django import setup os.environ["DJANGO_SETTINGS_MODULE"] = "config.settings.test" setup_test_environment() setup() by adding this code to the top of every test file: import sys if not ('manage.py' in sys.argv): from config.settings.test import setUpTestingWithDatabase setUpTestingWithDatabase() This works, and can still use the nose runner, and a CLI call like > python manage.py test myApp This works all very well, but I would like to avoid this code, keep it vanilla AND use it from both CLI and Test Explorer. MS Visual Studio supports runsettings, and I wonder if they can be used? Any other ideas? -
NoReverseMatch at /students/classes/Reverse for 'delete_gr' with arguments '('',)' not found
i am trying to edit classes in my classes models but its giving error help me try to fix this error Reverse for 'editclasses' with arguments '('',)' not found. 1 pattern(s) tried: ['students/editclasses/(?P[0-9]+)/$'] classes.html {% for clas in clas %} <tr> <td>{{clas.class_name}}</td> <td> <a href="{% url 'editclasses' clas.pk %}" class="btn btn-outline-info btn-sm" role="button"> Edit</a> </td> </tr> {% endfor %} editclasses.html div class="container"> <h4 class="text-center">Edit Class</h4> <hr/> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {% for field in form %} <div class="form-group row"> <label for="id_{{ field.name }}" class="col-2 col-form-label">{{ field.label }}</label> <div class="col-10"> {{ field }} {{ field.errors }} </div> </div> {% endfor %} <button type="submit" class="btn btn-primary" name="button">Update</button> </form> <br/><br/> </div> viewdata.html {% for gr in gr %} <tr> <td>{{gr.gr_no}}</td> <td>{{gr.first_name}}</td> <td>{{gr.last_name}}</td> <td>{{gr.date_birth}}</td> <td>{{gr.classes_A}}</td> <td>{{gr.sections_A}}</td> <td>{{gr.gender}}</td> <td>{{gr.classes_C}}</td> <td>{{gr.sections_C}}</td> <td>{{gr.address}}</td> <td>{{gr.area_code}}</td> <td>{{gr.status}}</td> <td> <a href="{% url 'editgr' gr.pk %}" class="btn btn-outline-info btn-sm" role="button"> Edit</a> <a href="{% url 'delete_gr' gr.pk %}" class="btn btn-outline-dark btn-sm" role="button"> Delete</a> </td> </tr> {%endfor%} views.py for classes and delete_gr def editclasses(request, pk): clas = get_object_or_404(Classes, pk=pk) if request.method == "POST": form = ClassesForm(request.POST or None, instance=clas) if form.is_valid(): form.save() return redirect('home') else: form = ClassesForm(instance=gr) return render(request, 'students/editclasses.html', {'form': form}) gr_register.objects.filter(pk=pk).delete() gr = gr_register.objects.all() context = { 'gr' … -
Django Template Extends: Children not overriding parent
I run the python manage.py runserver and it displays only the parent - which is base.html. According to the documentation, it should override the parent template with the child template: Template inheritance allows you to build a base “skeleton” template that contains all the common elements of your site and defines blocks that child templates can override. base.html and base_child.html are in the same folder: MyProject/MyApp/Templates/ views.py def baseview(request): return render(request,'base.html') Here are my templates: base.html <!DOCTYPE html> <html lang="en"> <head> <title> {% block titleblock %} Hello World Title {% endblock %} </title> </head> <body> <p> {% block bodyblock %} Hello World! {% endblock %} </p> </body> </html> base_child.html {% extends "base.html" %} {% block titleblock %} Hello Grass title {% endblock %} {% block bodyblock %} Hello Grass! {% endblock %} I believe the answers and comments for this question are unclear in description, which is why I pose this one. -
Django: Slicing form data before "form.is_valid"
I have a ModelForm, which saves and creates a new object for my class Person. This class Person has an attr called is_adult. Its value is a model.CharField with a max_length=1, where I save only values Y or N (Yes/No). The problem is that this attr is rendered as a Select HTML field. In this Select field, the available choices are "Yes" and "No", therefore when the form is sent as a POST method it comes with a value of 2-3 length CharField, but its Model attr has a max_length of 1, so I need to slice those two options before checking if form.is_valid(). Otherwise the form is not accepted because it is posting with a value of 2-3 chars and it's expecting 1 char. models.py: class Person(models.Model): is_adult = models.CharField(max_length=1, null=False, choices=ADULT_CHOICES, default='N') choices.py: ADULT_CHOICES= ( (0, 'No'), (1, 'Yes'), ) forms.py: class PersonForm(forms.ModelForm): class Meta: model = Person fields = ["is_adult"] widgets = { 'is_adult': forms.Select(attrs={'class': 'form-control'}), } labels= { 'is_adult': 'Is an adult?', } And of course views.py is expecting 'Y' or 'N', and not 'Yes' or 'No'. I tried to slice its string with the Python syntaxis, but I couldn't get the form field value before … -
How to fix "Uncaught SyntaxError: Unexpected number" appearing only in Chrome?
I am trying to run a Django site, using Gunicorn (with docker compose). Everything works as expected in Firefox, but Chrome reports the error "Uncaught SyntaxError: Unexpected number" for random .js scripts. If I reload the page, scripts are loaded without any errors. So, at first I had a similar issue, since Chrome was randomly failing to load scripts. I solved this by changing the port in Gunicorn from 8080 to 80. However, once I did that, the scripts started loading but also started throwing the Unexpected number error. I have tested it on both Chromium (Ubuntu 18) and Google Chrome (Windows), running the web site locally and from a server. Also, I've noticed the following: 1) files which throw errors are rarely the same, so in one window script example1.js may work, and example2.js throws the error, and in another window example3.js throws an error and the rest work. 2) if I reload the page, no .js file throws an error. 3) every error indicates that the problem is in line 5, like this: "Uncaught SyntaxError: Unexpected number jquery-3.2.1.min.js:5". Would greatly appreciate any advise on how to tackle this. -
How to save object in django database
I am creating models in django, i need a field to save object. I checked django models fields but didn't find any field to save object. Is there any field to save object in django database? -
How to fix Migrations Error , While migrating My Models
While using the command in CLI, for migrating my Models created in Django "python manage.py migrate" The CLI Shows an error init() missing 1 required positional argument: 'on_delete' CODE:- from django.db import models class Topic(models.Model): top_name = models.CharField(max_length=264,unique=True) def __str__(self): return self.top_name class Webpage(models.Model): topic = models.ForeignKey(Topic) name = models.CharField(max_length=264,unique=True) url = models.URLField(unique=True) def __str__(self): return self.name class AccessRecord(models.Model): name = models.ForeignKey(Webpage) date = models.DateField() def __str__(self): return str(self.date) This is the code -
NoReverseMatch at /students/classes/Reverse for 'delete_gr' with arguments
Reverse for 'delete_gr' with arguments '('',)' not found. 1 pattern(s) tried: ['students/delete_gr/(?P[0-9]+)/$'] i am trying to edit classes but its giving an error viewdata.html <td> <a href="{% url 'delete_gr' gr.pk %}" class="btn btn-outline-dark btn-sm" role="button"> Delete</a> </td> editclasses.html <div class="container"> <h4 class="text-center">Edit Class</h4> <hr/> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {% for field in form %} <div class="form-group row"> <label for="id_{{ field.name }}" class="col-2 col-form-label">{{ field.label }}</label> <div class="col-10"> {{ field }} {{ field.errors }} </div> </div> {% endfor %} <button type="submit" class="btn btn-primary" name="button">Update</button> </form> <br/><br/> </div> views.py (For delete_gr) and (FOR editclasses) def delete_gr(request, pk): gr_register.objects.filter(pk=pk).delete() gr = gr_register.objects.all() context = { 'gr' : gr } return render(request, 'students/index.html', context) def editclasses(request, pk): clas = get_object_or_404(Classes, pk=pk) if request.method == "POST": form = ClassesForm(request.POST or None, instance=clas) if form.is_valid(): form.save() return redirect('home') else: form = ClassesForm(instance=clas) return render(request, 'students/editclasses.html', {'form':form}) urls.py path('delete_gr/<int:pk>/', views.delete_gr, name='delete_gr'), path('editclasses/<int:pk>/', views.editclasses, name='editclasses'), i am trying to edit classes but query does not working its giving an error about this -
Django handle Annonymous users
I am trying to implement anonymous writes to a board. The information of the anonymous user (IP address and nickname) must be stored in the database. Currently, I have a User model and an Article model like this. class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(_('Username'), unique=True, null=True) etc... class Article(models.Model): id = models.AutoField(primary_key=True) author = models.ForeignKey(User, verbose_name=_("Author"), on_delete=models.PROTECT, null=True, blank=True) etc.... I thought of several ways to implement the anonymous write feature. For every anonymous user create User with just ip address and nickname and set foreign key to that user. class User(AbstractBaseUser, PermissionsMixin): TYPE_FIXED_USER = 0 TYPE_ANONYMOUS = 2 TYPE_CHOICES = ( (TYPE_FIXED_USER, 'Fixed User'), (TYPE_UNFIXED_USER, 'Unfixed User'), (TYPE_ANONYMOUS, 'Annonymous'), ) user_type = models.IntegerField(_('User type'), choices=UserType.TYPE_CHOICES) This looks like the easiest way, but I worry that it will create a lot of User and cause high load to the database. Add author_type, anon_author_ip, anon_author_nick field to Article. class Article(models.Model): TYPE_FIXED_USER = 0 TYPE_ANONYMOUS = 2 TYPE_CHOICES = ( (TYPE_FIXED_USER, 'Fixed User'), (TYPE_UNFIXED_USER, 'Unfixed User'), (TYPE_ANONYMOUS, 'Annonymous'), ) author_type = models.IntegerField(_('Author type'), choices=UserType.TYPE_CHOICES) This seems OK, but searching articles by nickname will be difficult. If I am to search for user 'user1234' I will have to look for Article.objects.filter(user__nickname__contains='user1234') and Article.objects.filter(anon_author_nick__contains='user1234') … -
How can I authenticate users via social account from mobile app using retrofit2?
I'm trying to connect my website's API and mobile app. I need to authenticate the user with google account but I don't know how to do it. I created the backend with Django. And I set the endpoint as rest-auth/google/. On the restframework's page, it requires Access Token and Code but honestly I don't get how I can test if it actually works using actual google account. I want to test from mobile app but I don't understand how and what I need to POST. Anyone could give me tips? -
customize django-fluent admin page
Is there a way to customize django fluent template? I tried extending admin/base_site.py and adding my own styles to it. This seems to be working for django's default template but not in django-fluent. -
__init__() missing 1 required positional argument: 'model_field'
I am trying to use Nested Serializer, if I remove the "product=ProductSerializer()" from serializer A, the code runs sucessfully, else it gives the below error. How come the SizeSerializer is working but Productserializer don't. model A class SKU(models.Model): size = models.ForeignKey(Size,on_delete=models.CASCADE) product = models.ForeignKey(Product,on_delete=models.CASCADE) number = models.CharField(max_length=100,null=True,blank=True) price = models.IntegerField(null=True,blank=True) parent_sku = models.CharField(max_length=100,null=True,blank=True) active = models.BooleanField(default=True) model B class Product(models.Model): name = models.CharField(max_length=200,null=True,blank=True) active = models.BooleanField(default=True) serializer A class SKU_Serializer(serializers.ModelSerializer): size = SizeSerializer() product = ProductSerializer() class Meta: model = SKU exclude = ('created_at','updated_at') serializer B class ProductSerializer(serializers.ModelField): class Meta: model = Product exclude = ('created_at','updated_at') output(error) File "D:\1___DEVELOPMENT\Clothing\hoplet\sku\views.py", line 6, in <module> from sku.serializers import SKU_Serializer File "D:\1___DEVELOPMENT\Clothing\hoplet\sku\serializers.py", line 8, in <module> class SKU_Serializer(serializers.ModelSerializer): File "D:\1___DEVELOPMENT\Clothing\hoplet\sku\serializers.py", line 10, in SKU_Serializer product = ProductSerializer() TypeError: __init__() missing 1 required positional argument: 'model_field' -
Django Allauth static file(static/facebook/js/fbconnect.js ) is not showing up
How can I access this url https://www.localhost/static/facebook/js/fbconnect.js. in django allauth ? Getting error in console: Refused to execute script from 'https://www.localhost/static/facebook/js/fbconnect.js' because its MIME type ('image/png') is not executable. Please help -
Nginx not serving files from /var/www/html after deploying Django app
I have a Django application stored at /var/www/w_gm . Now I have used Nginx + Gunicorn to deploy it. My default conf file at root@dev:/etc/nginx/sites-enabled# ls default w_gm Default conf file : server { listen 80 default_server; listen [::]:80 ipv6only=on default_server; # SSL configuration # # listen 443 ssl default_server; # listen [::]:443 ssl default_server; # # Note: You should disable gzip for SSL traffic. # See: https://bugs.debian.org/773332 # # Read up on ssl_ciphers to ensure a secure configuration. # See: https://bugs.debian.org/765782 # # Self signed certs generated by the ssl-cert package # Don't use them in a production server! # # include snippets/snakeoil.conf; root /var/www/html; # Add index.php to the list if you are using PHP index index.php index.html index.htm index.nginx-debian.html; server_name _; location / { # First attempt to serve request as file, then # as directory, then fall back to displaying a 404. try_files $uri $uri/ =404; } # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 # location ~ \.php$ { include snippets/fastcgi-php.conf; # With php7.0-cgi alone: #fastcgi_pass 127.0.0.1:9000; # With php7.0-fpm: fastcgi_pass unix:/run/php/php7.0-fpm.sock; } w_gm conf file : server { listen 80; server_name 119.00.00.100; location = /favicon.ico { access_log off; log_not_found off; } … -
NoReverseMatch at /students/classes/
Reverse for 'delete_gr' with arguments '('',)' not found. 1 pattern(s) tried: ['students/delete_gr/(?P[0-9]+)/$'] i am trying to edit classes but it giving an error kindly help me to fix this problem thanks addclasses.html {% extends 'authenticate/base.html' %} {% block content %} <div class="container"> <h4 class="text-center">ADD Class</h4> <hr/> <form method="POST" action="{% url 'addclasses' %}" enctype="multipart/form-data"> {% csrf_token %} {% for field in form %} <div class="form-group row"> <label for="id_{{ field.name }}" class="col-2 col-form-label">{{ field.label }}</label> <div class="col-10"> {{ field }} {{ field.errors }} </div> </div> {% endfor %} <button type="submit" class="btn btn-primary" name="button">Submit</button> </form> <br/><br/> </div> {% endblock %} editclasses.html {% extends 'authenticate/base.html' %} {% block content %} <div class="container"> <h4 class="text-center">Edit Class</h4> <hr/> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {% for field in form %} <div class="form-group row"> <label for="id_{{ field.name }}" class="col-2 col-form-label">{{ field.label }}</label> <div class="col-10"> {{ field }} {{ field.errors }} </div> </div> {% endfor %} <button type="submit" class="btn btn-primary" name="button">Update</button> </form> <br/><br/> </div> {% endblock %} views.py def editclasses(request, pk): clas = get_object_or_404(Classes, pk=pk) if request.method == "POST": form = ClassesForm(request.POST or None, instance=clas) if form.is_valid(): form.save() return redirect('home') else: form = ClassesForm(instance=clas) return render(request, 'students/editclasses.html', {'form':form}) urls.py path('editclasses/<int:pk>/', views.editclasses, name='editclasses'), models.py class Classes(models.Model): class_code = models.AutoField(primary_key=True) … -
How to handle single websocket connection for all chats in Django Channels
I want to make a chat application like WhatsApp, and I want to make the backend server using Django Channels to handle all the real-time updates. I have been exploring various sources but I could not figure out one thing about how do i manage single websocket connection (single endpoint) for each user and still receive messages from all the chats he is part of in real time. As per my current understanding, I can add channel(web socket connection corresponding to a user) to different channel groups but what if a user is part of a lot of groups(basically is eligible to receive updates from various chats)? Should I add that channel to all the groups, he can be part of as soon as the connection is established or is there any workaround like one in my mind: Store the list of channels corresponding to each user. Make a for loop whenever a message is received to send message to websocket connections corresponding to each user involved to receive that chat? Any help is appreciated. Thanks in advance. -
Check for erros and other values at the widget level - maybe using custom form field
How can I access if a field has)errors at the level of widget? Using default I tried: {% if widget.attributes.has_errors %} or {% if widget.has_errors %} but are not working. I use custom widget templates, I'm thinking to use a custom form Field and overwrite the default field. I know clean method exist but I don't know how to push to the widget the dynamic(non default) data/attributes I want. I tried: class AWidget(forms.Widget): def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) has_errors = context['widget']['attrs'].pop('has_errors', None) context['widget']['has_errors'] = has_errors It works for errors but I don't know if is the best option plus I want to pass other values/attributes from Form Field,and I think will be better to try to overwrite the Form Field but I don't know exactly how. -
After the redirect of login.html, how does urls, views and templates know which user they are dealing with?
I am using the login.html provided in django.auth (default it is in templates/registration/login.html right?) Here is login.html: <!-- templates/registration/login.html --> {% extends 'base.html' %} {% block title %}Login{% endblock %} {% block content %} <h2>Login</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Login</button> </form> {% endblock %} Notice I did not notify any information (such as user.username)to pass to next url. I change the LOGIN_REDIRECT_URL to a url in a app which is: app_name = 'ride' urlpatterns = [ path('', views.home, name='home'), ] Notice again there is no in the url. Then it will go to views.py: def home(request): return render(request,'ride/home.html') And there is only a request object to pass to template. And here is ride/home.html: <!-- ride/templates/ride/home.html --> {% extends 'ride/base.html' %} {% block title %}HOmeeeeeeeeeee {% endblock %} {% block content %} {% if user.is_authenticated %} Hi {{ user.username }} {% else %} <p>Welcome to CJ & XY's Ride Sharing Service!</p> <a href="{% url 'login' %}">login</a> | <a href="{% url 'login:signup' %}">signup</a> {% endif %} {% endblock %} I use user.username in this template and it displays perfectly. So my question is, how does this final template know which user is authenticated and which user's username? … -
Django 2.1 template img src is not working
I want to display images on my Django template file but the images are broken. All the images are uploaded in media static files but they cannot be displayed in my template file, when I go to Django admin page and click on the image link, here is the error message I got: Page not found(404) Can anyone please help me with this issue? Here is the template file "post_detail.html": <div class="row"> <div class="col-6"> {% if instance.image %} <img src="{{ instance.image.url }}" alt="image" class="img-thumbnail"> {% endif %} <div class="post-detail-item text-justify"><p> {{ instance.get_markdown }} </p> </div> </div> </div> Here is my app => posts views.py: def post_detail(request, slug=None): instance = get_object_or_404(Post, slug=slug) if instance.publish > timezone.now().date() or instance.draft: if not request.user.is_staff or not request.user.is_superuser: raise Http404 share_string = quote_plus(instance.content) initial_data = { "content_type": instance.get_content_type, "object_id": instance.id } form = CommentForm(request.POST or None, initial=initial_data) if form.is_valid() and request.user.is_authenticated(): c_type = form.cleaned_data.get("content_type") content_type = ContentType.objects.get(model=c_type) obj_id = form.cleaned_data.get('object_id') content_data = form.cleaned_data.get("content") parent_obj = None try: parent_id = int(request.POST.get("parent_id")) except: parent_id = None if parent_id: parent_qs = Comment.objects.filter(id=parent_id) if parent_qs.exists() and parent_qs.count() == 1: parent_obj = parent_qs.first() new_comment, created = Comment.objects.get_or_create( user = request.user, content_type= content_type, object_id = obj_id, content = content_data, parent = … -
Postgis extension in postgres docker official image
I'm trying to dockerize old Django project that using Postgis. But all my tries to install it inside my database container - failed. This is how my docker compose looks like: services: django: &django build: context: . dockerfile: ./compose/local/django/Dockerfile image: app_api_local_django depends_on: - postgres volumes: - .:/app env_file: - ./.envs/.local/.django - ./.envs/.local/.postgres ports: - "8000:8000" command: /start postgres: image: postgres:9.5 build: context: . dockerfile: ./compose/local/postgres/Dockerfile image: app_api_local_postgres volumes: - postgres_data_local:/var/lib/postgresql/data - postgres_backup_local:/backups env_file: - ./.envs/.local/.postgres ./compose/local/postgres/Dockerfile file : FROM postgres:9.5 RUN apt-get update && apt-get -y install postgis And I also do the same in ./compose/local/django/Dockerfile FROM python:2.7-jessie RUN apt-get install -y \ postgresql \ postgresql-client \ postgis Build successfully, but when I perform migration i received error: django_1 | PostgreSQL is available postgres_1 | ERROR: could not open extension control file "/usr/share/postgresql/9.5/extension/postgis.control": No such file or directory postgres_1 | STATEMENT: CREATE EXTENSION IF NOT EXISTS postgis -
Django template if statement to echo parameters
I am learning Django and doing some assignments. One of them requires me to write a function echo(request), that will echo parameters and header. So that string http://127.0.0.1:8000/echo/?a=1 will return 'get a: 1 statement is empty'. Letter and value may change and it may be GET or POST. If there are no query string parameters it should return just 'statement is empty'. And if there is a custom HTTP header 'X-Print-Statement = test' it should return 'statement is test'. I figured out how to do some of it, but I am having problems with returning empty GET/POST requests http://127.0.0.1:8000/echo/ (I get an error) and returning correct response with HTTP header present. Please help. def echo(request): return render(request, 'echo.html', context={ 'get_letter': request.META['QUERY_STRING'][0], 'get_value': request.GET.get(request.META['QUERY_STRING'][0]), 'get_tag': request.META.get('HTTP_X_PRINT_STATEMENT'), 'request_method': request.META['REQUEST_METHOD'] }) <!--DOCTYPE html --> <html> <body> {% if 'QUERY_STRING' in request.META %} <h1> {{ request_method }} {{ get_letter }}: {{ get_value }} statement is empty </h1> {% elif 'HTTP_X_PRINT_STATEMENT' in request.META %} <h2> statement is {{get_tag}} </h2> {% endif %} </body> </html> -
Setting widget in Function Based View
Is it possible to initialize a form field and set a widget within a form declaration in a function based view? Eg. form = UserOrderForm(request.POST or None, user=user) If so, how would the syntax look? Thanks! -
How to create new columns in django user models
How to create new inputs in the django user models. The django user model comes with the standard username email and password, however I want users to have more details linked with their account, like let's say phone number or something. What would be the best way to do this? -
Setting widgets in non-model form
I'd like for some options within my widget to be based on values that I pull into the form from my def init() method within my form (forms.Form). So far, I can only see that you can set a widget when defining a field within a non-model form. eg. cars = forms.MultipleChoiceField(required=False, widget=forms.CheckboxSelectMultiple) Is there some way to set widgets on certain fields within the def init() method within my non-model form? Thanks!