Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Logging incorrect translations in Django
I often run into the mistake of using gettext in a context where the actual language is not set yet - instead of using the appropriate gettext_lazy. Those errors can be difficult to catch - I would like to make them more visible appropriate logging, or possibly even throwing exceptions. Would it be correct, to write a wrapper function that logs an error in the case of get_language() is None? Then of course, one would need to enforce that this wrapper is always used - introducing another subtle easy to make mistake. In general, I suppose monkey-patching could be used, but I'd like to avoid that if possible. The whole dispatch behind django.util.translation seems already relatively complex. Is there a clean way too hook this functionality in there? -
Django REST Framework caching programmatically
From the official docs it looks like the only way of caching with DRF is to use decorators. As far as I know, there is also a more flexible way to use caching directly querying the cache, like in the example below (source): from django.core.cache import cache from django.conf import settings from django.core.cache.backends.base import DEFAULT_TIMEOUT CACHE_TTL = getattr(settings, 'CACHE_TTL', DEFAULT_TIMEOUT) def cached_sample(request): if 'sample' in cache: json = cache.get('sample') return JsonResponse(json, safe=False) else: objs = SampleModel.objects.all() json = serializers.serialize('json', objs) # store data in cache cache.set('sample', json, timeout=CACHE_TTL) return JsonResponse(json, safe=False) This approach gives use more control over what and how long we store in the cache. So, my question is the following: is there a way to adapt this way of caching to a simple view defined in DRF? Example: # MODEL class Item(models.Model): code = models.CharField(max_length=8, primary_key=True) name = models.CharField(max_length=32) # SERIALIZER class ItemSerializer(serializers.ModelSerializer): class Meta: model = Pair fields = '__all__' # VIEW class ItemsList(generics.ListAPIView): queryset = Item.objects.all() serializer_class = ItemSerializer def list(self, request): queryset = self.get_queryset() serializer = ItemSerializer(queryset, many=True) return Response(serializer.data) -
Django Rest Framework - overriding save in backend is not created custom id
I am working on a project. I have Django for my backend and Vue for my front end. When using the templates and saving in the Django project I have no issues. However, when I POST to my projects API the following save from my modal is not being created. models.py class DevProjects(models.Model): PROJECT_TYPE = [ ('New Application', 'New Application'), ('Update Application', 'Update Application'), ('Bug Fixes', 'Bug Fixes') ] PROJECT_STATUS = [ ('New', 'New'), ('In Progress', 'In Progress'), ('Complete', 'Complete'), ] project_id = models.CharField(max_length=15, editable=False, unique=True) project_title = models.CharField(max_length=100) project_desc = models.CharField(max_length=500) project_category = models.CharField(max_length=25, choices=PROJECT_TYPE, null=True, blank=True) project_status = models.CharField(max_length=25, choices=PROJECT_STATUS, default='New') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateField(auto_now=True) created_by = models.ForeignKey(User, related_name='projects', on_delete=models.CASCADE) def save(self, *args, **kwargs): super(DevProjects, self).save(**kwargs) self.project_id = 'PROJ-' + str(self.id) super(DevProjects, self).save(**kwargs) def __str__(self): return self.project_title I have the project_id being created on save which gets the original ID but just adds 'PROJ-' in front. Whenever I submit the form from my frontend, that save definition is not being called, thus not creating the project_id. Project ID is what I use to send a GET request to get the projects. serailizer.py class DevProjectSerializer(serializers.ModelSerializer): class Meta: model = DevProjects fields = ("project_id", "project_title", "project_desc", "project_category", "project_status") … -
How do I use Django generic updateviews to update my model using individual form field values?
models.py: from django.db import models class Location(models.Model): name = models.CharField(max_length=20) is_source = models.BooleanField(default=False) is_destination = models.BooleanField(default=False) def __str__(self): return self.name views.py from django.shortcuts import render from django.urls import reverse_lazy from django.views import generic from .models import Location class LocationsListView(generic.ListView): model = Location template_name = 'locations/list.html' context_object_name = 'locations' class LocationUpdateView(generic.edit.UpdateView): model = Location fields = ['name', 'is_source', 'is_destination'] context_object_name = 'location' template_name = 'locations/update.html' success_url = reverse_lazy('locations:list') class LocationDeleteView (generic.edit.DeleteView): model = Location template_name = 'locations/confirm_delete.html' context_object_name = 'location' success_url = reverse_lazy('locations:list') locations/update.html {% extends 'base.html' %} {% block title %}Location Update{% endblock %} {% block content %} <section> <div class="container"> <h1>Location Update</h1> <div class="form-container"> <form method="post"> {% csrf_token %} {% if form.errors %} <div class="p-3 mb-3 border border-danger border-3 rounded">{{ form.errors }}</div> {% endif %} <div class="mb-3"> <label for="" class="form-label">Name</label> <input type="text" class="form-control" value="{{ form.name.value }}"> </div> <div class="mb-3"> <input type="checkbox" class="form-check-input" {% if form.is_source.value %} checked {% endif %}> <label for="">Source</label> </div> <div class="mb-3"> <input type="checkbox" class="form-check-input" {% if form.is_destination.value %} checked {% endif %}> <label for="">Destination</label> </div> <input type="submit" class="btn btn-success mb-3" value="Save"> </form> </div> </div> </section> {% endblock %} locations.urls.py from django.urls import path from . import views app_name = 'locations' urlpatterns = [ path('', views.LocationsListView.as_view(), … -
django app - django.core.exceptions.ImproperlyConfigured
So I'd like to overwrite some of the signals provided by django all auth. Therefore I overwrite the core/apps.py file like this: class CoreAppConfig(AppConfig): name = 'core.apps.CoreAppConfig' label = "core" def ready(self): from allauth.account.signals import email_confirmed from allauth.account.models import EmailAddress from .signals import profile # todo import not working email_confirmed.connect(profile, EmailAddress) And my init file: default_app_config = 'core.apps.CoreAppConfig' And my installed apps include: 'core.apps.CoreAppConfig', "profile" is a signal which just creates a new Profile object for the user in the request. This is not the problem here. The problem is that when I run the server, an error occurs; Error: django.core.exceptions.ImproperlyConfigured: Cannot import 'core.apps.CoreAppConfig'. Check that 'core.apps.CoreAppConfig.name' is correct. -
Issues importing Chart.js into django project via CDN
I have a simple django project that needs the use of the Chart.js library for one of the templates. My base.html where I imported the library is shown below is shown below: <!DOCTYPE html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]--> <!--[if gt IE 8]> <html class="no-js"> <!--<![endif]--> <html> <head> <style> body {font-family: Helvetica, Roboto, Georgia} div * {display:flex; justify-content:center} </style> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Switch Monitor</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href=""> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <script type="module" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.0.1/chart.min.js" integrity="sha512-tQYZBKe34uzoeOjY9jr3MX7R/mo7n25vnqbnrkskGr4D6YOoPYSpyafUAzQVjV6xAozAqUFIEFsCO4z8mnVBXA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> </head> <body> <div id="dialog" style="display:grid;justify-content:center"> {% block title %} <h1>Switch Monitor</h1> {% endblock title %} {% block content %} {% endblock content %} </div> {% block script %} <script src="" async defer></script> {% endblock script %} </body> </html> My django settings.py is shown below, the server was restarted after the CORS settings were changed. from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = … -
Django REST: Set all Serializer fields as not required at once
Is there any way to set my serializer fields as not required by default? it'll take me hours to set every field of every serializer I have as not required so I wanted to know if there's any shortcut. One example: class ComputersSerializer(serializers.ModelSerializer): name = serializers.CharField(required=False) serial = serializers.CharField(required=False) otherserial = serializers.CharField(required=False) contact = serializers.CharField(required=False) contact_num = serializers.CharField(required=False) comment = serializers.CharField(required=False) date_mod = serializers.DateTimeField(required=False) is_template = serializers.IntegerField(default=0) template_name = serializers.CharField(required=False) is_deleted = serializers.IntegerField(default=0) is_dynamic = serializers.IntegerField(default=0) ticket_tco = serializers.DecimalField(max_digits=20, decimal_places=4, required=False) uuid = serializers.CharField(required=False) date_creation = serializers.DateTimeField(required=False) is_recursive = serializers.IntegerField(default=0) last_inventory_update = serializers.DateTimeField(required=False) computertypes = ComputertypesSerializer(required=False) computermodels = ComputermodelsSerializer(required=False) entities = EntitiesSerializer(required=False) networks = NetworksSerializer(required=False) locations = LocationsSerializer(required=False) autoupdatesystems = AutoupdatesystemsSerializer(required=False) users = assistanceSerializers.UsersSerializer(required=False) groups = assistanceSerializers.GroupsSerializer(required=False) states = StatesSerializer(required=False) users_tech = assistanceSerializers.UsersSerializer(required=False) groups_tech = assistanceSerializers.GroupsSerializer(required=False) manufacturers = ManufacturersSerializer(required=False) class Meta: model = Computers fields = '__all__' For the moment I had to set it for each field. I've been searching if someone had the same problem but it looks like I'm lazier than the rest of programmers. -
<embed> - src from proxy server
I am currently struggling with setting the src attribute of the <embed> element. I have my PDF documents stored in the cloud storage with limited access. My application has users, and each user has its own set of PDF contracts on the dedicated namespace. Since I do not want to expose any URL to the users nor call the storage from the front end, I prepared a proxy endpoint (with authorized access) that returns the application/pdf response to be displayed in a particular <embed> component. Does anyone know how to display the content with this paradigm? Thank you for any hint. -
use of gTTS in Django project
i want to use gTTS in my Django project. Accordingly i installed django-gtts(pip install Django-Gtts). It is installed successfully.. later i added 'gTTS' under INSTALLED-APPS of setting.py file. Then run the server and also tried makemigrations gTTS. in both the case got below errir. import_module(entry) File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in imp ort_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'gTTS' please suggest what i should next.. i tried all possible way with my litte knowledge but unable to fix it.. please let me know if you need more information. -
Group by in serializer in Django Rest Framework
I am new to Django Rest Framework, I want to group my serializer data by date, How can I do that. How can I group this by Date? my model: mongo model with some more fields also but only uses these two fields class Activity(Document): """ mongo model """ candidate_id = StringField(required=True, db_field='c') timestamp = DateTimeField(required=True, db_field='d') ... ... more fields My Views: my views file class RecentActionView(generics.ListAPIView): serializer_class = RecentActionSerializer def get_queryset(self): recruiter_id = self.request.GET.get("recruiter_id") activity_list = Activity.objects.filter(recruiter_id=str(recruiter_id)).order_by('- timestamp') return activity_list my serializer: using serializermethod field to get data from other DB by using candidate id from activity model class RecentActionSerializer(serializers.Serializer): name = serializers.SerializerMethodField() designation = serializers.SerializerMethodField() age = serializers.SerializerMethodField() timestamp = serializers.DateTimeField(format="%H:%M") def get_name(self, obj): return something def get_designation(self, obj): return something def get_age(self, obj): return something I want to group my response by Date like : [ { "date": "2022-12-05", "candidates":[ { "name": "One", "designation": "Lead", "age": 30, "timestamp": "14:30" } ] }, { "date": "2022-12-04", "candidates":[ { "name": "Two", "designation": "Lead", "age": 30, "timestamp": "14:30", } ] } ] my actual response is like: [ { "name": "One", "designation": "Lead", "age": 30, "activity_timestamp": "13:12" }, { "name": "Two", "designation": "Lead", "age": 30, "activity_timestamp": "13:12" } ] -
Fetch Python Logger Formatter Variables in Code
I have a Django project and this is what the logger formatter configuration looks like. 'formatters': { 'simple': { 'format': '%(asctime)s SCORPIO [%(request_id)s] ' + os.environ['ENVIRONMENT'] + ': %(message)s', 'datefmt': '%Y-%m-%dT%H:%M:%S', }, }, How does Python pick the different variables (asctime, request_id) provided in the format? I need to fetch the request_id variable in case of a failure and display it on a page. I've mostly worked with Java in which these variables are picked from the ThreadContext so I tried looking for such an alternative in Python but couldn't find one. -
Unable to create new project in django
(zenv) PS C:\Users\heman\Dev\try-django> django-admin startproject zFirst_site EROOR: Traceback (most recent call last): File "<frozen runpy>", line 198, in _run_module_as_main File "<frozen runpy>", line 88, in _run_code . . . . . . . File "C:\Python311\Lib\site-packages\django\db\models\fields\__init__.py", line 155, in __init__ if isinstance(choices, collections.Iterator): ^^^^^^^^^^^^^^^^^^^^ AttributeError: module 'collections' has no attribute 'Iterator' * It was all okay till by mistake i uninstalled every pip packages* -
Inside a Django model class, is it possible to asssign an attribute with the value of another attribute's foreign key?
class Post(models.Model): item = models.ForeignKey(Item, related_name="posts", on_delete=models.CASCADE) post_by = models.TextField(max_length=50) # value= With the above django model, is it possible to assign to value such that I get item's foreign key object called Item and then with that I get Item's id and this is stored in the attribute value? -
Django User Logging In System | Views.py doesn't work
I am currently making a user authentication system. I have a login screen with a couple of input fields. I can log the values of the input fields to the console in my javascript. I send the data to my backend. Submitting doesn't work and in my views.py loggin the data to the console too. I can basically completely remove the views.py function and the Template is shown anyway! Is that because I am using the Django Authentication Urls, so the registration folder is the default for the django registration? How can I send that to my backend? I have my logging in template (https://pastebin.com/RKe5ECps) Views.py def login_user(request): if request.method == "POST": username = request.POST["username"] password = request.POST["password"] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('forum') else: messages.success(request, ("There was an error Loggin in, Try Again!")) return redirect('login') else: return render(request, 'login.html', {}) Urls.py path('', include('django.contrib.auth.urls')), Folder Structure: templates/registration/login.html templates/registration/signup.html I tried removing the authentication, but than i couldn't see anything, because at the login/ url there was nothing. -
Duplicate data after using update_or_create
In my project I retrieve data from an API that I save on my database created in parallel, the problem is that the initial data is duplicated each time I refresh the page that executes the API models.py class Empl(models.Model): code=models.CharField(max_length=10,blank=True,null=True) age=models.CharField(max_length=255,blank=True,null=True) service=models.CharField(max_length=255,blank=True,null=True) views.py url='http://myAPI/Empl/GetEmpl' x=requests.get(url) content=x.json() for data in content: emp , _ = Empl.objects.update_or_create(code=data['code'],age=data['age'],service=data['service']) emp.save() At the level of my project when I look for an employee on the search bar, several employees with the same data. And this every time I refresh the page that executes the API, the initial data is duplicated and so on. Oddly when I perform a filter on an employee through her code in Mysql Base I get a single tuple, I don't understand? -
How to handle network errors when saving to Django Models
I have a Django .save() execution that loops at n times. My concern is how to guard against network errors during saving, as some entries could be saved while others won't and there could be no telling. What is the best way to make sure that the execution is completed? Here's a sample of my code # SAVE DEBIT ENTRIES for i in range(len(debit_journals)): # UPDATE JOURNAL RECORD debit_journals[i].approval_no = journal_transaction_id debit_journals[i].approval_status = 'approved' debit_journals[i].save() -
Converting texts to foreign keys when importing data with Django excel
Tbl.1 id author brand_id name barcode unit user1 TestBrand1 Product1 TST1234 700 user2 TestBrand2 Product2 TST5678 380 I have an excel spreadsheet as in the example above. The author and brand_id in the table fields represent the foreignkey fields in the model. When the user wants to add a product to the system with excel, he/she has to enter the author and the brand as strings. Like the table in the example above. But since author and brand_id are foreign keys, excel should be like this.` Tbl.2 id author brand_id name barcode unit 1 1 Product1 TST1234 700 2 2 Product2 TST5678 380 My question is how can I dynamically convert the author and brand data received as strings as a foreign key on the database and save it. For example, if brand_id = TestBrand1, I want to record the id of that brand on the database.(As in Tbl.2) Here my Product models: class Product(models.Model): id = models.AutoField(primary_key=True) author = models.ForeignKey(User,on_delete= models.CASCADE, verbose_name='Product Author', null=True) brand_id = models.ForeignKey(Brand,on_delete=models.CASCADE, verbose_name="Brand Names") name = models.CharField(max_length=255, verbose_name="Product Name",unique=True) barcode = models.CharField(max_length=255, verbose_name="Barcode") unit = models.CharField(max_length=255,verbose_name="Product Unit") def __str__(self): return self.name Here my product views: @login_required(login_url="login") def addProduct(request): . . . . . elif … -
How to serialize and retrieve list of objects in Django Rest Framework?
I'm trying to retrieve a list of objects from my API, but even though they are properly stored in the Database from a script separate from the Django app, I am unable to read the list of objects properly and it gets converted to OrderedDic like so: -
send request from signal
I have an exam model that whenever an instance is created, instances of the Question model to the number that is specified in the Exam are created(using post_save signal). Also, I have a Go code that whenever a request is sent, fills out 3 fields of the Question model. My problem is how can I send this request in the signal part. The codes are as followed: models.py: class Exam(models.Model): title = models.CharField(max_length=255) subject = models.CharField(max_length=255, default='') organizer = models.CharField(max_length=255, default='...') description = models.TextField(max_length=1000) created_at = models.DateTimeField(auto_now_add=True) duration = models.DurationField() number_of_questions = models.PositiveSmallIntegerField() order = models.IntegerField(default=0) def __str__(self): return self.title class ExamQuestion(models.Model): exam = models.ForeignKey('ExamApply', on_delete=models.CASCADE) question_template = models.ForeignKey(QuestionTemplate, on_delete=models.CASCADE) text = models.TextField(max_length=5000, null=True, blank=True) question_params = models.JSONField(null=True, blank=True) answer_choices = models.JSONField(null=True, blank=True) answer_given = models.JSONField(default=dict, null=True, blank=True) correct_answer = models.JSONField(null=True, blank=True) data = models.JSONField(null=True, blank=True) is_correct = models.BooleanField(null=True) order = models.IntegerField(null=True, blank=True) def __str__(self): return str(self.id) class ExamApply(models.Model): class Status(models.TextChoices): CREATED = 'CR', 'Created' STARTED = 'ST', 'Started' FINISHED = 'FN', 'Finished' user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) exam = models.ForeignKey(Exam, on_delete=models.CASCADE) start_date = models.DateTimeField() end_date = models.DateTimeField() status = models.CharField(max_length=2, choices=Status.choices, default=Status.CREATED) def get_score(self): score = ExamQuestion.objects.filter(exam=self, answer_given=F('correct_answer')).count() return score signals.py: @receiver(post_save, sender=ExamApply) def create_examapply_examquestion(sender, instance, created, **kwargs): if created: … -
How to override a Model field without saving in Django
Suppose I have a model below : class Post(MainProcess, TimeStampedModel, SoftDeletionModel, models.Model): """Post model.""" slug = models.SlugField(default=uuid.uuid4(), unique=True, max_length=100) uuid = models.UUIDField(unique=True, max_length=500, default=uuid.uuid4, editable=False, db_index=True, blank=False, null=False) title = models.CharField(_('Title'), max_length=100, blank=False, null=False) image = models.ImageField(_('Image'), upload_to='blog_images', null=True, max_length=900, blank=True) I wanted to override the image field values without using the save() function, what is the best approach here which will be efficient. -
How To Implement Streaming in video raising and comments in Django rest framework
I developed a web application contain app of videos, I want to make video uploaded and comments like tiktok and facebook in my application to be streaming with DRF is there any modules or github repos could i see it , -
Django Transaction.atomic() Vs SQLAlchemy session for bulk update
I'm trying to find the best way to bulk update a MySQL DB using python the current ways I have are: req_model.objects.bulk_update(update_queries, list(column_to_update)) in this method, the problem is the fetching part required for the update_queries which is a list of updated objects of the model through internet scouring, I found out about Django's transaction.atomic(): with transaction.atomic(): for key, value in user_ids_dict: model.objects.filter(id=key).update(some_value=value) another issue with this is that Django doesn't support composite primary keys other than specifying them in the metaclass the other method (which I currently use) is using SQLAlchemy sessions(this works but its very slow due to server limitations): self.init_session() self.execute_bulk_update(model, mappings) self.session.commit() model is a list of dicts that contain updates and mappings is an SQLAlchemy model is atomic() faster than the session? I'll also gladly accept any other better suggestions for bulk-updating tables. -
using both MySQL and PostgreSQL in Django
I have a heavy-traffic website with a lot of users and posts and some other additional Features. and I want to redesign it using Django with DRF and vue.js. while I am searching for what is better to use between PostgreSQL and MySQL as the progect database I read that MySQL is better on performance if it read-only data. and PostgreSQL is better at doing queries. a- so I wanted to use MySQL to save posts on it which is read-only data as I think so. b- and save everything else in PostgreSQL. 1- is a & b a good idea to get a better performance for my website or just work with one database only? 2- can i link between those two databases -
Django Website does not load static files
I am in the middle of creating a django project and I have templates and static folders within the project directory. I can render and view the html files however it cannot load css files stored in the static folder. I have placed the load static tag in my html file but when I run python manage.py runserver it I get this error Performing system checks... Watching for file changes with StatReloader System check identified some issues: WARNINGS: ?: (staticfiles.W004) The directory '/static' in the STATICFILES_DIRS setting does not exist. System check identified 1 issue (0 silenced). December 08, 2022 - 14:54:53 Django version 4.1.3, using settings 'brighterstrat.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. This is how I have referenced the static files in my html file <link rel="stylesheet" href="{% static 'css/bootstrap.min.css'%}"> <link rel="stylesheet" href="{% static 'css/style.css'%}"> setting.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [os.path.join(BASE_DIR, '/static')] STATICFILES_STORAGE = "django.contrib.staticfiles.storage.StaticFilesStorage" How can I make it load the css files -
my image is not storing on submit in django
When i submit my form having image it is not saving in any folder and when i submit it from django admin panel it is saving this is my models.py class dish(models.Model): dish_id = models.AutoField dish_name = models.CharField(max_length=255, blank=True, null=True) dish_category = models.CharField(max_length=255, blank=True, null=True) dish_size = models.CharField(max_length=7, blank=True, null=True) dish_price = models.IntegerField(blank=True, null=True) dish_description = models.CharField(max_length=255, blank=True, null=True) dish_image = models.ImageField(upload_to="", default=None, blank=True, null=True) dish_date = models.DateField() def __str__(self): return self.dish_name this is my setting.py STATIC_URL = 'static/' MEDIA_URL = 'images/' DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' MEDIA_ROOT = os.path.join(BASE_DIR, 'card/static/images') this is my view.py def index(request): if request.method == "POST": dish_name = request.POST.get('dish_name') dish_size = request.POST.get('dish_size') dish_price = request.POST.get('dish_price') dish_description = request.POST.get('dish_description') dish_image = request.POST.get('dish_image') dish_category = request.POST.get('dish_category') item = dish(dish_name = dish_name, dish_size = dish_size, dish_price =dish_price, dish_description = dish_description,dish_category=dish_category, dish_image=dish_image, dish_date = datetime.today()) item.save() dishs = dish.objects.all() params = {'dish': dishs} return render(request, "card/index.html", params) this is my form <form method="post" action="/index"> {% csrf_token %} <div>Dish name: <input name="dish_name" type="text" placeholder="Dish name"></div> <div>Dish category: <input name="dish_category" type="text" placeholder="Dish category"></div> <div>Dish size: <input name="dish_size" type="text" placeholder="Dish size"></div> <div>Dish price: <input name="dish_price" type="text" placeholder="Dish price"></div> <div>Dish description: <input name="dish_description" type="text" placeholder="Dish description"></div> <div>Dish image: <input name="dish_image" type="file"></div> <button type="submit" class="btn btn-success">Submit</button> …