Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to render my data from dictionary using django_tables2
To my django_table2 I pass a dictiorary and not a queryset as usual views object_list = Warehouse_Order_Reserve.objects.values('wholesale_product__description','wholesale_product__code','wholesale_product_id' ).annotate(quantity=Sum('quantity')) When I am trying to render my data to my table I am facing with the problem that only the field of warehouse_product_id is rendered properly and not the fields of description and code tables class ReserveTable(tables.Table): wholesale_product_name = tables.Column(accessor='wholesale_product_description',verbose_name= 'Product') wholesale_product_code = tables.Column(accessor='wholesale_product_code',verbose_name= 'Sku') wholesale_product_id = tables.Column(accessor='wholesale_product_id',verbose_name= 'ID') details=tables.LinkColumn('reserve_details_list',args=[A('wholesale_product_id')],accessor='Backorder Details',orderable=False,empty_values=(),verbose_name = 'Λεπτομέρειες δέσμευσης') class Meta: #define the model model = Warehouse_Order_Reserve template_name = 'django_tables2/bootstrap4.html' exclude = ('id','date',"warehouse","woo_order",'wholesale_product') sequence = ('wholesale_product_name','wholesale_product_code', 'wholesale_product_id',"quantity",'details') def render_wholesale_product_name(self,record): return '%s' % (record['wholesale_product_description']) def render_wholesale_product_code(self,record): return '%s' % (record['wholesale_product_code']) def render_wholesale_product_id(self,record): return '%s' % (record['wholesale_product_id']) def render_details(self,record): return format_html('<a href="/reserve_details/{}/"><button class="btn btn-primary btn-sm" type="">Details</button></a>',record['wholesale_product_id']) model class Warehouse_Order_Reserve(models.Model): woo_order = models.ForeignKey(Woo_Orders,verbose_name="Order",null=True,on_delete=models.CASCADE) wholesale_product=models.ForeignKey(Product,null=True,on_delete=models.CASCADE) warehouse=models.ForeignKey(Warehouse,verbose_name=u'Warehouse',blank=True, null=True,on_delete=models.CASCADE) quantity = models.DecimalField("Quantity", max_digits=7, decimal_places=2, default=0) date = models.DateTimeField("Date",null=True, blank=True, default=datetime.datetime.now) Is this has to do with accessor? Usually when we pass to the table a queryset we return the value as below def render_wholesale_product_name(self,record): return '%s' % (record.wholesale_product.description) but in my case this does not work. How can i render my data? -
How to keep record of stages after edit/update of a form just to see the list and detail view of what it was previously?
So I have a model registered in admin site. I filled up the model-form and save it. Then, edit the form and save it again. Now is it possible to see the previous data as records in front end?? i surfed through django simple history. I wanted to confirm , will it work? -
Trasform a complex SQL query into Django ORM language
In my postgreSQL database i have this SQL query: SELECT FT."Riferimento1", FT."Riferimento2", "CodProdotto", "QuantitaFatturata", "PrezzoUnit", "DataFattura", "NumeroFattura", "CodCli" FROM public.idocuments_as_fatturetestata FT LEFT JOIN public.idocuments_as_fatturerighe FR ON FT."Riferimento1" = FR."Riferimento1" AND FT."Riferimento2" = FR."Riferimento2" WHERE FT."CodCli" = '12192' AND ("DataFattura" >= '2017-01-31' AND "DataFattura" <= '2018-12-21'); all works done, but i have to implement in my django project using ORM for have results but i have n idea how to achieve this results. Someone have an idea about? So many thanks in advance -
How to install sudo and nano command in MySql docker image
I am trying to connect Django application with MySql docker container. I am using the latest version of MySql i.e MySql 8.0 to build a container. I was able to build the MySql container successfully but I am not able to connect it using Django's default MySql Connector. When I run the docker-compose up command I get the error mentioned below. django.db.utils.OperationalError: (1045, 'Plugin caching_sha2_password could not be loaded: /usr/lib/x86_64-linux-gnu/mariadb19/plugin/caching_sha2_password.so: cannot open shared object file: No such file or directory') I started looking for the solution and got to know that MySql has released a major change in its default authentication plugin which is not support by most of the MySql Connectors. To fix this issue I will have to set the default-authentication-plugin to mysql_native_password in my.cnf file of MySql container. I logged into container using command docker exec -it <conatiner id> /bin/bash and was also able to locate the my.cnf file inside the container. To edit the my.cnf file I will have to use the nano command as stated below. nano my.cnf But unfortunately nano command is not installed in MySql Container. To install nano I will need sudo installed in container. I tried installing sudo using below mentioned … -
django make table with context
I want make table like this excel in django listview My Study model class Study(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE) teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE) time = models.TimeField(choices=time_choices) duration = models.DurationField(default=datetime.timedelta(minutes=20)) class Meta: abstract = True class Regular(Study): start_on = models.DateField(default=datetime.date.today) days_of_week = models.CharField(max_length=10, choices=day_of_week) def __str__(self): return '{} - on {} {}'.format(self.student, self.days_of_week, self.time) class Meta: ordering = ['days_of_week','time'] but I don't have any idea about making table. class ScheduleLV(ListView): template_name = 'students/study_list.html' context_object_name = 'study_list' # def get_queryset(self): # return Regular.objects.all() queryset = Regular.objects.all().order_by('time', 'days_of_week') def get_context_data(self, **kwargs): context = super(ScheduleLV, self).get_context_data(**kwargs) context['temp'] = Temporary.objects.filter( temp_date__week=datetime.date.today().isocalendar()[1]) return context I send context this format What can I do.... please help me. -
Django LiveServerTestCase - Unable to force_login in multiple tests
Versions Django version: 1.9 Python: 3.5 Django Rest Framework: 3.5.4 Error Observed: Error Traceback (most recent call last): File "/Users/ds/git/some_repo/integration/test_multiple_login.py", line 32, in test_two self.client.force_login(self.user) File "/Users/ds/.pyenv/versions/3.5.7/envs/work_env/lib/python3.5/site-packages/django/test/client.py", line 608, in force_login self._login(user) File "/Users/ds/.pyenv/versions/3.5.7/envs/work_env/lib/python3.5/site-packages/django/test/client.py", line 621, in _login login(request, user) File "/Users/ds/.pyenv/versions/3.5.7/envs/work_env/lib/python3.5/site-packages/django/contrib/auth/__init__.py", line 117, in login user_logged_in.send(sender=user.__class__, request=request, user=user) File "/Users/ds/.pyenv/versions/3.5.7/envs/work_env/lib/python3.5/site-packages/django/dispatch/dispatcher.py", line 192, in send response = receiver(signal=self, sender=sender, **named) File "/Users/ds/.pyenv/versions/3.5.7/envs/work_env/lib/python3.5/site-packages/django/contrib/auth/models.py", line 23, in update_last_login user.save(update_fields=['last_login']) File "/Users/ds/.pyenv/versions/3.5.7/envs/work_env/lib/python3.5/site-packages/django/contrib/auth/base_user.py", line 74, in save super(AbstractBaseUser, self).save(*args, **kwargs) File "/Users/ds/.pyenv/versions/3.5.7/envs/work_env/lib/python3.5/site-packages/django/db/models/base.py", line 708, in save force_update=force_update, update_fields=update_fields) File "/Users/ds/.pyenv/versions/3.5.7/envs/work_env/lib/python3.5/site-packages/django/db/models/base.py", line 736, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/Users/ds/.pyenv/versions/3.5.7/envs/work_env/lib/python3.5/site-packages/django/db/models/base.py", line 805, in _save_table raise DatabaseError("Save with update_fields did not affect any rows.") django.db.utils.DatabaseError: Save with update_fields did not affect any rows. Sample Code to reproduce this: from django.test import TestCase, LiveServerTestCase from paths.factories import UserFactory class ATestClass(LiveServerTestCase): @classmethod def setUpClass(cls): """ Test Data common across all tests """ super().setUpClass() cls.user = UserFactory(is_staff=False, is_superuser=False) def test_one(self): """ Login and then do some actions """ self.client.force_login(self.user) # do something self.assertTrue(True) def test_two(self): """ Login and do some actions """ self.client.force_login(self.user) # do something self.assertFalse(False) What worked? If I replace LiveServerTestCase with TestCase it works as expected. However, since I need access … -
Cannot use my MySQL Database with Django - ValueError after running migrate command
I'm working with Django 3.0 and after playing a bit with this framework, I would like to connect it to my big MySQL Database. My goal is to be able to set up the Admin Django Dashboard with my all my data from my MySQL Database. So far, after seeing some tutorials, this is what I've done : Settings.py DATABASES = { 'default': { 'ENGINE': "django.db.backends.mysql", 'NAME': "nameDB", 'USER': "root", 'PASSWORD': "mypassword", 'HOST': "myHost", 'PORT': "", 'OPTIONS': { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'" } } } My App (let's say dashboard) is installed on my INSTALLED_APPS. Then, I did : python manage.py inspectdb > models.py It generate well the models.py. So I moved the models.py to my Dashboard app folder. After that, I wanted to migrate my DB using this following command line : python manage.py migrate At this step, there are some errors that I'm not able to solve. Errors Traceback (most recent call last): File ".\manage.py", line 21, in <module> main() File ".\manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\nameUser\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\nameUser\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Users\nameUser\Anaconda3\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\nameUser\Anaconda3\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() (base) PS C:\xampp\htdocs\django-test\app> python … -
Error Loading Project: Cannot load facet Django in Pycharm community version, but no error in professional version
I start learning Django, building a simple project with Pycharm community version first, in the middle of development, I switch to professional version. after the trail version expired, I move back to community version. Now when I am using community version, the Pycharm shows event error: "Error Loading Project: Cannot load facet Django". I try professional version, it's shows successfully load. Can anybody help? -
How to update Foreign key field using nested serializer in django
I am facing one issue for updating models using django serializer. Here is my models: class User(models.Model): email = models.EmailField(unique=True) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) class UserProfile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) designation = models.CharField(max_length=200, blank=True) contact_number = models.CharField(max_length=20, blank=True) team = models.CharField(max_length=200, blank=True) manager = models.CharField(max_length=200, blank=True) joining_date = models.DateField(default=datetime.now) I need to create a serializer for editing profile details of the current user This is my serializer. class UserSerializer(ModelSerializer): class Meta: model = User fields = ('id', 'first_name','last_name') class UserProfileSerializer(ModelSerializer): user = UserSerializer( required = False) class Meta: model = UserProfile fields = ('id', 'designation', 'contact_number', 'team', 'manager', 'joining_date','user') def update(self, instance, validated_data): user = validated_data.get('user') instance.user.first_name = user.get('first_name') instance.user.last_name = user.get('last_name') instance.user.save() Currently I am getting an Error 'NoneType' object has no attribute 'get' If I change this user = UserSerializer( required = False) to user = UserSerializer() I am getting an error { "user": [ "This field is required." ] } -
how to display the student name using their foreignkey
I have this code in my views.py me = StudentsCoreValuesDescription.objects.filter(grading_Period = coreperiod)\ .values('Marking','Students_Enrollment_Records__Students_Enrollment_Records__Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Firstname')\ .distinct('Students_Enrollment_Records__Students_Enrollment_Records__Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Firstname').order_by('Students_Enrollment_Records__Students_Enrollment_Records__Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Firstname') when i tried to display it into my html {% for students in me %} <tr> <td colspan="2"><input type="hidden" value="{{students.id}}" name="student">{{students.Students_Enrollment_Records.Students_Enrollment_Records.Students_Enrollment_Records.Students_Enrollment_Records.Students_Enrollment_Records.Student_Users.Firstname}}</td> </tr> {% endfor %} nothing display into my site, and when i tried to print the print(me) the result is -
dDjango Tempalte TemplateSyntaxError
I want to add CSS and Js file path into header and footer for load CSS and js files for web template but I'm getting this error. I load {% load static %} TemplateSyntaxError at / Could not parse the remainder: '/css/bootstrap.min.css' from 'front/css/bootstrap.min.css' Request Method: GET Django Version: 3.0.2 Exception Type: TemplateSyntaxError <link rel="stylesheet" type="text/css" href="{% static front/css/bootstrap.min.css %}"> <link rel="stylesheet" type="text/css" href="{% static front/css/font-awesome.css %}"> <link rel="stylesheet" type="text/css" href="{% static front/js/plugins/swiper/swiper.css %}"> <link rel="stylesheet" type="text/css" href="{% static front/js/plugins/magnific/magnific-popup.css %}"> <link rel="stylesheet" type="text/css" href="{% static front/css/style.css %}"> -
I want to develop tour and travel manaement system with content based filtering algorithm
I want to develop tour and travel manaement system with content based filtering algorithm can anyone help me for starting the project. I m new in django and i have to complete my final year project. -
Table schema name doesn;'t match to the data model class name in Django
Can anyone please advise, why is that the schema names in the Prosgre DB and model class names don't match? For example, my data model class name is 'User'.But, what exactly showing in my database is user_user. May I know what is that happened? -
django: creating a new model from existing model and displaying it in admin
My existing django project has admin.py as from django.contrib import admin from .models import ScholarProfile admin.site.register(ScholarProfile) and models.py as class ScholarProfile(models.Model): author_name= models.CharField(max_length=100) profile_url= models.URLField(max_length=200, primary_key= True) Company= models.CharField(max_length=100, null=True) Website= models.CharField(max_length=100, null=True) publication_title= ArrayField(models.CharField(max_length=500)) normalized_citations= ArrayField(models.CharField(max_length=50), null= True) citations= ArrayField(models.CharField(max_length=50), null= True) coAuthors= ArrayField(models.CharField(max_length=50), null= True) created_at= models.DateTimeField(auto_now_add= True) country= models.CharField(max_length=100, null= True) publications= models.CharField(max_length=100, null= True) Tcitations= models.CharField(max_length=100, null= True) Hindex= models.CharField(max_length=100, null= True) Gindex= models.CharField(max_length=100, null= True) Mindex= models.CharField(max_length=100, null= True) Oindex= models.CharField(max_length=100, null= True) Eindex= models.CharField(max_length=100, null= True) Hmedian= models.CharField(max_length=100, null= True) TNCc= models.CharField(max_length=100, default= '00', ) Year= ArrayField(models.CharField(max_length=100), null=True) def __str__(self): return (self.author_name) All the above data is related to author_name .I am having trouble figuring out how to create a different model with only publication_title, citations and co-authors and relate them to the author_name (preferably by foreign key), so that I can display the model in my admin ? -
Download videos from server to users machine as response in django
I have lunched a small any video downloader with written in django and youtubedl. Whenever user tries to download video it gets downloaded inside server in a folder /home/SERVER_USER_NAME/Downloads.Now how do i tell browser to download that video to users local machine?I have written a method serve_file() but its not working. #!/usr/bin/env python3 from __future__ import unicode_literals from django.shortcuts import render, redirect from .forms import AnyVideoDownloadForm import youtube_dl import os from django.contrib import messages from mimetypes import MimeTypes from urllib.request import pathname2url from django.http import HttpResponse URL_LIST = '' # Create your views here. def home(request): global URL_LIST if request.method == 'POST': form = AnyVideoDownloadForm(request.POST) if form.is_valid(): URL_LIST = form.cleaned_data['url'] return redirect('anydownload') else: form = AnyVideoDownloadForm() return render(request, 'anyvideo/home.html', {'form': form}) def serve_file(): file_path = '/home/SERVER_USER_NAME/Downloads/video.mp4' filename = os.path.basename(file_path) mime = MimeTypes() url = pathname2url(file_path) mimetype, encoding = mime.guess_type(url) f = open(file_path, 'rb') response = HttpResponse(f.read(), content_type=mimetype) response['Content-Length'] = os.path.getsize(file_path) response['Content-Disposition'] = \ "attachment; filename=\"%s\"; filename*=utf-8''%s" % \ (filename, filename) f.close() return response def anydownload(request): if request.method == 'GET': ydl_opts = { # 'logger': MyLogger(), 'quiet': True, 'skip_download': True, 'match_filter': youtube_dl.utils.match_filter_func("!is_live"), } with youtube_dl.YoutubeDL(ydl_opts) as ydl: meta = ydl.extract_info(URL_LIST, download=False) context = { 'title': (f"{meta['title']}"), 'uploader': (f"{meta['uploader']}"), } return render(request, … -
ValueError: The view restapiapp.views.post didn't return an HttpResponse object. It returned None instead
@csrf_exempt def post(request): if request.method == 'POST' and request.user.id: record = Record.objects.create(title=title, author=author, description=description, image=image, user_id=user) file_serializer = RecordSerializer(data=request.data) serializer.is_valid() serializer.errors if file_serializer.is_valid(): file_serializer.save() return HttpResponse(file_serializer.data, status=status.HTTP_201_CREATED) else: return HttpResponse(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) ValueError: The view restapiapp.views.post didn't return an HttpResponse object. It returned None instead. -
how to add to django admin list_editable a reverse relation Field
These are my simple models. class Customer(models.Model): name = models.CharField(max_length=50) email = models.EmailField(null=True, blank=True, unique=True) phone = models.CharField(max_length=30, null=True, blank=True) def __str__(self): return self.name class Box(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='box') box_status = models.CharField(max_length=20) these are my model admin classes. from django.contrib import admin from .models import Customer, Box @admin.register(Customer) class CustomerAdmin(admin.ModelAdmin): list_display = ['name', 'email', 'phone', 'box_status'] list_editable = ['phone', 'box_status'] def box_status(self, obj): det = list(obj.box.values_list('box_status', flat=True)) return det @admin.register(Box) class BoxAdmin(admin.ModelAdmin): pass Now box_status from related model can work list_display but not working in list_editable. the error is <class 'django.forms.widgets.admin_class'>: (admin.E121) The value of 'list_editable[1]' refers to 'box_status', which is not an attribute of 'newapp.Customer'. -
Insert Data into other model in django
I have 2 models: (Invoice and Summary) class Invoice(models.Model): inv_id = models.IntegerField() order_id = models.IntegerField() unit_price = models.IntegerField() num_units = models.IntegerField() def __str__(self): return str(self.inv_id) class Summary(models.Model): invo_id = models.ForeignKey(Invoice, on_delete=models.CASCADE) sum = models.IntegerField() I need to insert data in Summary table from url and also compute "sum" by using Invoice Table. I tried: inv_id = request.GET.get('inv_id').split(',') for i in inv_id: # summary = Invoice.objects.filter(id=i).annotate(result=F('unit_price') * F('num_units')).aggregate(Sum('result'))['result__sum'] summary = Invoice.objects.raw('''select id as id,sum(unit_price * num_units) as sum from restapi_invoice where inv_id = {}'''.format(i)) x = Invoice.objects.get(pk=summary[0]) # Summary.objects.update_or_create(invo_id_id=x, defaults={"sum": summary[1]}) p = Summary(sum=summary[1]) p.save() p.invo_id.add(x) it's not working. How can I insert id from url and also compute sum of that id and store in Summary table ? -
Add or change a related_name argument to the definition Error
I'm have a model called TimeStampwithCreator class TimeStampWithCreator(TimeStamp): class Meta: abstract = True created_by = models.ForeignKey( settings.AUTH_USER_MODEL, verbose_name=_("Created By"), editable=False, blank=True, null=True, related_name='created_by', on_delete=models.SET_NULL) updated_by = models.ForeignKey( settings.AUTH_USER_MODEL, verbose_name=_("Updated By"), editable=True, blank=True, null=True, related_name='updated_by', on_delete=models.SET_NULL) def save(self, *args, **kwargs): if not self.created_by: self.created_by = get_current_user() self.updated_by = get_current_user() super(TimeStampWithCreator, self).save(*args, **kwargs) save.alters_data = True And this model is inherit from TimeStampModel Now I want to create two model using TimeStampWithCreator, Every things is working fine with one model like this class Province(TimeStampWithCreator): name = models.CharField( unique=True, max_length=255, help_text="Eg:- Province 7", ) class Meta: db_table = 'province' verbose_name = 'Province' verbose_name_plural = 'Provinces' def __str__(self): return self.name upto here it is working fine but when i create anther model, class District(TimeStampWithCreator): province = models.ForeignKey(Province, on_delete=models.CASCADE, related_name='province_name') name = models.CharField( max_length=255, ) class Meta: db_table = 'districts' verbose_name = 'District' verbose_name_plural = 'Districts' def __str__(self): return self.name But here I'm facing error i didn't know whats going wrong -
dynamic report generation based on user selection django
I have a 3 tier application (Front end angular, backend django and mssql) i have come across bit of a situation now where we have to build the reports based on users selection. we have multiple table's and columns, and stored procedures to get required output. for example, in report we have name place dob rank branch subject and many more. so user selects required feilds, not all, he might select only name and dob.or more. and we are taking it from different tables multiple stored procedures for those query. How do we fetch the user requested data from database and pass it to frontend through django -
Email send django returning error when details comes from database
I have A FUNCTION TO SEND MAIL IN django helper file my function is givenm below def mail_send(data): result = {} getTemplate = EmailTemplate.objects.filter(pk=data['type']).first() if getTemplate != None: templates = Template(getTemplate.template) config = EmailConfiguration.objects.filter(pk=1).first() context = Context( { 'name': data['name'], 'password': data['password'], 'site_name': config.site_name } ) msg_plain = 'Login Details ' + data['name'] + ' / ' + data['password'] msg_html = templates.render(context) EMAIL_USE_TLS = config.tls EMAIL_HOST = config.host EMAIL_HOST_USER = config.from_email EMAIL_HOST_PASSWORD = config.password EMAIL_PORT = config.port mail = send_mail( data['msg'], msg_plain, EMAIL_HOST_USER, [data['email']], fail_silently=False, html_message=msg_html, ) else: result['msg'] = 'Template Not Found .Unable to send Email..' result['status'] = False its returning me the error like : [Errno 111] Connection refused but when i put all this setting in settings.py its working fine with me but i dont want this i want to come from database and send a mail please suggest me i am stuck here from last day .i am newbe in django so its getting verry difficult to me -
how to know all django reverse lookups pointing to a model
I have a model A, and several models (B, C and D), all of them with a foreign field pointing to A. I want to implement a method to collect all records in B, C, and D related to each record in A, through the reverse look ups set in foreign keys in B, C and D. The problem is that the amount of models with a foreign key pointing to A can change, so I want to make the method dynamic, so I need to know the models and their fields pointing at A, and their related_name. Is there a way to obtain this information? -
Is there any way to query UUID in graphQL-ariadne
I am new to GraphQL and I am using ariadne. Sorry if this sounds dubious but is it possible to create a type UUID in ariadne and query the same. If so, then how. Also how do I create a custom type in ariadne. -
django - database - migrating from sqlite3 to postgresql on server and local
Two databases were setup for my django app on server (Ubuntu 18.04), sqlite is for development, PostgreSQL is for production. It is probably a stupid idea in the first place: because of an environment variable error, sqlite was still being used in production and user has been uploading data (files and pictures) for a while. I now need to change the database to PostgreSQL on the server without losing the data. I found some solutions on google but none is suitable, I'm trying to get as much help as I can. Thanks guys! -
Problem setting initial Django ModelForm field value
I’m trying to set the default value in the form (the field is the date for publishing the article “public”), but when loading the form on the page, the field is empty. I tried to set the default value in the "header" field (any value, not necessarily today's date) - also does not appear. form: from main.models import Article from datetime import datetime class AddArticleForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(AddArticleForm, self).__init__(*args, **kwargs) self.fields['publish'].initial = datetime.now() class Meta: model = Article fields = ('title', 'author', 'body', 'publish', 'status') labels = { 'body': 'Text' } widgets = { 'title': forms.TextInput(attrs={'class': 'md-form'}), 'author': forms.TextInput(attrs={'class': 'md-form'}), 'body': forms.Textarea(attrs={'class': 'md-textarea', 'rows': 3}), 'publish': forms.DateTimeInput(attrs={'class': 'md-form'}), 'status': forms.Select(attrs={'class': 'custom-select'}) } views: def add_article(request): form = AddArticleForm(request.POST) if form.is_valid(): form.save() return redirect('/articles/') args = { 'form': form } return render(request, 'html/add_article.html', args) html: ... <form action="." method="post" class="add-article"> {% csrf_token %} {% for field in form %} <div class="md-form"> {% if field.name != 'status' and field.name != 'publish' %} <label for="{{ field.name }}">{{ field.label }}</label> {{ field }} {% else %} <label for="{{ field.name }}"></label> {{ field }} {% endif %} </div> {% endfor %} <button type="submit" class="btn btn-pink btn-block">Share</button> </form> ... enter image description here