Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
python-crontab IOError Read crontab ubuntu: must be privileged to use -u
I have a Ubuntu server with Apache and a django web app running. I am using python-crontab to create cronjob's based on selections by a user. This worked fine on my dev server :8000. However, when I moved it over to production I got this error: IOError: Read crontab ubuntu: must be privileged to use -u This is linked to this code: cron = CronTab(user=True) This is where the error is. I have tried with no user, with my root user, pretty much anything. Any advice on how to solve this would be greatly appreciated -
Got AttributeError when attempting to get a value for field `Name` on serializer `UserSerializer`
I got the following error: Got AttributeError when attempting to get a value for field Name on serializer UserSerializer. The serializer field might be named incorrectly and not match any attribute or key on the User instance. Original exception text was: 'User' object has no attribute 'Name'. Why do I get an error? Here is my code: views.py from .serializers import UserSerializer from rest_framework import viewsets, status from django.contrib.auth.models import User class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer serializers.py from django.contrib.auth.models import User from rest_framework import serializers from .models import Profile from rest_framework.authtoken.models import Token class UserSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ('id', 'Name', 'secondName', 'user', 'nickName', 'phoneNumber') """extra_kwargs = {'password': {'write_only': True, 'required': True}}""" def create(self, validated_data): user = User.objects.create_user(**validated_data) token = Token.objects.create(user=user) print('Loogg') return user models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver """Define Profile Fields""" class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, default=None) Name = models.CharField(max_length=32) secondName = models.CharField(max_length=32) nickName = models.CharField(max_length=32) phoneNumber = models.IntegerField(max_length=32) def __str__(self): return self.user.username class Meta: verbose_name = 'Profile' verbose_name_plural = 'profiles' urls.py from django.contrib import admin from django.urls import path from django.conf.urls import include from rest_framework import routers from .views … -
Compiling django files to pyc
I would to compile a python file in my django application, using: python --OO -m compileall *.py For example in app blog with structure: blog\ ... admin.py apps.py forms.py ... I want django to see __pycache__/admin.pyc as admin.py and so on. After compilation, I will delete all *.py files. Is there a way to linking some_file.pyc as to some_file.py for dajngo interpreter? -
enabling AVX2,AVx512 flags for tensorflow in server
Iam trying to load models that are trained in google colab in the backend of django website. the hosting service has no gpu support so i need to enable AVX2,AVX512 flags for cpu execution of tensorflow models.I gone through the process of enabling them .but every process includes installation of bazel .How is it possible for me to install bazel in the backend and execute it to set up my tensorflow with flags in hosting environment.here is my error with using tensorflow cpu. I tensorflow/core/platform/cpu_feature_guard.cc:142] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN)to use the following CPU instructions in performance-critical operations: AVX2 AVX512F FMA#012To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags. I wonder if there is command using pip that installs tensorflow with required flags AVX2.AVx512fetc.please help -
i am a newbie to django, and am getting error when am trying to the runserver
Traceback (most recent call last): File "c:\users\iam-korede\appdata\local\programs\python\python38-32\lib\runpy. py", line 194, in run_module_as_main return run_code(code, main_globals, None, File "c:\users\iam-korede\appdata\local\programs\python\python38-32\lib\runpy. py", line 87, in run_code exec(code, run_globals) File "C:\Users\iam-korede\AppData\Local\Programs\Python\Python38-32\Scripts\dj ango-admin.exe_main.py", line 7, in File "c:\users\iam-korede\appdata\local\programs\python\python38-32\lib\site-p ackages\django\core\management_init.py", line 401, in execute_from_command_l ine utility.execute() File "c:\users\iam-korede\appdata\local\programs\python\python38-32\lib\site-p ackages\django\core\management_init.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "c:\users\iam-korede\appdata\local\programs\python\python38-32\lib\site-p ackages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "c:\users\iam-korede\appdata\local\programs\python\python38-32\lib\site-p ackages\django\core\management\commands\runserver.py", line 61, in execute super().execute(*args, **options) File "c:\users\iam-korede\appdata\local\programs\python\python38-32\lib\site-p ackages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "c:\users\iam-korede\appdata\local\programs\python\python38-32\lib\site-p ackages\django\core\management\commands\runserver.py", line 68, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "c:\users\iam-korede\appdata\local\programs\python\python38-32\lib\site-p ackages\django\conf_init_.py", line 83, in getattr self.setup(name) File "c:\users\iam-korede\appdata\local\programs\python\python38-32\lib\site-p ackages\django\conf_init.py", line 64, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settin gs are not configured. You must either define the environment variable DJANGO_SE TTINGS_MODULE or call settings.configure() before accessing settings. -
Convert QueryDict to key-value pair dictionary
I have a QueryDict that I get from request.POST in this format: <QueryDict: {'name': ['John'], 'urls': ['google.com/\r\nbing.com/\r\naskjeeves.com/'], 'user_email': ['john.smith@gmail.com']}> Why are the values all in lists? I did dict(request.POST) I got {'name': ['John'], 'urls': ['google.com/\r\nbing.com/\r\naskjeeves.com/'], 'user_email': ['john.smith@gmail.com']} How can I get?: {'name': 'John', 'urls': 'google.com/\r\nbing.com/\r\naskjeeves.com/'`, 'user_email': 'john.smith@gmail.com'} -
When should I use a lazy function in Django
I am starting out with django and I have come across functions like reverse_lazy instead of reverse and gettext_lazy instead of gettext for translation. From the information, I could get online, it seems that these lazy functions only call the original functions when they are to be used and not immediately they are declared. What exactly does this mean and in what real life coding senerios should I use the lazy version as against the original function. Thanks a lot in advance -
Django drf-writable-nested not calling create method
I am using drf-writable-nested and overriding the create method of the serializer but it is not executing. I have tried the below code. Any help would be appreciated. models.py class Product(models.Model): name= models.CharField(max_length=500, unique=True, null=True) price = models.FloatField(null=True) description = models.CharField(max_length=100, null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, null=True) class ProductImage(models.Model): product = models.ForeignKey(Product, related_name="productImage", null=True,on_delete=models.SET_NULL) product_image = models.ImageField(max_length=255, null=True,blank=True) def __str__(self): return self.product_image.name serializers.py from rest_framework import serializers from drf_writable_nested.serializers import WritableNestedModelSerializer from API.serializers.productImageserializers import ProductImageSerializer class ProductsSerializer(WritableNestedModelSerializer): productImage = ProductImageSerializer(many=True) class Meta: model = Product fields = '__all__' def create(self, validated_data): image_data = validated_data.pop('productImage') product = Product.objects.create(**validated_data) for attached_file in image_data: ProductImage.objects.create(**attached_file) return product Api views.py @api_view(['GET','POST']) @permission_classes([IsAdminUser]) def products(request): productsserializer = ProductsSerializer(data=request.data) if productsserializer.is_valid(): productsserializer.save() return Response(productsserializer.data, status=status.HTTP_201_CREATED) return Response(productsserializer.errors, status=status.HTTP_400_BAD_REQUEST) I am submitting a post request to add the details. The request also contains image files. I want to create a new product which will have an images. I have installed the drf-writable-nested library which will do the nested writables without calling the create function. I have tried without using the create method and also later overriding the create method but it was showing the below error. { "productImage": [ "This field is required." ] } -
Form not passing is_valid() check when trying to use form data from another form
I have two forms in two separate models: Trainer and User. The Trainer form has one field called price_for_trainer that I need to pull into the User form. It's getting pulled in with the default value of 0 but I need the price for the trainer, like $5000, which would have been entered by the trainer. I'm using the prefix keyword (see code below) as described in this example: django: add form field to generated form from another table But when I debug my code trainer_form.is_valid() inside of if request.method == "POST": returns False, so my code block doesn't get executed. Also, when debugging I'm printing the form errors for Trainer and they say field is required. I should also mention that I'm using forms.ModelForms for both my Trainer and User. Here's what I've tried. I've tried using the prefix keyword in my User view (see code below) which pulls in the price_for_trainer field from the Trainer form but sets the field to the default value of 0 Here's my code: User views.py def user(request): if request.method == "POST": user_form = UserForm(request.POST, prefix="user") trainer_form = TrainerForm(request.POST, prefix="trainer") if user_form.is_valid() and trainer_form.is_valid(): user = user_form.save() trainer = trainer_form.save(commit=False) trainer.user=user trainer.save() return … -
Django admin actions based on custom conditions
I have a user model with fields like user_name, email and created_on. I tried the following code to export the user data into csv format Using the following code I am able to download the selected user data. Is it possible to download the user list on the basis of the time period by making use of this function ? def export_as_csv(self, request, queryset): meta = self.model._meta field_names = [field.name for field in meta.fields] response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename={}.csv'.format(meta) writer = csv.writer(response) writer.writerow(["first_name", "email", "created_on"]) for obj in queryset: row = writer.writerow([obj.first_name, obj.email, obj.created_on) return response class UserAdmin(admin.ModelAdmin): actions = [export_as_csv] list_display = ('created_on','email', 'first_name') -
Django filter local folders
I have a templatetag function that returns a Collapse menu with all folders, subfolders and images in a root directory but now I want to be able to filter which folders I get, the templatetag function recives one parameter, the root directory, and I know it should recibe a second parameter with the folder I want to get but I'm confused in this part. in my settings.py I have this: STATICFILES_DIRS = [ BASE_DIR / 'static', 'D:/Users/my_user/Documents/Luis/results', ] in my templatetag.py I have this: from django import template from django.utils.safestring import mark_safe import os register = template.Library() @register.simple_tag def my_tag(path): html='' for file in os.listdir(path): rel = os.path.join(path, file) if os.path.isdir(rel): html += f"""<button type="button" class="collapsible">{file}</button>""" html +='<div class="content"><div class="row mt-2">' html += my_tag(rel) html += '</div></div>' else: html +=f'<div class="col-md-6 d-flex align-items-stretch"><picture>' x=str(rel)[43:] print(x) html += """<img src="/static"""+"""/%s" """%(x) html += """ class="lazy card-img-top" width="500" height="400" """ html += """alt="/static"""+"""/%s" """%(x) html +='></picture></div>' return mark_safe(html) and in my template.html I have this: {% load static files %} <style> .collapsible { background-color: #F8F8F8; color: #858E9B; cursor: pointer; padding: 18px; width: 100%; border: none; text-align: left; outline: none; font-size: 15px; } /* .active, .collapsible:hover { background-color: #555; }*/ .content { padding: … -
Sqlite3 .database command in python
I am trying to view all the databases in sqlite3. It can be done through the command line with .database command. I want to do the same thing in Django and show the render the details in HTML. The following is the code I wrote in the views file: def analyzer(request): conn = sqlite3.connect("db.sqlite3") c = conn.cursor() c.execute("SHOW DATABASES") l = c.fetchall() print (l) return render(request, 'analyzer.html') -
Set initial object in ModelChoiceField of Django form in the FormView
I have a Django Model, ModelForm and a FormView. When the user enters the view it will get the current slug and use that slug to do a query of company objects. Then I want in my form to select the specific company in the form and select it automatically. Model: class Company(models.Model): """ Model for a Company. """ name = models.CharField(verbose_name=_('Company Name'), max_length=255) slug = models.SlugField(unique=True) ModelForm: class ApplicationForm(ModelForm): """ ModelForm for an Application """ class Meta: model = Application fields = '__all__' exclude = ['slug'] The form field is of type ModelChoiceField. This is my FormView: class ApplicationView(FormView): """ FormView that are displaying the ApplicationForm """ template_name = 'application.html' form_class = ApplicationForm success_url = '/' def get_form(self, *args, **kwargs): form = super().get_form(*args, **kwargs) slug = self.kwargs['slug'] company = Company.objects.get(slug=slug) form.fields['company'].initial = company return form But this code above does not work to select the object of the current company. It only shows me "--------". Why and how can it be solved? -
/.platform/hooks/': No such file or directory when deploying Django App to AWS Elastic Beanstalk
I am trying to deploy a Django app to AWS ElasticBeanStalk. I followed all the guides in the marked correct answer but I still get the below error: [INFO] -----------------------Command Output----------------------- [INFO] find: '/.platform/hooks/': No such file or directory [INFO] ------------------------------------------------------------ As I used windows OS, I created my .sh file from https://cocalc.com/ online console. I also zipped the files and used the EBS console to deploy to avoid my files being converted during git add/commit. My config file in .ebextension content is: container_commands: 01_sh_executable: command: "chmod +x .platform/hooks/predeploy/01_execute.sh" My 01_execute.sh file content is: #!/bin/bash source /var/app/venv/*/bin/activate cd /var/app/staging python manage.py makemigrations python manage.py migrate python manage.py createsu python manage.py collectstatic --noinp The platform chosen is Python 3.7 running on 64bit Amazon Linux 2. I also noticed that when I run eb ssh and type ls, it returns blank. Linux is not one of my strength. Any help will be highly appreciated. -
Can anyone help to explain difference between django middleware and wsgi middleware
Can anyone help to explain difference between django middleware and wsgi middleware? Many thanks! -
Modified django.contrib.auth.middleware.AuthenticationMiddleware
Modify Get_User so that it does not generate an error when there is a request without a token then I need that it does not generate me the error of token if not that it takes me to the sight which already parameterized him those permissions. def get_user(request): """ Return the user model instance associated with the given request session. If no user is retrieved, return an instance of `AnonymousUser`. """ from .models import AnonymousUser user = None try: user_id = _get_user_session_key(request) backend_path = request.session[BACKEND_SESSION_KEY] except KeyError: pass else: if backend_path in settings.AUTHENTICATION_BACKENDS: backend = load_backend(backend_path) user = backend.get_user(user_id) # Verify the session if hasattr(user, 'get_session_auth_hash'): session_hash = request.session.get(HASH_SESSION_KEY) session_hash_verified = session_hash and constant_time_compare( session_hash, user.get_session_auth_hash() ) if not session_hash_verified: if not ( session_hash and hasattr(user, '_legacy_get_session_auth_hash') and constant_time_compare(session_hash, user._legacy_get_session_auth_hash()) ): request.session.flush() user = None return user or AnonymousUser() -
(Wagtail) Field defines a relation with model 'wagtailimages.Images', which is either not installed, or is abstract
I'm having an issue with Wagtail/Django. I have the file app/models/abstract_card_snippet.py which contains: from django.db import models from wagtail.admin.edit_handlers import FieldPanel from wagtail.documents.edit_handlers import DocumentChooserPanel # Abstract Card Snippet class AbstractCardSnippet(models.Model): title = models.CharField(max_length=255) text = models.CharField(max_length=255, null=True, blank=True) url = models.URLField(max_length=255, null=True, blank=True,) image = models.ForeignKey( 'wagtailimages.Images', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) panels = [ FieldPanel('title'), FieldPanel('text'), FieldPanel('url'), ImageChooserPanel('image'), ] def __str__(self): return '{}'.format(self.title) class Meta: abstract = True Then in app/models/generic_card_snippet.py is: from wagtail.snippets.models import register_snippet from .abstract_card_snippet import AbstractCardSnippet @register_snippet class GenericCard(AbstractCardSnippet): pass But when I run the project or try to make migrations this error comes up: web_1 | Exception in thread django-main-thread: web_1 | Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.6/threading.py", line 916, in _bootstrap_inner web_1 | self.run() web_1 | File "/usr/local/lib/python3.6/threading.py", line 864, in run web_1 | self._target(*self._args, **self._kwargs) web_1 | File "/usr/local/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper web_1 | fn(*args, **kwargs) web_1 | File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run web_1 | self.check(display_num_errors=True) web_1 | File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 436, in check web_1 | raise SystemCheckError(msg) web_1 | django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: web_1 | web_1 | ERRORS: web_1 | app_snippets.GenericCard.image: (fields.E300) Field defines a relation with model 'wagtailimages.Images', which is either … -
Website Peer to Peer Chat API Recommendations
TL;DR I need to create a platform where people can message each other on a website, what API's are there that can do this easily? From my research so far, I have come across TalkJS, but this seems to be very expensive ($249 per month) are there any other tools that will allow me to easily implement peer to peer chat on my website that are cheaper or preferably free? My website is currently written using Django (Python) TalkJs: https://talkjs.com/ -
I cannot implement DJANGO REST API with REACT
I want to integrate React with Django REST API for my ecom website but for some reason that does not work. I really do not know what I missed. Any input is welcomed. Please see the code below. REACT Home.js (this is the code for products) const loadAllProducts = () => { getProducts() .then((data) => { if(data.error) { setError(data.error); //box filled with data error console.log(error); // message "error" } else { setProducts(data); // box filled with data product } }); loadAllProducts(); }; coreapicalls.js (here I want to fetch the data) import { API } from "../../backend.js"; export const getProducts = () => { return fetch(`${API}product`, { method: "GET" }) .then(response => response.json()) .catch((err) => console.log(err)); }; .env (I have both of my servers running, the url and symbol "/" are correct.) REACT_APP_BACKEND = http://localhost:8000/api/ My compiler returns no specific error. ./src/core/Home.js Line 16:11: 'loadAllProducts' is assigned a value but never used no-unused-vars ./src/core/Card.js Line 26:11: 'getAredirect' is assigned a value but never used no-unused-vars DJANGO (settings.py, Django does give me JSON data on the localhost:8000/api/product/) 'api', 'api.category', 'api.product', Best, Rok. -
Page not found error when trying to load template from Link in mail
Hi All i've implemented sendgrid mail for my newsletter app in django, in which mail is send to user for confirming the subscription, but when i'm trying to click on link mail, it's throwing me error 404. I know that it's not able to find the url but what i'm not getting is how to create url for this. Adding code for ref: HTML: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1 align="center">You have subscribed for Newsletter</h1> <p>Thank you for signing up for my email newsletter! Please complete the process by \ <a href="{{ redirect_url }} ?conf='{{ conf }}'"> clicking here to \ confirm your registration</a></p> </body> </html> views.py: def home(request): # Rendering Home page and Handling of Newsletter if request.method == 'POST': subscriber_mail = request.POST['email'] conf_num = random_digits() # checking if subscriber already exist check_subscriber = Subscribers.objects.filter(subscriber_mail=subscriber_mail) if not check_subscriber: sub = Subscribers(subscriber_mail=request.POST['email'], conf_num=random_digits()) sub.save() redirect_url = request.build_absolute_uri('/confirm/') message = Mail( from_email=settings.FROM_EMAIL, to_emails=sub.subscriber_mail, subject='Newsletter Confirmation', html_content= get_template('frontend/newsletter_subscribed.html').render({ 'redirect_url': redirect_url, 'conf': sub.conf_num})) sg = SendGridAPIClient(settings.SENDGRID_API_KEY) response = sg.send(message) return render(request, 'frontend/index.html', {'email': sub.subscriber_mail, 'action': 'added', 'form': SubscriberForm()}) else: return render(request, 'frontend/index.html', {'form': SubscriberForm(), 'messages':'You are already subscribed for newsletter.'}) else: return render(request, 'frontend/index.html', … -
Deploying django blog with heroku
I just finished writing a blog app with django which works perfectly locally but on deploying, I'm getting this error ProgrammingError at / relation "posts_post" does not exist LINE 1: ...evious_post_id", "posts_post"."next_post_id" FROM "posts_pos... Please what can I do to resolve this? -
Error while importing data with foreign keys in django import-export
I have implemented importing data using django import-export library. When i try to import data with names of object that do not exists it throws error matching query does not exist. It ends with generating template with error stack trace like this: Line number: 1 - CustomUser matching query does not exist. sample@sample.com, data1, firstname, secondname Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/import_export/resources.py", line 520, in import_row self.import_obj(instance, row, dry_run) File "/usr/local/lib/python3.7/site-packages/import_export/resources.py", line 385, in import_obj self.import_field(field, obj, data) File "/usr/local/lib/python3.7/site-packages/import_export/resources.py", line 368, in import_field field.save(obj, data, is_m2m) File "/usr/local/lib/python3.7/site-packages/import_export/fields.py", line 110, in save cleaned = self.clean(data) File "/usr/local/lib/python3.7/site-packages/import_export/fields.py", line 66, in clean value = self.widget.clean(value, row=data) File "/usr/local/lib/python3.7/site-packages/import_export/widgets.py", line 364, in clean return self.get_queryset(value, row, *args, **kwargs).get(**{self.field: val}) File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 408, in get self.model._meta.object_name accounts.models.CustomUser.DoesNotExist: CustomUser matching query does not exist. Custom resouce import class: class UserResourceImport(resources.ModelResource): """ Resource class for import utilities """ # set foreign key relations for model, this way we can provide name instead of id custom_user = fields.Field(column_name='year_group', attribute='year_group', widget=ForeignKeyWidget(CustomUser, 'name')) class Meta: model = user_model fields = ('email','custom_user','first_name','last_name') skip_unchanged = False report_skipped = True export_order = ('email', 'custom_user', 'first_name', 'last_name') import_id_fields = ['email'] Every other error of importing will result in generation … -
Javascript variables use in Django Models
I have created a sign up with google authentication system in which I'm getting info of user by a javascript variable . I want to create a django model in which the fields should use the info from javascript function. Here is code of javascript function : function onSignIn(googleUser) { console.log("success"); var profile = googleUser.getBasicProfile(); console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead. console.log('Name: ' + profile.getName()); console.log('Image URL: ' + profile.getImageUrl()); console.log('Email: ' + profile.getEmail()); // This is null if the 'email' scope is not present. location.replace("http://localhost:8000/faculty"); } -
How to fetch cert data (certificate file location) from request object in Django?
How can i fetch data of verify and cert paramater from request object. I have made a request to a url where my django backend deployed url = "https://www.example.com/" cert = "PathToPemFile" verify = "PathToCertFile" I made a request req = request.post(url, post_data, headers=header_dict, cert=cert, verify=verify) Now At Backend of www.example.com Class CertificateView(APIVIEW): def post(self, request, *args, **kwargs): get_cert_location = request.cert AttributeError: request object does not have an attribute cert How can i get the data of cert and verify in my post function from request object. -
How to properly add multi choice field to existing form in Django?
just like in title. This is what I currently have. I've tried django-multiselectfield but I had many issues with my foreignkey and ManyToMany usage in models. Maybe I should just use a JavaScript or something? I'm a newbie to Django and I really don't know which way to take. MODELS class Category(models.Model): name = models.CharField(max_length=50, unique=True) def __str__(self): return f'{self.name}' class Expense(models.Model): class Meta: ordering = ('date', '-pk') category = models.ForeignKey(Category, null=True,blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=50) amount = models.DecimalField(max_digits=8,decimal_places=2) date = models.DateField(default=datetime.date.today,db_index=True) def __str__(self): return f'{self.date} {self.name} {self.amount}' FORMS class ExpenseSearchForm(forms.ModelForm): GROUPING_CHOICES = ('date', 'category asc', 'category desc') grouping = forms.ChoiceField(choices=[('', '')] + list(zip(GROUPING_CHOICES, GROUPING_CHOICES))) SORTING_CHOICES = ('date asc', 'date desc' ) sorting = forms.ChoiceField(choices=[('', '')] + list(zip(SORTING_CHOICES, SORTING_CHOICES))) class Meta: model = Expense fields = ('name','category') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for i in self.fields: self.fields[i].required = False