Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Nginx www redirect to non-www, browser says your connection to this site is not secure, Django
I can't connect to my site with www.example.com, it says 'not secure' only https://example.com works. At first I didn't set the DNS A record for www to redirect to my server ip so www.example.com wasn't working, but once I added the www A record it now shows Not Secure with the red https line through it when I go to www.example.com. Here is my myapp.conf from nginx sites-available: upstream myapp_app_server { server unix:/apps/myapp/myapp_env/run/gunicorn.sock fail_timeout=0; } server { listen 80; listen [::]:80; server_name example.com www.example.com; return 301 https://$server_name$request_uri; } server { listen 443 ssl http2; listen [::]:443 ssl http2; server_name example.com; ssl_certificate /etc/letsencrypt/live/example.com-0001/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/example.com-0001/privkey.pem; include /etc/letsencrypt/options-ssl-nginx.conf; ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; client_max_body_size 4G; access_log /etc/nginx/logs/nginx-access-prod.log; error_log /etc/nginx/logs/nginx-error-prod.log; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /var/www/html/myapp/static/; } location /media/ { alias /var/www/html/myapp/media/; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto https; proxy_set_header Host $http_host; proxy_redirect off; if (!-f $request_filename) { proxy_pass http://myapp_app_server; break; } if ( $host !~* ^(example.com|www.example.com)$ ) { return 444; } } } Here is my nginx.conf from etc/nginx: user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; } http { sendfile on; tcp_nopush on; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; … -
" 'User' object has no attribute 'products' 'User' "
When I run my code I keep getting this error " 'User' object has no attribute 'products' 'User' " I don't know where I went wrong please help me. Below is are my user's app codes Because I am trying to build the website to display products onto the user's profile page so the user can see the products they have got and also display these products on the main home page but I got stuck with this error. "'User' object has no attribute 'products'" **View.py** def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'{username}! your account created') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) @login_required def profile(request): users = request.user products = users.products.all() return render(request, 'users/profile.html', {'user': users, 'products': products}) @login_required def add_product(request): if request.method == 'POST': form = ProductForm(request.POST, request.FILES) if form.is_valid(): product = form.save(commit=False) product.users = request.user product.slug = slugify(product.title) product.save() return redirect('profile') else: form = ProductForm() return render(request, 'users/add_product.html', {'form': form}) Models.py from django.contrib.auth.models import User from django.db import models class Users(models.Model): name = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) created_by = models.OneToOneField(User, related_name='users', on_delete=models.CASCADE) class Meta: ordering = ['name'] def __str__(self): return self.name forms.py This … -
How to PHP cURL call to Django?
This is my cURL code to shoot Django. But it cannot get any result and keep sending request. Anyone know about this issue? Thank you.. $ch = curl_init($to_shoot_url); curl_setopt($ch, CURLOPT_TIMEOUT, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); $result = curl_exec($ch); echo $result;die; curl_close($ch); -
Reorder DELETE Field in Formset
I have a Django formset that is displayed as a table with one form per table. I would like to add a checkbox in the first column of the table so that the user to check it if they would like to delete the row (form). I have the javascript to manage the deletion of the formset row (form) and modify the management form on the front end, but I am having an issue when I add the DELETE field to the form. I used the solution reference in modify DELETE widget so that I could add the class "delete" to all of my delete fields for use in CSS and JS on the front end. When the DELETE field is added it is always the last field in the form. I would like it to be first. models.py class ModelOne(models.Model): attr_one = models.CharField(max_length=16) attr_two = models.CharField(max_length=16) forms.py class BaseFormOneFormset(BaseModelFormSet): def add_fields(self, form, index) -> None: super().add_fields(form, index) form.fields[DELETION_FIELD_NAME].widget = forms.CheckboxInput(attrs={'class':"delete"}) form.fields["id"].widget=forms.HiddenInput(attrs={'class':'pk'}) class FormOne(forms.ModelForm): class Meta: model = ModelOne attr_one = forms.CharField(max_length=16, required=True, label="attr_one", widget=forms.TextInput(attrs={'size':5,'class':'required '})) attr_two = forms.CharField(max_length=16, required=True, label="attr_two", widget=forms.TextInput(attrs={'size':5,'class':'required '})) views.py def view_one(request): formset_factory_one = modelformset_factory( ModelOne, FormOne, formset=BaseFormOneFormset, extra=0, can_delete=True) formset_one = formset_factory_one(query_set=FormOne.objects.all(), prefix="formone") return render(request, … -
Remove specific sign when filtering in Django
I have this query cardId = request.POST.get('id') with connection.cursor() as cursor: cursor.execute("SELECT category1_id FROM app_card_tbl WHERE id =%s", [cardId]) row = cursor.fetchone() cursor.execute("SELECT name FROM app_category1_tbl WHERE id =%s",[row]) tab1 = cursor.fetchone() print(tab1) And the output of this is ('thisisname',) All i want is the output should looks like this it should remove the `(',) sign it is possible? thisisname -
Hide one of the User.ModelAdmin.fieldsets if User role changes in django
Hi I want to hide some fieldsets in admin if user role changes. In get_queryset() I'm changing queryset if role == 'CMS' I also want to hide Permission fieldset for same role. Here is my admin: Note: I'm Using list for fieldsets here I pasted touples from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contrib.auth.models import Permission from .models import BankAccount from addresses.models import Address User = get_user_model() class AddressInline(admin.TabularInline): model = Address extra = 0 @admin.register(User) class UserAdmin(BaseUserAdmin): list_display = ( 'id', 'full_name', 'email', 'gender', 'role', ) list_filter = ( 'gender', 'is_staff', 'is_superuser', 'is_active', ) list_display_links = ( 'full_name', 'email', ) search_fields = ( 'email', 'first_name', 'last_name', 'phone_number', ) readonly_fields = ( 'created', 'updated', ) ordering = ('first_name', 'email', 'last_name',) fieldsets = ( ('Credentials', {'fields': ('email', 'phone_number', 'password')}), ('Info', {'fields': ('first_name', 'last_name', 'gender', 'role', 'otp', 'profile_pic', 'created', 'updated')}), ('Permissions', {'fields': ('is_vendor', 'is_staff', 'is_superuser', 'is_active', 'groups', 'user_permissions')}), ) add_fieldsets = ( ('Credentials', {'fields': ('email', 'phone_number', 'password1', 'password2')}), ('Info', {'fields': ('first_name', 'last_name', 'gender', 'role', 'profile_pic')}), ('Permissions', {'fields': ('is_vendor', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}), ) inlines = (AddressInline,) def full_name(self, obj=None): return f'{obj.first_name} {obj.last_name}' def get_queryset(self, request): if request.user.role == 'CMS': return self.model.objects.filter( role='CUSTOMER', is_staff=False, is_superuser=False … -
ckeditor embed failure issue
I use ckeditor in Django. I want to insert an embed link, but the following message is displayed when using the auto-embedding plugin. This URL could not be automatically embedded. Also, the network operation message for embedding is as follows. status 403 error "No referrer header presented with the request." -
How to use to_internal_field and to_representation to modify just one field of a model?
I have a Position model that has a field named time_to_fill. I want the user to be able to input an integer representing the number of days from the creation date of the model instance and the serializer to convert this to a datetime. Likewise upon fetching the data I want the serializer to just calculate the time delta and return an integer. I have tried implementing it through to_internal_field() but it seems like I need to implement a conversion to and from native types for all fields. Is there anyway to use to_internal_field() for one field? Model: class Position(models.Model): name = models.CharField(max_length=50, blank=False) client = models.ForeignKey(Client, null=False, blank=False, on_delete=models.CASCADE) time_to_fill = models.DateTimeField(null=True, blank=True, default=timezone.now) applicant_source = models.JSONField(default=dict, null=True, blank=True) vacancies = models.IntegerField( null=True, blank=True, validators =[MinValueValidator(0)], default=0) filled = models.IntegerField( null=True, blank=True, validators =[MinValueValidator(0)], default=0) Serializer (fails with a NOT NULL constraint error): class PositionSerializer(serializers.ModelSerializer): client_name = serializers.ReadOnlyField(source='client.name') class Meta: model = Position fields = '__all__' def to_internal_value(self, data): if (data['time_to_fill']): date = datetime.now(tz=timezone.utc) data['time_to_fill'] = date + timedelta(int(data['time_to_fill'])) return super().to_internal_value(data) -
Is it possible to have multiple views use one model but have all input go to the same table?
I'm playing around with user inputs in a madlib game, I want the user to be able to fill out the blanks then play a second game that would remember the first inputs. I have one model that handles all of the inputs, the user is asked to fill out forms on different pages but instead of appending their inputs into the same table it creates a new one. I feel like it has something to do with my views but I'm not sure how to send everything to one table, I'll post my views below. from .models import Story from .forms import PartOneForm, PartTwoForm def index(request): return render(request, 'mad_libs/index.html') def story(request): """Show part one""" story = Story.objects.all() context = {'story': story} return render(request, 'mad_libs/part_one.html', context) def part_one_forms(request): if request.method != 'POST': form = PartOneForm() else: form = PartOneForm(data=request.POST) if form.is_valid(): form.save() return redirect('mad_libs:part_one') context = {'form': form} return render(request, 'mad_libs/part_one_forms.html', context) def story_2(request): """Show part one""" story = Story.objects.all() context = {'story': story} return render(request, 'mad_libs/part_two.html', context) def part_two_forms(request): if request.method != 'POST': form = PartTwoForm() else: form = PartTwoForm(data=request.POST) if form.is_valid(): form.save() return redirect('mad_libs:part_two') context = {'form': form} return render(request, 'mad_libs/part_two_forms.html', context) -
how can i solve problem of django project?
Traceback (most recent call last): File "C:\Users\DELL1\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\utils.py", line 69, in getitem return self._engines[alias] KeyError: 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\DELL1\AppData\Local\Programs\Python\Python39\lib\site-packages\markdown_deux\templatetags\markdown_deux_tags.py", line 4, in from django.utils.encoding import force_text ImportError: cannot import name 'force_text' from 'django.utils.encoding' (C:\Users\DELL1\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\encoding.py) when I run a project of Django I face the following error please help how can I fix this? -
python if statements and validation error
Need some help with the if statements and Vaidation errors. Right now I have this function: def validate(self, validated_data): if self.partial: validated_data = self.fill_data(self.instance, validated_data) if not validated_data['brand'].sunny_account.first(): raise ValidationError('This brand does not have Sunny enabled') validated_data['calculate'] = Account.NEW return validated_data Need to add another if statement: if not validated_data['brand'].moon_account.first(): raise ValidationError('This brand does not have Moon enabled') If I add another if not statement in this function it's not going to the second one if not and raising the first Validation error. I would like that this function checking all if's and raising Validation error for the each case. -
Need help TypeError at /register/
TypeError at /register/ Got a TypeError when calling User.objects.create(). This may be because you have a writable field on the serializer class that is not a valid argument to User.objects.create(). You may need to make the field read-only, or override the RegisterSerializer.create() method to handle this correctly. Original exception was: Traceback (most recent call last): File "/Users/bishnukandel/Desktop/ISQA8380/lab4part3/venv/lib/python3.7/site-packages/rest_framework/serializers.py", line 917, in create instance = ModelClass.objects.create(**validated_data) File "/Users/bishnukandel/Desktop/ISQA8380/lab4part3/venv/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Users/bishnukandel/Desktop/ISQA8380/lab4part3/venv/lib/python3.7/site-packages/django/db/models/query.py", line 411, in create obj = self.model(**kwargs) File "/Users/bishnukandel/Desktop/ISQA8380/lab4part3/venv/lib/python3.7/site-packages/django/db/models/base.py", line 484, in init raise TypeError("'%s' is an invalid keyword argument for this function" % kwarg) TypeError: 'password2' is an invalid keyword argument for this function view.py from rest_framework import status, generics from rest_framework.decorators import api_view from django.views.decorators.csrf import csrf_exempt from .serializers import * from rest_framework.response import Response from rest_framework.permissions import IsAuthenticated, IsAuthenticatedOrReadOnly, AllowAny @csrf_exempt @api_view(['GET', 'POST']) def customer_list(request): permission_classes = (IsAuthenticatedOrReadOnly) if request.method == 'GET': customers = Customer.objects.all() serializer = CustomerSerializer(customers, context={'request': request}, many=True) return Response({'data': serializer.data}) elif request.method == 'POST': serializer = CustomerSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @api_view(['GET', 'PUT', 'DELETE']) def getCustomer(request, pk): """ Retrieve, update or delete a customer instance. """ try: customer = Customer.objects.get(pk=pk) except Customer.DoesNotExist: … -
Send real time data from django rest framework to flutter
I'm trying to implement the idea of sending a real-time data from REST API (DRF) to flutter. The problem is when i update the the model, i need the last update sent directly to flutter app without needing to refresh the app every time i sent a new update from the server. Can i achieve this through the backend? or there is another method in the flutter itself? Thanks in advance. -
Django table does not exist
I have a app in Django called webshopCatalog with the models.py. It is all in a development server, and I have previously dropped the mysql database followed by creating a new one since I was experimenting. The problem is, when I try to create a product now I get an error saying that the table does not exists (see the full error log when I click on the product link from admin). I have tried with python manage.py makemigrations and python manage.py migrate it doesn't solve the problem. I also tried to comment out the model followed by making a python manage.py makemigrations and python manage.py migrate --fake and hereafter uncomment the model followed by repeating the steps without --fake, still it doesn't solve the problem. from django.db import models from django.db.models.fields.related import create_many_to_many_intermediary_model from django.urls import reverse class Product(models.Model): name = models.CharField(max_length = 50, unique=True) description = models.TextField() allergic_note = models.CharField(max_length = 255, blank = True, null=True) quantity = models.IntegerField(null = True, blank = True) #Used for campaign products to show how many items there is left price = models.DecimalField(max_digits=9, decimal_places=0, default=0.00) is_active = models.BooleanField(default = True) is_deliverable = models.BooleanField(default = True) image_path = models.ImageField(upload_to = 'productImages') meta_keywords = … -
Django/Postgres primary key sequence
I have a Django application deployed on Heroku (free dyno) and I use Heroku Postgres as my database (Hobby Tier). I been noticing that sometimes there are some gaps/jumps on the primary key numeration. For example, there was a jump from 162 to 195, from 237 to 270... But objects are not deleted in between this gaps. I can't really understand why this is happening. Has anyone experienced something similar? What do you think? Is this problem related to Django, Postgres or Heroku? -
django | display the name value from select option with ajax (jquery) not the id
this is the ajax code $('.addtasksubmit').click(function(e) { e.preventDefault(); $.ajax({ url: 'addtodo', type: "POST", data: { title: $('#task-title').val(), category: $('#catsel option:selected').val(), 'csrfmiddlewaretoken':$('input[name=csrfmiddlewaretoken]').val() }, success: function(response) { console.log(response) $('.todos-box').append(` <a href="#" class="category-link">${response.category}</a> `) $("#addtodo").trigger('reset'); $("#exampleModal").modal('hide'); } }) }) So ${response.category} gives me the id of the category but i need the category name to be viewed and this is views.py response = { 'title': request.POST['title'], 'category' : request.POST['category'], } todo = Todo.objects.create(title=response['title'], category=Category.objects.get(id=response['category']), user=request.user) todo.save() is there any way to view the category name with ajax not the id? or how can i get the name of the category with its id. sorry for my bad english.. -
Auto update model value based on another value in this model django
I have a model called Products. This model has values like this class Product(models.Model): title = models.CharField(max_length=70, null=True, blank=True) producent = models.CharField(max_length=40, null=True, blank=True) stock = models.PositiveIntegerField(default=0, null=True, blank=True) display = models.BooleanField(null=True, blank=True, default=True) How can I change display to be False if stock is equal to 0 automatically, so when client buys last product in store display value will change from True to False and Product.objects.filter(display=True) will result in products that I want to show or are in stock. I know that I can simply chain .filter() but I wonder if I can do in an elegant way -
django can't find tinymce
I am using django 4.0.2 and django-tinymce 3.4.0 python 3.8 I am trying use tinymce as text editor by adding this line to main/urls.py urlpatterns = [ ..., path(r'^tinymce/', include('tinymce.urls')), ...., ] but is says no module named tinymce i also tried import tinymce installed after activating in virtual env using pip install django-tinymce. enter codxception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/usr/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/home/ubuntu/Desktop/guftaho/genv/lib/python3.8/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/ubuntu/Desktop/guftaho/genv/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 124, in inner_run self.check(display_num_errors=True) File "/home/ubuntu/Desktop/guftaho/genv/lib/python3.8/site-packages/django/core/management/base.py", line 438, in check all_issues = checks.run_checks( File "/home/ubuntu/Desktop/guftaho/genv/lib/python3.8/site-packages/django/core/checks/registry.py", line 77, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/home/ubuntu/Desktop/guftaho/genv/lib/python3.8/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/home/ubuntu/Desktop/guftaho/genv/lib/python3.8/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/home/ubuntu/Desktop/guftaho/genv/lib/python3.8/site-packages/django/urls/resolvers.py", line 448, in check for pattern in self.url_patterns: File "/home/ubuntu/Desktop/guftaho/genv/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/ubuntu/Desktop/guftaho/genv/lib/python3.8/site-packages/django/urls/resolvers.py", line 634, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/ubuntu/Desktop/guftaho/genv/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/ubuntu/Desktop/guftaho/genv/lib/python3.8/site-packages/django/urls/resolvers.py", line 627, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", … -
My modelformset saves only the first generated form and doesn't add the rest
I have up to 4-5 forms, the formsets come in last, I used to javascript to generate more forms at the click of a button. After submission and validation, only the first form data gets saved to the database, the others don't, how can i fix this please? This is my views.py file @login_required(login_url='login') def addItem(request, id) -> render: res_name = Restro.objects.get(user=request.user) menuobj = Main.objects.get(restro_name=res_name) sub_form = createSubCartForm(request.POST) itemformset = modelformset_factory(Item, form=addItemForm, extra=0, fields=['itname', 'quantity']) itemform = itemformset(request.POST or None) vsub_form = createVSubCartForm(request.POST) vitemformset = modelformset_factory(v_Item, form=addVItemForm, extra=0, fields=['vname']) vitemform = vitemformset(request.POST or None) vformset = modelformset_factory(ItemVariation, form=addItemVariationForm, extra=0, fields=['iname', 'varprice', 'quantity']) vform = vformset(request.POST or None) if 'nonala' in request.POST: if request.POST.get('cate1') == 'Non-Ala Carte': if all([sub_form.is_valid(), itemform.is_valid()]): global pare pare = sub_form.save(commit=False) pare.main_category = Main.objects.get(restro_name=res_name) pare.save() for form in itemform: child = form.save(commit=False) child.user = request.user child.sub_category = Sub.objects.get(id=pare.id) child.save() return redirect('cust') elif 'ala' in request.POST: if request.POST.get('cate2') == 'Ala Carte': print(request.POST) context = { 'm_name': menuobj.main_category, 'sub_form': sub_form, 'itemform': itemform, 'vsub_form': vsub_form, 'vitemform': vitemform, 'vform': vform } return render(request, 'item_form.html', context) This is my templates file <form id="non-alacart" action="" method="post" class="hidden"> {% csrf_token %} <h3 class="text-center" style="font-weight: bold;">Create Sub Cartegory for <span id="mn">{{ m_name }}</span> Category</h3> <input … -
Django - Update button checkbox to all users in realtime
I have a checkbox like this in django app, this is updated checking actual value in database when page is loaded, when user change that is updated again. This is a global switch where all users can see, my question is: how can i update this to all users if one change that? <input type="checkbox" class="form-check-input" id="customSwitch1" checked> I test update that every 5 seconds using sockets and this work. But i don't know if exist other method to do that directly with django. Any suggestion? -
can I go to a new section after submitting a form in Django
My template is coposed by section and div tags, and I want to know is there a way make me go to a new section <section> </section> on the same template-page only when my form is submitted , if yes, how i can force that on html template what i should put as a condition before the section tag!!. -
User attributes in settings.py for Okta authentication
I am currently using the following attributes in my settings.py in Django for user authentication: 'ATTRIBUTES_MAP': { 'email': 'email', 'username': 'UserName', 'first_name': 'FirstName', 'last_name': 'LastName' } Now, I want to add an attribute for the group received for the users, what format should I add for the group attribute here? -
Not being able to send emails on a django backend from a React frontend
On a form submission from my React frontend, my django backend sends emails to multiple user. I am not using any sort of backend queue for the job scheduling (for now), so the request should take little time to complete. Its important to note that I am using axios interceptors for refreshing tokens on a 401 response. Now, the thing is, everytime someone submits the form and there is more than 1 user to send an email to, I get a 401 response to my axios interceptor and it fails. But when there is only 1 user they send an email to, it works fine. I understand this might be hard to visualize without code context, but would really appreciate if someone has any idea as to why this might happen? -
Query of coordinate data in Folium (ClickForMarker)
everyone, I am currently creating a small project with python / django. I would like to develop a tool in which the user can mark a point on a map - and then send it off using the "Remember address" button. This data should then be stored in the database. I use Folium / Leaflet for this. With the function "ClickForMarker" I can already mark points on the map. Now to my question :) Currently, a new marker is placed with each click - however, I would like that if a user clicks several times, the marker is always updated. How can I read out the data (coordinates). Or do I have a "Send data" button below the map - can I process the post request with the data? I don't think I have to mention that I'm still a beginner - with Javascript, for example, I only know very little. I'm happy about any help :) -
Django generic views with form_class and model attributes
In a note about generic views in Django's docs, it says that even if form_class is set, the model attribute should be set too. But I've seen many examples (some on Django docs itself) that only the form_class was specified. Also, inside the ModelFormMixin class (generic views inherit from it) you can find this: if self.form_class: return self.form_class else: if self.model is not None: # If a model has been explicitly provided, use it model = self.model It's in the 'else' that it would look for the model. So for views that inherit from generic views like FormView or CreateView, is it necessary that I set the model attribute if I've set the form_class? If not, then what is that note talking about?