Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: table create_post has no column named links
i am getting this error (table create_post has no column named links) when trying to submit my form models: class Post(models.Model): links = models.CharField(default="", max_length=2000) forms: class NewPost(forms.ModelForm): links = forms.CharField(max_length=2000, widget=forms.Textarea(attrs={'class': 'form_input_text', 'style':'resize:none;'}), required=False) class Meta: model = Post fields = ['links'] views: def newPost(request): if request.method == 'POST': form = NewPost(request.POST) if form.is_valid(): form.save() return redirect('myposts') form = NewPost() return render(request, 'create/new_post.html', {'title_page': 'New Post', 'form': form}) -
Format decimal on definition in Admin Panel Django
I create a definition to get the percentage of completed tasks associated with a project. class ProjectAdmin(ImportExportModelAdmin,admin.ModelAdmin): #... def percentage(sef, obj): return obj.todo_set.filter(state = True).count() * 100 / obj.todo_set.all().count() #... list_display = ['project_title', 'category_list', 'date_format', 'crq_count', 'task_count', 'percentage', 'file_count', 'state'] I want to eliminate the decimals and transform it into whole numbers Finally, the idea is that if all the tasks are completed, the project status should go to finished class Project(models.Model): #... state = models.BooleanField(blank=True, null = True, default = False) -
Django ORM filter SUM different related objects on a loop
I have the following models: class Developer(models.Model): name = models.CharField(max_length=100) class Skill(models.Model): code = models.CharField(max_length=30) class Experience(models.Model): date_from = models.DateField(blank=True, null=True) date_to = models.DateField(blank=True, null=True) developer = models.ForeignKey(Developer, related_name='experience', on_delete=models.CASCADE) class SkillExperience(models.Model): skill = models.ForeignKey(Skill, on_delete=models.CASCADE, related_name='skill_experience') experience = models.ForeignKey(Experience, on_delete=models.CASCADE, related_name='skill_experience') years_experience = models.IntegerField() I know that for a single query I could do: Developer.objects.filter( experience__skill_experience__skill__code='Python' ).annotate( # sum up these years <b>total_years=Sum('experience__skill_experience__years_experience')</b> ).filter( <b>total_years__gte=5</b> ) But how to proceed if I'm on a loop of skills and I need to check an OR, so let's say looping this array: [{code: 'python', years_experience: 5}, {code: 'node', years_experience: 2}] and I need to return Devs who have either 5 years xp with python OR 2 years xp with node? -
django: Unable to connect to django server on LAN
I have a django server with python manage.py runserver 0.0.0.0:8000 ALLOWED_HOSTS=['*'] CORS_ALLOW_ALL_ORIGINS = True I have my ip as 192.168.0.5 where the django server is running i can access 192.168.0.5:8000/admin from my pc (i.e where server is running, same as the ip) but then when i try to access from a pc on lan it says CONNECTION TIMEDOUT on that pc on lan i tried to ping the ip 192.168.0.5, ping working fine Not able to understand whats wrong. Its not connecting only, whereas I have a reactjs server running on my pc whose ip is 192.168.0.5, i am able to access it from anywhere on lan -
Error: sequence item 0: expected str instance, ForeignKey found?
I'm trying to add my model to my admin.py page, I've had to play around with my ManytoMany and Arrayfields fields to get it working correctly, however I'm not out of the mud yet. Im getting this error: Error: sequence item 0: expected str instance, ForeignKey found when I try to add an object in my admin page. Here is my original model: class Bucket(models.Model): options = ( ('personal', 'Personal'), ('social', 'Social'), ) class BucketObjects(models.Manager): def get_queryset(self): return super().get_queryset().filter(Bucket.owner) owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='buckets') users = models.ManyToManyField(settings.AUTH_USER_MODEL) category = models.CharField(max_length=30, choices=options) name = models.CharField(max_length=35) created = models.DateTimeField(default=timezone.now) slug = models.SlugField(unique=True, blank=True, null=True) stock_count = models.IntegerField(blank=True, null=True) stock_list = ArrayField(models.CharField(max_length=6,null=True),size=30,null=True) about = models.CharField(max_length=75) objects = models.Manager() bucketobjects = BucketObjects() class Meta: ordering = ('-created',) def total_stocks_calc(self): self.stock_count = Bucket.objects.aggregate(Sum('stock_list', distinct=True)) self.save() def get_absolute_url(self): return reverse("bucket:bucket-view", kwargs={"slug": self.slug}) def __str__(self): return self.stock_list here is my admin.py code: @admin.register(models.Bucket) class AuthorAdmin(admin.ModelAdmin): fields = models.Bucket._meta.get_fields() list_display = ('id','owner','category', 'get_users', 'name', 'created', 'slug','stock_count','get_stocks', 'about') prepopulated_fields = {'slug': ('name',), } def get_users(self, obj): return "\n".join([u.users for u in obj.users.all()]) def get_stocks(self, obj): return "\n".join([s.stock_list for s in obj.stock_list.all()]) Not sure why I'm getting this error. EDIT: Full Traceback error: Request Method: GET Request URL: http://127.0.0.1:8000/bbucketmaster9/bucket/bucket/add/ Django … -
Not able to update an item in Django
I am trying to update the Bar Information for users by getting their details and setting the Bar instance. But every time I click on the link on my dashboard it redirects me to the dashboard which is what I used for the else statement if it is not a post method. view.py def UpdateUserBar(request): user = request.user.id bar = Bar.objects.get(user_id=user) form = UpdateBar(instance=bar) if request.method == 'POST': form = UpdateBar(request.POST, instance=bar) if form.is_valid(): form.save() return redirect('/updatebar') messages.success(request, 'Bar Information Updated successfully') else: return redirect('/dashboard') messages.error(request, 'Only Post method is accepted') else: form = UpdateBar(instance=bar) context = {"form":form, "bar":bar} return render(request, "dashboard/super/landlord/update_bar.html", context) forms.py class UpdateBar(ModelForm): class Meta: model = Bar fields = '__all__' models.py class Bar(models.Model): status = ( ("open", "open"), ("closed", "closed"), ("pending", "pending"), ) user_id = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=50) address = models.CharField(max_length=100) opening_time = models.TimeField() closing_time = models.TimeField() status = models.CharField(choices=status, default="pending", max_length=14) image = models.ImageField(upload_to='images/bars', default='images/bars/default.jpg') def __str__(self): return self.name updatebar.html {% load i18n widget_tweaks %} <form class="form-horizontal" role="form" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <label class="col-md-2 control-label">{{ form.name.label }}:</label> <div class="col-md-10"> <input type="text" id="id_name" name="name" class="form-control" value="{{user.name}}" disabled> </div> </div> <div class="form-group"> <label class="col-md-2 control-label">{{ form.user_id.label }}:</label> <div class="col-md-10"> <input id="id_user_id" name="user_id" … -
Check if number has opted out in twilio
I am building a web application that needs to be able to send SMS messages and check if a number has opted out of SMS. The only option that I have found is to use a web-hook for SMS replies and check there. I am looking for an option where I can just ping the API and check if a number has been opted-out. -
Running through an environmental error during deploying django app on heroku
I have created virtual env with anaconda prompt and created my django project in that env. I have created repository on github and push my code there and also create app on heroku but when i am running this git push heroku main command, it showing me an error which I have given below: ERROR: Could not install packages due to an EnvironmentError: [Errno 2] No such file or directory: '/tmp/build/80754af9/asgiref_1605055780383/work'.. traceback: PS C:\Users\AHMED\newrest\source> git push heroku main Enumerating objects: 48, done. Counting objects: 100% (48/48), done. Delta compression using up to 4 threads Compressing objects: 100% (44/44), done. Writing objects: 100% (48/48), 16.22 KiB | 615.00 KiB/s, done. Total 48 (delta 10), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: ! Python has released a security update! Please consider upgrading to python-3.8.6 remote: Learn More: https://devcenter.heroku.com/articles/python-runtimes remote: -----> Installing python-3.8.5 remote: -----> Installing pip 20.1.1, setuptools 47.1.1 and wheel 0.34.2 remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: Processing /tmp/build/80754af9/asgiref_1605055780383/work remote: ERROR: Could not install packages due to an EnvironmentError: [Errno 2] No such file or directory: '/tmp/build/80754af9/asgiref_1605055780383/work' remote: remote: ! Push rejected, failed to … -
Date/Time picker in html + django
I am trying to find solution for my problem, but unfortunately there is no answers. I need one button which will paste the current date/time in one of the inputs on my html form. The website is made with django. I need to put button beside {{form.data_godzina_one}}. <div id='wazne'> {{form.Trailer.label}}: {{form.Trailer}} <br><br> {{form.operacja.label}}: {{form.operacja}} <br><br> {{form.wydzial_one.label}}: {{form.wydzial_one}} <br><br> {{form.data_godzina_one.label}}: {{form.data_godzina_one}}<br><br> {{form.driver_one.label}}: {{form.driver_one}}<br> </div> -
Django django-filter django-tables2 limit query results
I am trying to limit the number of rows displayed in a table filtered using django-filter and build by django-tables2. I did not find anything here or in the docs (I don't want to use pagination). I know I can slice the queryset but I also want to have the table sortable and can't figure out how to do both. This is my views.py: def filtered_table(request): f = itemFilter(request.GET, queryset=ItemModel.objects.all()) has_filter = any(field in request.GET for field in set(f.get_fields())) table = None if has_filter: if not request.GET.get('sort'): table = ItemTable(f.qs, order_by='-timestamp') else: table = ItemTable(f.qs, order_by=request.GET.get('sort')) return render(request, 'itemlist/filteredlist.html', { 'itemtable': table, 'filter': f, }) I tried to slice the queryset before passing it to the table: table = PassTable(f.qs.order_by('-timestamp')[:20]) table = PassTable(f.qs.order_by(request.GET.get('sort'))[:20]) Resulting in: AssertionError: Cannot reorder a query once a slice has been taken. Because django-tables2 calls .order_by() again. Is there a way to configure django-tables2 or manipulate the queryset to limit the displayed rows? -
How to get dynamic HTML form fields name and value in Django?
some times 10 fields and more how to receive with request.POST.get(" ") or any method in django ex spec data id name 1 width 2 color {% for spec in spec %} <div class="form-group"> <label>{{spec.name}}</label> <input type="text" name="{{spec.id}}" class="form-control"> </div> {% endfor %} -
Django not storing data exactly as entered in form
I'm Django 3.1.4 with Postgres 13 Model: class Programme(models.Model): client = models.CharField(max_length=50, editable=True, blank=False, null=False) name = models.CharField(max_length=50, editable=True, blank=False, null=False) View: class ProgrammeCreateForm(ModelForm): class Meta: model = Programme fields = ('client', 'name') If the form input for 'client' is "ABC COMPANY" or "ABC Company", this data is being stored in the database as "Abc Company". Why is this and what should I be doing to ensure that the data is stored exactly as entered? Thanks. -
Can't change my Django model with migrations
I tried to implement many solutions that I found here, but nothing helps, so I'm looking for an answer. In my Django project I have Model.py with the following model: class Boat(models.Model): boatId = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) manufacturer = models.ForeignKey(Manufacturer, related_name='boatModels', on_delete=models.CASCADE, default=None) modelName = models.CharField(max_length=256, default=None) loa = models.FloatField(default=None) draftMin = models.FloatField(default=None) draftMax = models.FloatField(default=None) displacement = models.IntegerField(default=None) makerURL = models.CharField(max_length=1000, default=None) videoURL = models.CharField(max_length=1000, default=None) tags = TaggableManager() Initially I got this error with the latest added field videoURL: OperationalError at /boats/ no such column: boat_app_boat.videoURL Now it is this one: OverflowError at /admin/boat_app/boat/edc81b63-d8a5-4ab2-887d-97703554dc4e/change/ Python int too large to convert to SQLite INTEGER I did mess up with deleting old migrations as some advised, but I think it only made things worse. What is the best way to eventually migrate 'by the book' or if it is impoossible to say, I'd accept advice on how to start from fresh as I only have several items in my database. -
Separate Django user model from Wagtail user model
Is there a way to separate the general Django auth user model and the Wagtail auth user model? I'm including a wagtail blog app in my already existing Django project but I've been asked to create a separate user model for the blog app and I haven't found a way to do it. -
Dajngo class based view testing with django-bootstrap-modal-forms
I'm trying to test a class based view in Django where I'm implementing django-bootstrap-modal-forms. This is my view: class new_address_contact(BSModalCreateView): template_name = 'registry/address_contact.html' form_class = address_contact_Modal_Form csAddr = None # Aggiungo al contesto le mie variabili per poter utilizzare un solo template def get_context_data(self, **kwargs): # Al contesto standard/ aggiungo il modello address context = super().get_context_data(**kwargs) idAddress = self.kwargs['idAddress'] self.csAddr = CS_Address.objects.get(pk=idAddress) context['csAddr'] = self.csAddr context['title'] = 'INSERISCI NUOVO CONTATTO' context['function'] = 'INSERISCI' return context def post(self, request, *args, **kwargs): # Devo intercettare la chiamata per aggiungere il modello CS_Adresss al nuovo CS_Contact form = super().get_form() if form.is_valid(): if not self.request.is_ajax(): idAddress = self.kwargs['idAddress'] self.csAddr = CS_Address.objects.get(pk=idAddress) newContact = form.save(commit=False) newContact.address = self.csAddr newContact.save() messages.success(request, "Operazione effetuata correttamente!") return HttpResponseRedirect(self.get_success_url()) else: return super().post(request, *args, **kwargs) else: return super().post(request, *args, **kwargs) def get_success_url(self): idAddress = self.kwargs['idAddress'] self.csAddr = CS_Address.objects.get(pk=idAddress) return self.csAddr.get_absolute_url() for the test I tried to follow the django documentation: class Address_Contact(RegistryTest): def test_post_new_address_contact(self): post_data = { 'idAddress': self.cs_address.id, 'contact_type': 'cell', 'contact_value': '3339941768', 'note': 'qualche nota', } #todo finire test NB questa è una class based pop up view url = reverse('registry:new_address_contact', args=[self.cs_address.pk]) request = RequestFactory().post(url, data=post_data) response = new_address_contact(request=request) # view.setup(request) # response = view.post() self.assertEqual(response.status_code, 302) I'm playing … -
How to authenticate in Django with Azure AD via django-microsoft-auth
I'm trying to set up a local Django app which uses Azure Active Directory for authentication. I went through this quick start using the django_microsoft_auth library for backend authentication. I registered a new app on Azure and set the URI to http://localhost:8000/microsoft/auth-callback/. This is the same port which is used for the other pages like the admin page. When I try to login via Azure AD, I get the following error message: AADSTS50011: The reply URL specified in the request does not match the reply URLs configured for the application Only few other threads with this problem exist and there hasn't been a real solution yet using this library. Does anyone know a solution to this problem? -
django.core.exceptions.ImproperlyConfigured error all of a sudden
Worth mentioning: Everything was working fine with my django project until today. I tried to run some test from another session of coding to see if everything was alright then I saw this. Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I tried: export DJANGO_SETTINGS_MODULE=<name_of_my_app>.settings then another error was raised: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. I tried putting this in settings.py: import django django.setup() Then something about SECRET_KEY can not be empty appeared even tough I had SECRET_KEY = '<my_secret_key>' in settings.py Never encountered this problem before and I don't know how to solve it or why it happened all of a sudden. -
View Other Users Profile Page in Django
I am creating a django application and i'm stuck at a point where i need to display other user's information about a product they will place an order for when that product is clicked but so far it is just displaying my own information. -
Can SELECT FOR UPDATE cause deadlocks?
I am using Django 2.2.12 as an ORM for MySQL 8.0, one of the queries is a concurrent SELECT FOR UPDATE, inside a transaction, where two or more threads may be targeting the same rows. Is not select for update atomic? Two transactions are allowed to lock and select the rows at same time? I am getting deadlock errors at random times. -
Trying to use add_notification() method on UserProfile object, ValueError: cannot assign UserProfile - Notification.user must be a User instance
I'm trying to use the default user model in my django application. I created UserProfile objects to have custom/additional fields for users. I'm trying to assign Notification objects to each UserProfile and I have the following code block allUsers = User.objects.all() for each in allUsers: uprof = UserProfile.objects.get_or_create(user=each) for u in allUsers: if u.userprofile: notif1 = u.userprofile.add_notification(title="Welcome to our site " + u.email, body="Your first notification") # error notif2 = u.userprofile.add_notification(title="Sample Notification" + u.email, body="Empty template for " + u.email) # also same error I was running this in a django shell plus. The first for loop iterates through all users and gives them a UserProfile object. The second tries to assign a notification to that user with a userprofile method called add_notification(). This fails and generates the error ValueError: Cannot assign "<UserProfile: devtest4@gmail.com>": "Notification.user" must be a "User" instance. I kinda don't really know what this error message means. And even so, I thought this would be the correct way of assigning a UserProfile to every existing User and then adding a notification to each user's respective userprofile. Am I going about this wrong? user_profile/models.py class UserProfile(models.Model): phone_number = models.CharField(max_length=15, verbose_name='Phone Number') user = models.OneToOneField(User, on_delete = models.CASCADE) api_key … -
Django model force capitalizing db_column names
I'm creating a Django model that reads from an Oracle SQL database. From the table that the model reads from, some columns have mixed cases and spaces, i.e. "Region" and "Foo Bar". So SELECT "Region", "Foo Bar" FROM some_table is perfectly valid on the db side of things. The Django model reads those columns explicitly using the db_column field, class SomeModel(models.Model): region = models.CharField(max_length=100, db_column="Region") foo_bar = models.CharField(max_length=100, db_column="Foo Bar") When Django goes to the database, however, I get the error ORA-00904: invalid identifier: "some_table"."FOO BAR" from column name being capitalized somewhere along the process. Is there some way that I can force Django to preserve the mixed case from the Django perspective, without modifying the column names on the db side? I have tried: db_column="'Foo Bar'", '"Foo Bar"', "\"Foo Bar\"", none of these seem to make the string interpreted literally and upper-cased. Thanks! Hacky workarounds welcomed. -
DRF Function Based View custom schema decorator for query parameters in swagger ui
I'd break my brain and loose/waste to much time to manage using Schema Decorator in DRF. I follow https://www.django-rest-framework.org/topics/documenting-your-api/ and manage it but on sagger-ui and redoc-ui. But GET method query parameters or POST body json string payload aren't documented. So i'm trying to deal with AutoSchema, ManualSchema and Custom classes to generate api documentation. https://www.django-rest-framework.org/api-guide/views/#view-schema-decorator But i never manage anything good. and yes i looking through [django-rest-framework] tag on stackoverflow too and yes i open a discussion on DRF google community (but no answers yet). So what i tried. Try to deal: import coreapi import coreschema from rest_framework.schemas import AutoSchema, ManualSchema log_file_delete_schema = AutoSchema( manual_fields=[ coreapi.Field( "file_path", required=True, location="query", type="string", description="path of the log to be delete", ) ] ) But it returns "AutoShema as no get_operation" error Try next: import coreapi import coreschema from rest_framework.schemas import AutoSchema, ManualSchema class CustomLogFileDeleteSchema(AutoSchema): def __init__(self): super(CustomLogFileDeleteSchema, self).__init__ def get_manual_fields(self, path, method): extra_fields = [ coreapi.Field( "file_path", required=True, location="query", description="log file path", type="string", example="/path/to/file/logfile.log", ) ] manual_fields = super().get_manual_fields(path, method) return manual_fields + extra_fields It returns to me 'CustomLogFileDeleteSchema' object has no attribute 'instance_schemas' I tried to use Django Rest Swagger but it's unmaintened project now so ==> next I'm using function … -
How to display a Custom Error Page in Django
I have a list of tables in my application, if a user book an available table it books it correctly without error but if a user books an unavailable table it displays an error page saying "Tables matching query does not exist". I have been trying some ways to get a custom error page or perhaps some nicer interface instead of the page error. error log Environment: Request Method: POST Request URL: http://localhost:8000/reserve/1/ Django Version: 3.1.4 Python Version: 3.7.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'core', 'dashboard', 'widget_tweaks', 'phonenumber_field'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\Habib\Documents\django\FIVERR\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Habib\Documents\django\FIVERR\venv\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Habib\Documents\django\FIVERR\adam_mailk\core\views.py", line 30, in ReserveTable table_exists = Tables.objects.get(table_no=request.POST['table'], bar=bar) File "C:\Users\Habib\Documents\django\FIVERR\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\Habib\Documents\django\FIVERR\venv\lib\site-packages\django\db\models\query.py", line 431, in get self.model._meta.object_name Exception Type: DoesNotExist at /reserve/1/ Exception Value: Tables matching query does not exist. views.py def ReserveTable(request, pk): bar = Bar.objects.get(id=pk) tables = Tables.objects.filter(bar=bar, status="available") form = ReservationForm() if request.method == "POST": if request.POST['table']: request.POST = request.POST.copy() table_exists = Tables.objects.get(table_no=request.POST['table'], bar=bar) if table_exists.DoesNotExist: return redirect(reverse('error-page', kwargs={'message': "This object does … -
django file upload progress bar with XMLHttpRequest
i created a normal django model.ModelForm and it is worked perfectly until i tried to add Progress bar for files uploading, i have an issue. i recieve the form information(request.POST and request.FILES) twice! but it is save the data only once in database, so also it is work, but i know i have a mistake in my code and i want to understand my mistake. this is my function for displaying the progress bar: function UploadFilesWithProgress(form, url) { const progressbarWrap = document.querySelector('.progress-bar-wrap'), label = progressbarWrap.querySelector('h6'), percentage = progressbarWrap.querySelector('span'), progressbarFill = progressbarWrap.querySelector('.progress > .progress-bar') let xhr = new XMLHttpRequest() xhr.open('POST', url, true); xhr.upload.onloadstart = function (e) { progressbarWrap.classList.remove('d-none') percentage.textContent = '0%' label.textContent = 'uploading...' }; xhr.upload.onprogress = function (e) { const percent = e.lengthComputable ? (e.loaded / e.total) * 100 : 0; progressbarFill.style.width = percent.toFixed(2) + '%'; progressbarFill.setAttribute('aria-valuenow', percent.toFixed(2)) percentage.textContent = percent.toFixed(2) + '%'; } xhr.upload.onloadend = function (e) { label.textContent = 'uplaod completed!' percentage.textContent = 'completed!' } xhr.send(new FormData(form)); } Form = document.getElementById('add-course-form') if (Form) { Form.onsubmit = function () { UploadFilesWithProgress(Form, Form.action); } } and this is my view: # I use CBV, so i share just the post method to not get missy. def post(self, *args, **kwargs): form … -
Tweet not creating in django twitter clone
I am just trying to build a simple twitter clone using django. To create a new tweet, a user has to choose an image and type some text. So i do just that, and when I click on the create tweet button, I get a form error that says "The image field is required". I don't understand why this happens. Here is a screenshot of that error: I don't even get ant error message. Here is my CreateTweet view function: class CreateTweetView(LoginRequiredMixin,CreateView): model = Tweet fields = ('image','tweet') template_name = 'twitter/create_tweet.html' def form_valid(self): new_tweet = form.save(commit=False) new_tweet.author = self.request.user new_tweet.save() return redirect('home') What is the problem here? EDIT: I have chosen an image, and upon form submission, I get this error In the media folder, I don't see the uploaded image