Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Fetch Data from database and project it on a Datatable using django/ajax
I just recently learned Django/ajax/datatables. I can project my data using a {%for%} loop and im trying to do the same thing with ajax calls. My view: def is_ajax(request): return request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest' def getfromServer(request): if is_ajax(request=request) and request.method == "GET": books= Book.objects.all() bookserial = serializers.serialize('json', books) return JsonResponse(bookserial, safe=False) return JsonResponse({'message':'Wrong validation'}) index.html <div class="container"> <table id="books" class="display" style="width:100%"> <thead> <tr> <th>Book</th> <th>Author</th> <th>Genre</th> <th>Date Publishedd</th> <th>Copies</th> </tr> </thead> </table> </div> <script> $(document).ready(function() { $('#books').DataTable({ ajax: { type: "GET", datatype : 'json', url: 'views/getfromServer', }, columns: [ { data: 'name' }, { data: 'author' }, { data: 'genre' }, { data: 'pub_date' }, { data: 'copies' }, ] }); </script> Im pretty sure it kinda works this way but i just cant figure it out . -
change Class property properties (verbose_name exmpl.) from base Django model
I have an abstract class with name and slug field.when i inherit from another class i want to change verbose_name parameter according to that class. How can I set this properties? I want to set the verbose_name parameter of the name field to "foo". but I want to use different parameter data for two different classes. An example: For ProductModel name field verbose_name="Foo" For CategoryModel name field verbose_name="Poo" class BaseProductModel(models.Model): name = models.CharField(max_length=200) slug = AutoSlugField(populate_from="name",unique=True,verbose_name="Slug") class Meta: abstract=True class ProductModel(BaseProductModel): # I want to set the verbose_Name parameter of the name field to "foo". #The two fields (name and slug) come from the inherited (BaseProductModel) class. description = models.TextField(max_length=500,verbose_name="Detay") class CategoryModel(BaseProductModel): # The two fields (name and slug) come from the inherited (BaseProductModel) class. # I want to set the verbose_Name parameter of the name field to "Poo". def __str__(self): return self.name -
Employee roster using HTML, CSS, JS, and Django Framework [closed]
I already have a website that has multiple functions and I want to add a webpage for creating and editing my employee's roster. right now, we are using excel so I want to create a webpage that is excel like so my employees can view their roster online. I need suggestions for a good and free library to do that or if someone knows how to do it using pure JavaScript, I would appreciate that. preferably something that works well with Django. I attached a picture of the current roster to make things clear. -
Django - How to add a comment form at the buttom of a poll
Please help with this. I created a poll app (follow a TraversyMedia tutorial). I want to be able to let user to add a comment along with the poll. I creaded a model "Comment" and from admin area i can set ca commment to a specific question and in front page i can display it alog with the resolts poll from that question. But I don't know how to bring this "comment" form to the user's page so that the user, after choosing one of the poll options, leaves a comment and it is saved together with the poll options. Below you will find my settings. (i created the form.py and set the class etc but i don't know what to do next). Thank you models class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('publicat la:') def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text class Comment(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name="comments") comment_text = models.TextField(null=True, blank=True) def __str__(self): return self.comment_text views from .models import Question, Choice, Comment # preluare si afisare intrebari din sondaj def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, 'sondaj/index.html', context) # afisare optiuni … -
Unable to catch GraphQL error in django testing
I am testing my resolver in graphQl, i am working with django and ariadne library. this is the test i wrote: def test_check_trigger(self): query = """ query GetTrigeer($id: ID!) { trigger(id:$id){ uuid agent threshold } } """ agent = Agent.objects.create( user=self.user, user_address=self.user_address, agent_address=self.agent_address1 ) trigger = Trigger.objects.create( user=self.user, agent=agent, pool=self.pool1, token=Trigger.TOKEN0, threshold=50, state=Trigger.ARMED ) trigger_id = agent.uuid #passing wrong value to get error variables = {"id": str(trigger_id)} with self.assertRaises(GraphQLError,msg="Trigger not found"): self.run_graphql_query( query=query, variables=variables, token=self.token) This is the function i am using to get response from graphql: def run_graphql_query(self, query, token, variables): c = Client(raise_request_exception=True) access_token = token["access"] AUTHORIZATION_HEADER = "HTTP_AUTHORIZATION" AUTHORIZATION_TYPE = "Bearer" headers = {AUTHORIZATION_HEADER: f"{AUTHORIZATION_TYPE} {access_token}"} r = c.post("/graphql/", data={ "operations": json.dumps( {"query": query, "variables": variables} ) }, **headers) return r But i am not able to catch the error, i may be using wrong approach but all i want to do is pass wrong value in query and match error messages as expected, this is error message i am getting in terminal: 617, in resolve_field result = resolve_fn(source, info, **args) File "/home/welcome/agents-platform/services/api/api/auth.py", line 12, in resolve_is_authenticated result = original_resolver(obj, info, **kwargs) File "/home/welcome/.local/share/virtualenvs/api-_WI5du6j/lib/python3.8/site-packages/ariadne/utils.py", line 75, in wrapper return func(*args, **convert_to_snake_case(kwargs)) File "/home/welcome/agents-platform/services/api/stoploss/resolvers.py", line 76, in resolve_trigger … -
python django vs php laravel
I'm a python Django back end developer, applied for a job as back end and they asked me to implement a minimal double-entry accounting system via PHP Laravel, I have not worked on PHP Laravel at all, and have 5 days to accomplish the task, should I dedicate the next 5 days to learn and accomplish the task or it won't be easy mission given that I'm not familiar with the language and the framework. Will my understanding of Django easier the process of learning? Please your input will really help me decide, I'm overthinking it alot. -
Django TypeError : expected str, bytes or os.PathLike object, not list || When adding new object
When I'm in the admin panel and I add this object called Cover I am getting this error. I have the same image, text, and char field in other models without any issue does anybody have a good idea of what is happening? TypeError : expected str, bytes or os.PathLike object, not list https://ibb.co/XzDwsXd But I don't have a list anywhere! Please help! models.py class Cover(models.Model): cover_image = models.ImageField(upload_to="images/", blank=True, null=True) cover_title = models.CharField(max_length=64, null=True) text = models.TextField(max_length=256, null=True) views.py def index(request): if request.method == 'POST': is_private = request.POST.get('is_private', False) message_email = request.POST['message_email'] send_mail( 'New Midas&Co litter and newsletter request from '+ message_email, # subject message_email + ' requests to be notified about upcoming litters.', # message 'Midas & Co Website', # from Email ['midasandcompany22@gmail.com', 'webmasterzzzbot@gmail.com'], # to email ) return render(request, "cattery/index.html", {'message_email': message_email, 'cover':cover}) return render(request, "cattery/index.html") admin.py from django.contrib import admin from .models import Cat, Stud, Queen, Cover admin.site.register(Cat) admin.site.register(Stud) admin.site.register(Queen) admin.site.register(Cover) -
Django TypeError at /admin/login in the admin AppConfig.__init__() missing 1 required positional argument: 'app_module'
I am not able to go to the admin site when I type /admin. With startproject this page should work as far as I know and I cannot find out what is the problem. -
how to make my django api publicily accessible?
I deployed it in the ubuntu server, it is running on localhost port 8000? I tried doing port 80 redirecting to 8000 using IP tables but its not helping -
Restricting user sending one form again and again?
I want to know how to restrict a user that he can't send form again and again, if it submitted already by him. The main goal is like, if I have a form like daily quiz that asks "What is the capital city of Italy?", a user should see it and send an answer once. And restrict a user to send an answer until the new question is active, like "What is the capital city of Germany". Are there any good approach? -
Reliably navigate route history for "back" button Django 4.0.3
On each of my app views, there is a page header with breadcrumbs & a back button to return to the previous view. I'd like to be able to reliably track & navigate the user's routing history to make sure to always send them back to the same view they came from. HTTP_REFERER doesn't factor in the potential of nested views. If you were to navigate from Page A -> Page B - Page C & use the back button on Page C you'd be taken to Page B, and then the HTTP_REFERER would become PAGE_C which sends the user in an infinite loop rather than taking them to Page A on clicking back again. window.history.back() or window.history.go(-1) doesn't consider that someone might be linked directly to Page B in which the back button would then send them to whatever is the previous page in their browsing history throughout the life of that tab, not direct them to Page A. My thought was maybe a middleware could append each route to a list in request.session, however, at this point I'm unsure how I'd detect a back button click to move backwards through this. As well, with this solution, I'm worried … -
URL can't contain control characters
I am getting Url can't contain special character.{the whole url with mobile number and otp in it} (found at least ' ') errror. Please help ''' def send_otp(mobile , otp): print("FUNCTION CALLED") conn = http.client.HTTPSConnection("api.msg91.com") authkey = settings.AUTH_KEY headers = { 'content-type': "application/json" } url = "http://control.msg91.com/api/sendotp.php?otp="+otp+"&message="+"Your otp is "+otp +"&mobile="+mobile+"&authkey="+authkey+"&country=91" conn.request("GET", url , headers=headers) res = conn.getresponse() data = res.read() print(data) return None ''' -
How can I use for loop to find society name endswith city name or not?
I am trying to check each society's name that contains the city name at the end of the society name. This is the code that I writing in the cmd. for s in societies: ... s_name = societies.filter(name__iendswith=s.locality.city.name) ... print(s_name) I have tried the above code and I got these entries. All these societies' name contains city name at the end but problem is that as you see it prints the same entry again and again. <QuerySet [<Society: Society object (213)>, <Society: Society object (239)>, <Society: Society object (629)>, <Society: Society object (634)>, <Society: Society object (635)>, <Society: Society object (636)>]> <QuerySet [<Society: Society object (213)>, <Society: Society object (239)>, <Society: Society object (629)>, <Society: Society object (634)>, <Society: Society object (635)>, <Society: Society object (636)>]> <QuerySet [<Society: Society object (213)>, <Society: Society object (239)>, <Society: Society object (629)>, <Society: Society object (634)>, <Society: Society object (635)>, <Society: Society object (636)>]> <QuerySet [<Society: Society object (213)>, <Society: Society object (239)>, <Society: Society object (629)>, <Society: Society object (634)>, <Society: Society object (635)>, <Society: Society object (636)>]> <QuerySet [<Society: Society object (213)>, <Society: Society object (239)>, <Society: Society object (629)>, <Society: Society object (634)>, <Society: Society object (635)>, <Society: Society object … -
Django form not showing validation error with in Templates
I am trying to build Registration page . I am writting custom validation for my registration form field . But the problem is form is not raising validation error . When i am writting form.is_valid() it is showing validated . I am new to django and learning new concepts . I am trying to figure out what is wrong here . Forms.py file code : from django import forms from django.core import validators def emptyField(value): if value == '': raise forms.ValidationError("Please fill all the fields .") def length(value): if len(value) > 20: raise forms.ValidationError("Username can contain atmost 20 characters .") class UserForm(forms.Form): username = forms.CharField(required=False,validators=[emptyField,length]) email = forms.EmailField(required=False,validators=[emptyField]) password = forms.CharField(required=False,validators=[emptyField]) rePassword = forms.CharField(required=False,validators=[emptyField]) views.py file code : from django.shortcuts import render,redirect from .forms import UserForm # Create your views here. def home(request): return render(request,"Users/home.html") def registrationPage(request): if request.method == "POST": form = UserForm(request.POST) if form.is_valid(): print("validated") else: form=UserForm() context = { "form": UserForm } return render(request,"Users/register.html",context) register.html file code : <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <title> REGISTRATION PAGE </title> </head> <body> <h1> REGISTRATION PAGE </h1> <form method="POST"> {% csrf_token %} {{ form.username }} {{ form.email }} {{ form.password }} {{ form.rePassword }} <input type="submit" … -
HTTPS Mixed content error with hosting React site and Django REST API
I am trying to host a website made with React and its API (Django REST) on the same Ubuntu machine. The React site is currently being hosted on a domain with HTTPS, while the API is hosted on a port on the machine with HTTP. I get the following error accessing the site: Mixed Content: The page at (site) was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint (api). This content should also be served over HTTPS. It still works if I enable insecure content for the site, but is there a way to serve both of them over HTTPS other than having the API on a separate domain? -
Is there a way to add all Django Models fields into a check list?
I would like to create a checklist form based on the models selected can I print out all of the models fields into a checklist for the user to select which field to create a table for? -
How could i use fieldsets in django template for Django 3.0
Here i am using python version 3.7.10 and Django 3.0 My fieldsets worked fine on python 2.7 and Django 1.8 Here is my forms.py class CampaignMainForm(forms.ModelForm): class Meta: model = Campaign exclude = ['campaign_create_send_id', 'list_id', 'name', 'subject', 'created_by', 'send_datetime', 'send_timezone'] fieldsets = [ ['group',{ 'fields': ['group'], 'legend': "Recipients", }], ['template',{ 'fields': ['stored_template'], 'legend': "Template", }], ['templatedata',{ 'fields': ['stored_template_data', 'stored_template_data_validated'], 'legend': "Template Content", }], ] Now in my template how i tried is {% for fieldset in form.fieldsets %} <fieldset{% if fieldset.name != "templatedata" %} class="accordion-group"{% endif %}> {% if fieldset.name != "templatedata" %} <legend><bull class="bull {% if fieldset.legend == "Recipients" %}{% if object.group != None %}label-color-0d0{% endif %}{% elif fieldset.legend == "Template" %}{% if object.stored_template != None %}label-color-0d0{% endif %}{% else %}label-color-0d0{% endif %}"></bull> <a href="#" class="collapse-title" data-toggle="collapse" data-target=".collapse-{{ fieldset.legend|slugify }}" data-parent="#main-accordian">{{ fieldset.legend }}</a> <small class="muted">{% if fieldset.legend == "Template" %}{% if object.stored_template != None %}{{ object.stored_template.name }}{% endif %}{% endif %}{% if fieldset.legend == "Recipients" %}{% if object.group != None %}{{ object.group }} ({{ email_valid_count }} emails){% endif %}{% endif %}</small> </legend> ..... ..... {% endfor %} But here my for loop is not working properly.Actually what i need is if fieldset.name != "templatedata" then it need to display … -
Django rest framework Heroku Application Error
-----> Building on the Heroku-20 stack -----> Using buildpack: heroku/python -----> Python app detected -----> Using Python version specified in Pipfile.lock -----> Requirements file has been changed, clearing cached dependencies cp: cannot stat '/tmp/build_eaebc38f/requirements.txt': No such file or directory -----> Installing python-3.10.2 -----> Installing pip 21.3.1, setuptools 57.5.0 and wheel 0.37.0 -----> Installing dependencies with Pipenv 2020.11.15 Installing dependencies from Pipfile.lock (86a10d)... Ignoring tzdata: markers 'sys_platform == "win32"' don't match your environment -----> Installing SQLite3 -----> $ python manage.py collectstatic --noinput System check identified some issues: WARNINGS: ?: (staticfiles.W004) The directory '/tmp/build_eaebc38f/static' in the STATICFILES_DIRS setting does not exist. 161 static files copied to '/tmp/build_eaebc38f/staticfiles', 414 post-processed. -----> Discovering process types Procfile declares types -> web -----> Compressing... Done: 98.7M -----> Launching... Released v11 https://vicsites.herokuapp.com/ deployed to Heroku This my heroku deployment log and its still showing application error Here's my Procfile web: gunicorn vicsite.wsgi --log-file - The errors I spot in the log stated above are: ?: (staticfiles.W004) The directory '/tmp/build_eaebc38f/static' in the STATICFILES_DIRS setting does not exist. 161 static files copied to '/tmp/build_eaebc38f/staticfiles', 414 post-processed. 'sys_platform == "win32" don't match your environment -
How to save a foreign key automatically in Django?
I'd like to save restaurantID(foreign key which refers to Restaurant_Account) in the Menu table. They need to have the same value. For example, if user 'A' in Restaurant_Account is logged in and fills the form to save data in the Menu table, user A's restaurantID should be saved in the Menu table automatically. How can I do this? Thanks in advance. Below is my code! class Restaurant_Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) is_restaurant = models.BooleanField(default=True) restaurantID = models.AutoField(primary_key=True) name = models.CharField(max_length=200) isActive = models.BooleanField(default=True) image = models.ImageField(upload_to='images/', blank=True) website = models.URLField(blank=True) country = models.CharField(max_length=50) def __str__(self): return self.user.username class Menu(models.Model): restaurantID = models.ForeignKey(Restaurant_Account, on_delete=models.CASCADE, default=None, null=True) item = models.CharField(max_length=100) itemImage = models.ImageField(upload_to='images/', blank=True) price = models.DecimalField(max_digits=6, decimal_places=2) category = models.CharField( max_length=20, choices=CHOICES) def __str__(self): return self.item Below is my views.py. def Add_Menu(request, restaurantID): display=Menu.objects.get(id=restaurantID) form = MenuForm if request.method=="POST": form = MenuForm(request.POST, request.FILES) if form.is_valid(): restaurant = form.save(commit=False) restaurant.restaurantID = Restaurant_Account.objects.get(restaurantID=restaurantID) restaurant.save() #form.save_m2m() messages.success(request, "Saved successfully!") return redirect('index') else: form=MenuForm() return render(request, 'restaurant/add_menu.html', {'form':form, 'display':display}) -
Create superuser error, TypeError: create_superuser() missing 1 required positional argument: 'name'
When i run createsuperuser command in terminal ..it prompts to enter email and then password .I didn't get the username field. After entering password it gives me TypeError: create_superuser() missing 1 required positional argument: 'name'. Here is my models.py from django.db import models from datetime import datetime class Realtor(models.Model): name = models.CharField(max_length=50) photo = models.ImageField(upload_to='photos/%Y/%m/%d/') description = models.TextField(blank=True) phone = models.CharField(max_length=20) email = models.CharField(max_length=100) top_seller = models.BooleanField(default=False) date_hired = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.name and this is the error : self.UserModel._default_manager.db_manager(database).create_superuser( TypeError: create_superuser() missing 1 required positional argument: 'name' Could anyone please guide me how to solve this issue? -
How to allow adding inline objects only if a BooleanField is checked in django admin?
Screenshot: django admin site inline model I want the 'Add another Step' button to be disabled/greyed out if 'Have Step' is not checked (see screenshot above). When 'Have Step' is checked, the 'Add another Step' button should be enabled and the user can add a step. Is there any easy way to do this? Thanks! The Step model is an inline for the Course model. A course can have 0 or more steps. My models.py: class Course(models.Model): title = models.CharField(null=False, max_length=50) short_description = models.TextField(max_length=100, null=False) external_resource = models.BooleanField(default=False, blank=True) external_resource_link = models.URLField(null=True, blank=True) have_step = models.BooleanField(default=False, blank=True) class Step(models.Model): title = models.CharField(max_length=100, null=False) step_description = models.TextField(max_length=150, null=False) course = models.ForeignKey(LearningGuide, on_delete=models.CASCADE) My admin.py: class StepInline(admin.StackedInline): model = Step extra = 0 # no empty step form is shown initially min_num = 0 # min number of steps per course = 0 class CourseAdmin(admin.ModelAdmin): inlines = [StepInline] list_display = ['title'] admin.site.register(Course, CourseAdmin) -
Django JsonResponse is returning escaped Unicode
I’m trying to get Django to return a JsonResponse, but strings containing Unicode characters are being turned into escape sequences. For example, when I try to create a response with this dictionary: { "Latn-x-macron": "amisk", "Latn": "amisk", "Cans": "ᐊᒥᐢᐠ" } cURL gets a response like this: { "Latn-x-macron": "amisk", "Latn": "amisk", "Cans": "\u140a\u14a5\u1422\u1420" } Is there any way to get Unicode to return normally? -
Why file extension validator is not working properly in django?
I am trying to add a file extension validator in the Filefield of my model. But when I am adding a different extension file through my serializer it's adding the extensions I didn't put in my validators.py Here is the code so far # validators.py def validate_file_extension(value): import os from django.core.exceptions import ValidationError ext = os.path.splitext(value.name)[1] # [0] returns path+filename valid_extensions = ["png", "jpg", "jpeg", # for images "pdf", "doc", "docx", "txt", # for documents "mp3", "aac", "m4a", "mp4", "ogg"] # for audios if not ext.lower() in valid_extensions: raise ValidationError('Unsupported file extension.') #models.py class QuestionFile(models.Model): question = models.ForeignKey( Question, on_delete=models.CASCADE, related_name='files', null=True, blank=True) FILE_TYPE = ( ('NONE', 'NONE'), ('IMAGE', 'IMAGE'), ('DOCUMENT', 'DOCUMENT'), ('AUDIO', 'AUDIO'), ) file_type = models.CharField( choices=FILE_TYPE, max_length=50, null=True, blank=True) file = models.FileField( 'files', upload_to=path_and_rename, max_length=500, null=True, blank=True, validators=[validate_file_extension]) def __str__(self): return str(self.question) and here is the output in my serializer for this model "id": .., "file": "<filepath>/c-f479b7453519484b827dbc0051bd9a64.html", "file_type": .., "question": .. As it's visible, though .html extension is not added in the validators.py still it's uploading. Did I make any mistakes in my code? I am unable to figure out that. If any other information is needed let me know, please. Thanks -
Static files not loading for deployed django rest framework
I have built and successfully deployed a django rest framework using gunicorn and nginx on Ubuntu 18.04. However, the static files are not being pulled up. Django web app without loaded static files Here is my nginx configuration: server { listen 80 default_server; listen [::]:80 default_server; server_name [my_server_domain_or_IP]; #root /var/www/html; location = /favicon.ico { access_log off; log_not_found off; } location = /static/ { root /home/ubuntu/myprojectdir; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } And in my settings.py file: STATIC_URL = '/static/' import os STATIC_ROOT = os.path.join(BASE_DIR, 'static/') I have checked that DEBUG is set to False. I have also already run collectstatic and the static files are located in a folder called static in: /home/ubuntu/myprojectdir/static. Every change I tried to make in the nginx configuration, I restarted nginx with the following command: sudo systemctl restart nginx. I mainly followed this tutorial, the only difference is that I edited the default nginx configuration instead of creating a new one because it wasn't deploying my django application this way. I can't seem to figure out what's wrong and have been trying to solve it for days. Am I missing something here? -
Django Modelform user issues
I have a model form to list an item and I am trying to get the form to fill in the user id from the user that is submitting the form. Currently, the form is submitted successfully but it always uses the first user in the database's id for every item. models.py class Item(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False ) creator = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, default=2) item_name = models.CharField(max_length=40) price = models.DecimalField(max_digits = 6, decimal_places=2) description = models.CharField(max_length= 500) main_image = models.ImageField(upload_to=path_and_rename , max_length=255, null=True, blank=True) image_2 = models.ImageField(upload_to='items/', blank=True) image_3= models.ImageField(upload_to='items/', blank=True) image_4= models.ImageField(upload_to='items/', blank=True) image_5= models.ImageField(upload_to='items/', blank=True) quantity = models.IntegerField(default=1, validators=[ MaxValueValidator(100),MinValueValidator(1)]) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) def __str__(self): return self.item_name def get_absolute_url(self): return reverse("item_detail_view", args=[str(self.id)]) forms.py from django.forms import ModelForm, forms from .models import Item class List_Item_Form(ModelForm): forms.ModelChoiceField(queryset=Item.objects.filter(user=user)) class Meta: model = Item def __init__(self, *args, **kwargs): user = kwargs.pop("user", None) super().__init__(*args, **kwargs) views.py class AddListing( generic.CreateView): template_name = 'store/add_listing.html' fields = ('item_name','price','description','main_image','quantity') model = Item def form_valid(self, form): self.object = form.save(commit=False) self.object.user = self.request.user self.object.save() return super().form_valid(form)