Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fetch users that i follow?
I want to make a viewset to allow request.user (Authenticated user) to receive the users in a view that they follow. But i do not know how to make an appropriate queryset filter for it. Models (Note: Author is the one following,profile is the one followed) class User(AbstractUser,PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.CharField(max_length=255,unique=True) username =models.CharField(max_length=40,unique=True,default='undefinedusername') class UserFollow(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='following') profile = models.ForeignKey(User,on_delete=models.CASCADE,related_name='followers') View class FetchUserViewSet(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) queryset = User.objects.all() serializer_class = UserSerializer filter_backends = [FollowedUserFilterBackend] Filter class FollowedUserFilterBackend(filters.BaseFilterBackend): def filter_queryset(self, request, queryset, view): return queryset.filter( ??? ) I tried following__author = request.user but it returns the user that made the request,not the user that user follows. How can i do it? -
Trying to join a query for salesforce on python
I want to make a query from salesforce using an id opportunity_id="0061g00000BRG00AAH" query = "SELECT+FIELDS(ALL)+FROM+Opportunity+WHERE+ID+=+'"+opportunity_id+"'" print(json.dumps(sf_api_call('/data/v51.0/query/', {"q": query}))) But I get this error: b'[{"message":"\\nSELECT+FIELDS(ALL)+FROM+Opportunity+WHERE+ID+=+\'0061g00000BRG00AAH\'\\n ^\\nERROR at Row:1:Column:6\\nunexpected token: \'+\'","errorCode":"MALFORMED_QUERY"}]' -
How to get multiple fields of a django form in one row
Hej! I want to have multiple fields of a django form next to each other. (Input fields to search in a table) For now I can get them under each other with this template: <form method="post"> {{ form.as_p }} {% csrf_token %} <input type="submit" value="Search"> </form> or two next to each other with: <div class="container"> <div class="row"> {% for field in form %} <div class="col-sm-6"> {{ field.label_tag }} {{ field }} </div> {% endfor %} </div> </div> but then I loose the 'form' of the forms. How can I get multiple (let's say 5) fields in one row? All ideas welcome! Thanks for the help :) -
Definition of the structure of a REST API with django from a data format
I was asked to write an API interface which should retrieve data from a connected object. The format of this data is as follows: { "devEUI": "8cf9572000023509", "appID": 1, "type": "uplink", "time": 1629378939869, "data": { "gwid": "b827ebfffebce2d3", "rssi": -77, "snr": 10, "freq": 868.1, "dr": 5, "adr": true, "class": "C", "fCnt": 852, "fPort": 8, "confirmed": false, "data": "AgUCIzYBAIERAAAAAAAAAAAAAAAAAAAAAAAAAADHDgA=", "gws": [ { "id": "b827ebfffebce2d3", "rssi": -77, "snr": 10 } ] } } I develop with django. I want to write a REST api with django.Should the data and gws fields be classes? How can I define the classes? -
Passing a token in the header of a ListAPIView endpoint from one api to another Django REST
I have 2 APIs in Django REST. One API generates a JWT token. I want to send that token to another API. In the first API (API 1), I am posting the token to the ListItems class (/someendpoint/) in the header of the POST request. import requests token = "someToken" requests.post("/posting/token", {token}) In another API (API 2), I want to receive that JWT token in the request header : in views.py: class ListItems(generics.ListAPIView): permission_classes = [ItemsPermissions] queryset = SomeModel.objects.all() serializer_class = SomeSerializer in urls.py: url_patterns = [ path("/someendpoint/list/", ListItems.as_view(), ] What is the best way to achieve that ? -
https with nginx and docker compose not working
Please I need some assistance. Your contributions will be greatly appreciated I am trying to add ssl to my nginx and docker compose configuration. Currently, everything works fine with http, but it won't work with https. Here is my docker-compose.yml file version: '3.8' services: web_gunicorn: image: ACCT_ID.dkr.ecr.us-east-2.amazonaws.com/web_gunicorn:latest volumes: - static:/static - media:/media # env_file: # - .env pull_policy: always restart: always ports: - "8000:8000" environment: - PYTHONUNBUFFERED=1 - PYTHONDONTWRITEBYTECODE=1 nginx: image: ACCT_ID.dkr.ecr.us-east-2.amazonaws.com/nginx:latest pull_policy: always restart: always volumes: - static:/static - media:/media - ./certbot/conf:/etc/letsencrypt - ./certbot/www:/var/www/certbot ports: - "80:80" - "443:443" depends_on: - web_gunicorn certbot: image: certbot/certbot restart: unless-stopped volumes: - ./certbot/conf:/etc/letsencrypt - ./certbot/www:/var/www/certbot depends_on: - nginx entrypoint: "/bin/sh -c 'trap exit TERM; while :; do certbot renew; sleep 12h & wait $${!}; done;'" volumes: static: media: Here is my nginx.conf configuration that works (http) upstream web { server web_gunicorn:8000; } server { listen 80; server_name domain.com; location / { resolver 127.0.0.11; proxy_pass http://web; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static/ { alias /static/; } location /media/ { alias /media/; } } Here is my nginx.conf configuration that does not work (http and https) upstream web { server web_gunicorn:8000; } server { location / { resolver 127.0.0.11; … -
Django ListView derived classes ignoring paginate_by field
I am using Django 3.2 I am using OOP to keep my code DRY. I have a base class Foo (which derives from ListView), and I am setting common properties in that class. I then have two specialisations of Foo - which I expect to be cognisant of the paginate_by member variable - however, the subclasses seem to be ignoring the variable I set paginate_by to, as it has no effect. This is my code: class UserFooList(LoginRequiredMixin, ListView): http_method_names = ['post'] paginate_by = 2 def post(self, request, *args, **kwargs): # some processing logic return render(request, '/path/to/Foo_list.html', context=context, status=status_code) class UserApprovedFooList(UserFooList): def get_queryset(self): return Foo.objects.prefetch_related().filter(/* query criteria one */) class UserFoosInModerationQueueList(UserFooList): def get_queryset(self): return Foo.objects.prefetch_related().filter(/* query criteria two */) Why is the paginate_by field being ignored by UserApprovedFooList and UserFoosInModerationQueueList - and how do I resolve this? -
{% include %} django template issue
I'm trying to connect my header for a new file, I do it like this {% include filename%}. in other files it works without any problem. Now it only connects the html itself but without statics. {% load static %} <!DOCTYPE html> <html > <head> <meta charset="UTF-8"> <title>Sign In/Up</title> </head> {% include 'inc/_header.html' %} settings STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'essense/static'), ] -
django.db.utils.OperationalError : This probably means the server terminated abnormally (only Django app)
I am currently trying to connect to a Sage Evolution server from a django web application The below error is displayed when I run "inspectdb" or "inspectdb > models.py" The server does connect when I ping it through the command prompt and connect to it via the .bat file I had created to test the connection. So I don't see why it would be an error on the servers side C:\Users\KylePOG\Documents\GMA Programming\accConnect>python manage.py inspectdb > models.py Traceback (most recent call last): File "C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\base.py", line 219, in ensure_connection self.connect() File "C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\postgresql\base.py", line 187, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib\site-packages\psycopg2\__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: server closed the connection unexpectedly This probably means the server terminated abnormally before or while processing the request. The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\KylePOG\Documents\GMA Programming\accConnect\manage.py", line 22, in <module> main() File "C:\Users\KylePOG\Documents\GMA Programming\accConnect\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) … -
Django RestAPI but without CSS
I am making an REST API using Django Restframework It works perfectly but I get an error when I have pushed it to railway app like this Installing SQLite3 -----> $ python manage.py collectstatic --noinput Traceback (most recent call last): File "/workspace/manage.py", line 22, in <module> main() File "/workspace/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 187, in handle collected = self.collect() File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 114, in collect handler(path, prefixed_path, storage) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 338, in copy_file if not self.delete_file(path, prefixed_path, source_storage): File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 248, in delete_file if self.storage.exists(prefixed_path): File "/app/.heroku/python/lib/python3.9/site-packages/django/core/files/storage.py", line 318, in exists return os.path.exists(self.path(name)) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/storage.py", line 38, in path raise ImproperlyConfigured("You're using the staticfiles app " django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. ! Error while running '$ python manage.py collectstatic --noinput'. See traceback above for details. You may need to update application code to resolve this error. Or, you can disable collectstatic for this application: $ heroku config:set DISABLE_COLLECTSTATIC=1 https://devcenter.heroku.com/articles/django-assets ERROR: failed … -
{'required': 'This field is required.', 'null': 'This field may not be null.', 'invalid': 'Invalid data. Expected a dictionary, but got {datatype}.'}
This is the error which is thrown by the serializer.is_valid(). I don't know why this error come. I am new to Django Rest Framework. I am trying to make a simple invoice generating api. which takes info about seller, buyer, items and generate a invoice. So I write models for each and one model for invoice in which seller, buyer are foriegn key. Item model is related to invoice model through a foreign key. Any Help is appreciated. This is my models.py class Seller(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=50) phone = models.CharField(max_length=12) address = models.CharField(max_length=200) def __str__(self): return self.name class Buyer(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=50) phone = models.CharField(max_length=12) address = models.CharField(max_length=200) def __str__(self): return self.name class Invoice(models.Model): id = models.AutoField(primary_key=True) seller = models.ForeignKey(Seller, on_delete=models.CASCADE) buyer = models.ForeignKey(Buyer, on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) def total_amount(self): total = Decimal('0.00') for item in self.items.all(): total = total + item.total() return total def invoice_number(self): if len(str(self.id))==1: return 'Invoice00'+self.id elif len(str(self.id))==2: return 'Invoice0'+self.id else: return 'Invoice'+self.id def __str__(self): return f'{self.seller} {self.buyer} {self.date}' class Item(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=20) invoice = models.ForeignKey(Invoice, on_delete=models.CASCADE) price = models.DecimalField(decimal_places=2, max_digits=20) quantity = models.IntegerField(default=1) tax = models.DecimalField(decimal_places=2, max_digits=4) def total(self): total = Decimal(str((self.price-self.tax)*self.quantity)) return total.quantize(Decimal('0.01')) def … -
Django FilterSet, Count and Distinct
I'm building a custom filter for a model, and I wanted to have two optional boolean fields that would alter the way the queryset is created. One boolean for distinct, that would make the result be only unique values, like in .distinct(), and another boolean for count, that would instead return the number of items, like with a .count() I have found this: https://django-filter.readthedocs.io/en/stable/ref/filters.html#distinct but i cant really understand how to use it. Also, I haven't found a way for count My filter looks like this: class MyModelFilter(django_filters.FilterSet): class Meta: model = Inventory fields = ( "service", "provider" "recorded_at", "tenant", "tenant_name", "project_system", "area", "environment", "region", ) data_filter = django_filters.CharFilter(method="json_filter") def json_filter(self, queryset, name, value): string_to_json = json.loads(value) return queryset.filter(data__contains=string_to_json) -
Access a Django server from a VM Linux deployed with Amazon EC2
I have developed a Django app on a Amazon EC2 virtual machine which I access using ssh. When I run python manage.py runserver, everything works fine, and I have Django version 3.2.6, using settings 'crm.settings' Starting ASGI/Channels version 3.0.4 development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. The thing is I would like to see the result of this app in a browser, either on the VM or in the browser of my computer (of course 127.0.0.1 is not working on my "main" Linux) So far, I have tried ipconfig in the VM, but I do not know what to do with the output. Do you guys have any idea / clue? Any assistance is appreciated, feel free to ask for specifications. Thanks in advance -
setting conditional serializer class removes the custom serializer class for extra action in Django rest framework
I have one modelviewset and couple of extra actions for it. class TestViewset( mixins.RetrieveModelMixin, mixins.ListModelMixin, mixins.UpdateModelMixin, GenericViewSet, ): permission_classes = [CustomPermissionClass] def get_serializer_class(self) -> Type[ModelSerializer]: if self.action == "list" or self.action == "get": return FirstSerializer return SecondSerializer @action( detail=True, methods=["POST"], url_path="test-path", url_name="test-path", serializer_class=MyCustomSerializer, ) def test_path(self, request: Request, **kwargs) -> Response: print(self.get_serializer()) # Despite setting the 'MyCustomSerializer' it still gives me 'SecondSerializer' return Response(status=status.HTTP_200_OK) If I remove the get_serializer_class method and give only one serializer it works. What could be the best solution for this or is this any bug in drf? Ideally the extra action should use the serializer class that has been provided but its not. -
Compare and groupby using Django ORM
I have 8 objects from 2 different models. Say, Fruit and Colour I want to filter and group Fruits based on Benefits. For instance, Orange and Grapes can be grouped together because they share similar benefits , i.e. "rich in vitamin C" Here's my code: models.py class Fruit(models.Model): name = models.CharField(max_length=40, blank=True, null=True) colour = models.CharField(max_length=40, blank=True, null=True) benefits = models.JSONField(default=dict) class Benefit(models.Model): health_benefit = models.CharField(max_length=240, blank=True, null=True) I tried the following: all_benefits = Benefit.objects.values_list('health_benefit') Fruit.objects.filter(benefits__in=all_benefits) Not sure if this is the correct way to query. Thanks in advance. -
How to pass non string to innerHTML
I am using django, basically i am trying to change some part of the html code using javascript. below chart work nicely <div id='treemap_charts'> {{ treemap_code.first.treemap_price_difference_yesterday|safe }} </div> with final result being <div id='treemap_charts'> HTML code </div> However, when I added some javascript to alter the content inside the div id='treemap_charts' as shown below: <script> document.addEventListener('DOMContentLoaded', function(){ document.querySelector("#treemap_options").onchange = function() { if (this.value==='day') { document.querySelector('#treemap_charts').innerHTML='{{treemap_code.first.treemap_price_difference_yesterday}}'; } else { document.querySelector('#treemap_charts').innerHTML='{{treemap_code.first.treemap_price_difference_month}}'; } } }); </script> <div> <select id='treemap_options' name='Treemap Charts'> <option value='day' selected>1 Day Performance</option> <option value='week'>1 Week Performance</option> </select> </div> <div id='treemap_charts'> {{ treemap_code.first.treemap_price_difference_yesterday|safe }} </div> the HTML result end up as a string instead of HTML code <div id='treemap_charts'> "HTML code" </div> PS:I try to use this code but it does not work <script> document.addEventListener('DOMContentLoaded', function(){ document.querySelector("#treemap_options").onchange = function() { if (this.value==='day') { document.querySelector('#treemap_charts').innerHTML='{{treemap_code.first.treemap_price_difference_yesterday|safe}}'; } else { document.querySelector('#treemap_charts').innerHTML='{{treemap_code.first.treemap_price_difference_month|safe}}'; } } }); </script> Anyidea how I can pass {{ treemap_code.first.treemap_price_difference_yesterday|safe }} to the div without it changing to string? I search around the forum but seem unable to get the answer but one thing I learn is at least in the HTML need to have |safe else it will not work... -
Editing foreign keys in django-forms
I recently got into django and django forms. What i'm trying to do is make a form where my foreign key is editable. (a form of the other model where my foreign key is refering to inside a form). so lets say I have these models class Model2(models.Model): name = models.CharField(max_length=50) class Model1(models.Model): type = models.ForeignKey(Model2, on_delete=models.CASCADE) value = models.CharField(max_length=50) # other fields When you render the form for Model1, the foreign key must be editble aswell. I'm wondering if anything like this is possible -
Is there way to gracefully remove a Django plugin from the project
We have installed a charting plugin in our Django project, but we found another one that more suits our requirements. Is there a way to gracefully remove the plugin from our project? -
Django how to force page reload on event
I am developing an application that communicates with measurement system. Clicking "start test" button causes redirection to the "test_in_progress" view which is just a sign "test in progress" with progress spinner. In that view the application awaits response from the measurement system. I want to redirect to the "test_results" view when the message comes and I don't really know how to do that. Should I just set some flag and in "test_in_progress" page poll for the flag periodically with js (if this is the right approach then how to do that?). Or is there any way to force page redirection from within python? -
using Hebrew language in django and xhtml2pdf to save pdf
Hi I can't figure this up but how do I save pdf with Hebrew charcters in xhtml2pdf I can't find anything online the code suppose to acceses a property from the database and then create a pdf file and sent it to the client mail pyhon code that convert template to pdf from django.template.loader import get_template from os.path import join from .utils import render_to_pdf from django.http import HttpResponse from xhtml2pdf import pisa def generate_pdf(property): template = get_template("main/pdftabo.html") context = { "address": f'{property.street} {property.building_number} {property.city}', "owners": property.owners, "loan": property.loan, "plot": property.plot, } html = template.render(context) filepath = join('static',f'media/{property.block}{property.lot}.pdf') write_to_file = open(filepath, "w+b") result = pisa.CreatePDF(html,dest=write_to_file) write_to_file.close() the pdf template html code <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> {% load static %} <html lang="heb"> <head> <meta charset="character_set"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> @font-face { font-family: MyRightToLeftFont; src: url("{% static 'fonts/ahronbd.ttf' %}") } p { font-family: MyRightToLeftFont } </style> </head> <body> <pdf:language name="hebrew" /> <p>שלום</p> <table> <tr> <th>מגרש</th> <th>מס' בית</th> <th>מס' הדירה לפי הסכם המכר</th> <th>מהוות הנכס</th> </tr> <tr> <th>{{plot}}</th> <th>7</th> <th>1</th> <th>{{address}}</th> </tr> </table> </body> </html> image of what i get -
How to embed a Django application on a Wix website?
How do I embed a Django application inside a Wix website? I have my app hosted on a server, but now I want to embed this app inside a Wix website. I've made a couple of changes to the settings.py such as Commenting out csrf middleware and Xframeoptions middleware. Added these lines SESSION_COOKIE_SAMESITE = 'None' # As a string SESSION_COOKIE_SECURE = True X_FRAME_OPTIONS = 'ALLOWALL' XS_SHARING_ALLOWED_METHODS = ['POST','GET','OPTIONS', 'PUT', 'DELETE'] Added @csrf_exempt on top of every function in my views.py file. Although it's rendering the website, the only function that does not work is the sign in and register option, and that too only in the Wix website, it works fine when I sign in or register through the actual server domain but not when I do it through Wix. I'm not sure if it has something to do with Wix itself or Django, so can someone help my figure this issue out if it is even possible in the first place? -
Changing the default user while using REST framework JWT
I have a proxied user model: class TheDude(User): class Meta: proxy = True And I'm using the Django REST framework JWT to do JWT auth in the REST API. I'd like to get the user object from the request but currently it's a User object. Because it's proxied I can't use AUTH_USER_MODEL. I've tried doing a middleware component to override the user in the request but it's not set at that stage. I've also tried using JWT_RESPONSE_PAYLOAD_HANDLER however my function isn't called so I can't set it there either. If I want to be able to get TheDude object when I call request.user instead of User in my views, how would I do this while authing using the REST framework JWT Auth library? -
Django, How to update DateTimeField attribute only when one specific attribute is changed
I would like to update the attribute date_assigned only when the attribute Customer is changed. I know that I have to overwrite the save function within the same model but i don't know exactly how. class Ip(models.Model): customer = models.ForeignKey(Customer, null=False, on_delete=models.CASCADE) ip = models.GenericIPAddressField(protocol="IPv4", null=False, unique=True) date_created = models.DateTimeField(auto_now_add=True,) date_updated = models.DateTimeField(auto_now=True,) date_assigned = models.DateTimeField(auto_now=True) Any ideas? thanks in advance. -
Unable to publish data from inherited class - paho django
Initialized paho mqtt as a class class Initializer(): def __init__(self): self.client = mqtt.Client(mqtt_server+str(int(time.time()))) self.client.username_pw_set( username=mqtt_username, password=mqtt_password) self.client.on_connect = self.on_connect self.client.on_message = self.on_message self.client.on_subscribe = self.on_subscribe self.client.connect(broker, mqtt_port) self.client.loop_start() def on_connect(self, client, userdata, flags, rc): if rc == 0: #app_logger.info("Device Connection Established") print("Device Connection Established") else: #app_logger.info("Bad Connection") print("Bad Connection") then i have created a another class that inherits initializer class class send(Initializer): def __init__(self): super().__init__() self.client.publish("topic","data") able to print the value of self.client inside the initialization of send class but not able to publish data. -
Does form_valid() in CBV not call is_valid() method?
When I used function views, It was able to handle cleaned_data with overriding form.clean() method. I thought when I call form.is_valid method, form.clean() is called too. Form validation happens when the data is cleaned. If you want to customize this process, there are various places to make changes, each one serving a different purpose. Three types of cleaning methods are run during form processing. These are normally executed when you call the is_valid() method on a form. Now I'm trying to do same things with class-based-view, but it does not work as I thought. Here's my forms.py: class PublishForm(forms.ModelForm): class Meta: model = models.Article exclude = [ 'author', ] def __init__(self, user, *args, **kwargs) -> None: self.user = user return super(PublishForm, self).__init__(*args, **kwargs) def is_valid(self): print('IS_VALID METHOD CALLED') return super(PublishForm, self).is_valid() def clean(self): print('CLEAN METHOD CALLED') cleaned = super(PublishForm, self).clean() cleaned['author'] = self.user return cleaned and views.py: class PublishView(generic.CreateView): form_class = forms.PublishForm success_url = '/' template_name = 'ex00/publish.html' def form_valid(self, form): print(form.cleaned_data) return super(PublishView, self).form_valid(form) def form_invalid(self, form): print(form.errors) return super(PublishView, self).form_invalid(form) It seems form_valid() does not call neither form.is_valid() or form.clean(). But It was able to get form.cleaned_data(). How does form_valid() work? What should I do to manipulate cleaned_data …