Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i work on 2 models in a single Django view?
I have a Django app where users upload images and the images will be processed and saved in 2 models, the processed will be in a model and the preprocessed in another model. the processing function is called by just main(image_01.png) so the upload/analyse view will be with a formset right? as formsets act on 2 models/forms. so how can i really do this is just calling model.preprocessed.main() after calling the .save(commit=false) ? how can I write this effectively ? is there a better way to write this? and is there any example code? -
How to build an invoice system with custom features below using DJANGO
I am building a side project invoice app. I have an inquiry in regard with creating the invoice system. models.py class Product(models.Model): name = models.CharField(max_length=50) slug = models.SlugField(max_length=50, unique=True) price = models.DecimalField(decimal_places=2, max_digits=10) quantity = models.PositiveIntegerField(default=0) tax = models.DecimalField(decimal_places=2, max_digits=10) def __str__(self): return self.name def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Product, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('core:item_details', kwargs={'pk': self.pk }) @property def total_invoice(self): total = (self.price * self.quantity) / self.tax return round(total) class Invoice(models.Model): number = models.AutoField(primary_key=True) description = models.TextField(max_length=300, null=True) date = models.DateField(default=datetime.date.today) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='invoices') created = models.DateTimeField(auto_now_add=True, null=True) updated = models.DateTimeField(auto_now=True, null=True) product = models.ManyToManyField(Product, related_name='invoices') def __str__(self): return '{}'.format(self.number) def get_absolute_url(self): return reverse('core:invoice_details', kwargs={'pk': self.pk }) How can I implement the features below?? from the main menu of the invoice there is an ADD button for 1 and 2 individually. is_staff is the Manager who can : 1/ CUSTOMER: from ADD button number 1, select the user to be charged. (As soon as selected from that page, the manager is redirected to menu page and the user information selected is populated to menu) 2/ ITEM : Same scenario for choosing item but in this case you can select multiple items from pressing ADD … -
Is there a way to only show a field if specified using django-rest-framework?
I'm using django-rest-framework, https://www.django-rest-framework.org/api-guide/serializers/ Is there a way to show a field only if its specified in the ?field=X param? If I try this: class TopLevelJobSerializer(DynamicFieldsMixin, serializers.ModelSerializer): children_job_statuses = serializers.ReadOnlyField() class Meta: model = TopLevelJob # This inherits from Job, which has id, name fields = ('id', 'name') I get AssertionError: The field 'children_job_statuses' was declared on serializer TopLevelJobSerializer, but has not been included in the 'fields' option. The children_job_statuses is a property that takes a while to load. I only want to call this explicitly by calling /api/top_level_job/?fields=children_job_statuses How can I do this? Do I need a whole new serializer? -
O visual Studio não atualiza minhas mudanças no servidor
Quando modifico alguma coisa no código o Visual Studio não atualiza no servidor. Tenho que fechar e rodar ele novamente. Toda modificação que faço tenho que dá um CTRL C no terminal e python manage.py runserver novamente. Estou fazendo com Django -
Django. Data to xml
Please tell me what I'm doing wrong. I want the data published on the site to be generated on the .xml page. For this, I wrote in **views.py**, the following code: def xml(request): data = Foo.objects.all().filter(is_published=True) context = {'data': data} return render(request, 'export/template.html', context, content_type='application/xhtml+xml') My template.html: <feed> <generation-date>2019-08-01</generation-date> {% if data %} <offer> {% for i in data %} <internal-id="{{ i.id }}"> <type>{{ i.type }}</type> <price>{{ i.price }}</price> </offer> {% endfor %} {% endif %} </feed> The page is displayed without errors, but id, type, price generated empty. Question! The page is generated, but the data does not appear, what am I doing wrong? If I in general do everything wrong. Which way to go to unload site object data. Thank you in advance! -
How to save username in Django model?
I have a simple blog post model and I want to save the author name. My current code only saves the author as an empty value or the default value if it's provided. here is the model class Posts(models.Model): title = models.CharField(max_length=200) body = RichTextUploadingField() created_at = models.DateTimeField(default=datetime.now, blank=True) auther = models.CharField(max_length=200) # 'Post object' title fix def __str__(self): return self.title # 'Postss' plural fix class Meta: verbose_name_plural = "Posts" and here is the view @login_required def post_new(request): if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.save() return redirect('details', post.pk) else: form = PostForm() form = PostForm() return render(request, 'posts/post_edit.html', {'form': form}) -
Migration error at id in Django Rest Framework
I'm trying to create an api endpoint from my MongoDB database. Everything seems normal, but i keep getting the following error: MigrationError at /mymodel/ id I have no idea where is this coming from, since this is everything the error page says. Here is my model: class mymodel(models.Model): firstfield = models.FloatField() secondfield = models.FloatField() thirdfield = models.CharField(max_length=15) def save(self, *args, using=None, **kwargs): super(mymodel, self).save(*args, using='mydb', **kwargs) Serializers: class mymodelSerializer(serializers.ModelSerializer): class Meta: model = mymodel fields = ('firstfield', 'secondfield', 'thirdfield') def create(self, validated_data): return mymodel.create(**validated_data) My views: class mymodelList(generics.ListCreateAPIView): queryset = mymodel.objects.using('mydb').all() serializer_class = mymodelSerializer class mymodelDetail(generics.RetrieveUpdateDestroyAPIView): queryset = mymodel.objects.using('mydb').all() serializer_class = mymodelSerializer And my urls: path('mymodel/', views.mymodelList.as_view()), path('mymodel/<int:pk>/', views.mymodelDetail.as_view()), -
how to use javascript provided data into a django app?
I use intl-tel-input to make the users choose the country code to add phone numbers but the main problem is the phone numbers aren't saved with the code and that raises some errors and doesn't show the numbers formatted as I want. this is the js script I use to show the widget. <script> var input = document.querySelector("#phone"); window.intlTelInput(input,({})); </script> how can I change this to make the field also saves the country code to the data? -
Cannot assign [...] must be a "CustomUser" instance
I am building a Django application with a form, where a logged-in user, a composer, is able to submit a composition they wrote. For this reason, I'd like the 'composer' field of this composition to be already filled with their name, read-only. I have created a custom user model and linked it via the AUTH_USER_MODEL in the settings. When I create a new composition via the admin interface I have a drop-down list for the composer (showing the available users), and I can successfully create a new composition. While doing the same thing via the front-end, though, I get a 'Cannot assign "'1'": "Composition.composer" must be a "CustomUser" instance.' error. I've also tried with get_user_model() instead of 'settings.AUTH_USER_MODEL' in the Composition model, have tried with all the different ways of gathering the active user, for example putting request.user in a variable 'activeuser' in the context and setting the form manually with value="{{ activeuser }}", all to no avail. myapp/models.py: title = models.CharField(max_length=120) # max_length = required description = models.TextField(blank=True, null=True) composer = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) users/models.py: from django.contrib.auth.models import AbstractUser, UserManager class CustomUserManager(UserManager): pass class CustomUser(AbstractUser): pass settings.py: AUTH_USER_MODEL = 'users.CustomUser' myapp/views.py: active_user = request.user form = CompositionForm(request.POST or … -
Update DB data through form in django
I'm trying to add a form on my page that will update a certain field in my DB. This is what the template looks like: {% for row in mydb %} <form method="post" novalidate> {% csrf_token %} {% include 'main/includes/bs4_form.html' with form=form3 %} {{row.firstfield}} {{row.secondfield}} <button name="button3" type="submit" class="btn btn-danger style="background-color: red;">CANCEL</button></td> </form> {% endfor %} The for statements is to display each row of the data in my table in a single line. Near each line, there is a submit button. When this button is clicked, the field secondfield is updated with the value New Value, as you can see in my form. Thi is the part of the view involved: def myview(request, tvticker): row = mydb.objects if request.method == 'POST': ... if 'button3' in request.POST: form3 = form = UpdateForm(request.POST) if form3.is_valid(): profile = form.save(commit=False) profile.save() messages.success(request, f"Success") ... render(request, "main/mytemplate.html", context={'row': row,}) And here is the form: class UpdateForm(forms.ModelForm): SomeField = forms.CharField() class Meta: model = MyModel fields = ("SomeField",) def save(self, commit=True): send = super(UpdateForm, self).save(commit=False) send.secondfield = 'New Value' if commit: send.save() return send My actual code it's not working, is seems to send a POST request but the secondfield value is not updated. For … -
When data post to django api, ConnectionResetError: [Errno 54] occur
I'm recently learning how to use django as backend, and let react redux handle frontend. But when I try to implement login function in frontend, and post data to api, ConnectionResetError: [Errno 54] occurs. I used django's User model to create user, and used rest_framework to create API for login. Then, using react with redux as frontend. When user login, it will trigger reducer to implement a login action with axios.post, but the serverside keeps showing errors. When I just login on API view page, it works fine. So I think the problem is with frontend, but I couldn't figure it out. my API for login class LoginAPIView(generics.GenericAPIView): serializer_class = LoginSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1] }) my redux action to login export const login = (username, password) => dispatch => { const config = { headers : { "Content-Type": "application/json" } }; const body = { "username" : username, "password" : password } axios.post("/api/auth/login", body, config) .then(res => { dispatch({ type: LOGIN_SUCCESS, payload: res.data }); }).catch(err => { console.log(err); dispatch({ type: LOGIN_FAIL }) }); }; And in my Login.js Component onSubmit = e => { … -
How to allow user to edit only object created by self?
I have a custom user model implemented in my pigeon management app and I want to allow user to edit only pigeon added by self. In backend every user can see only pigeon that are his own based on filter. My problem is that a user can edit all pigeon in the database if they pass to the url an aleatory number that corespond to a pigeon pk in the database. # Pigeon Model class Porumbei(models.Model): id_porumbel = models.AutoField(primary_key=True) data_adaugare = models.DateTimeField(default=timezone.now, null=True, blank=True) crescator = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True) serie_inel = models.CharField(max_length=25, null=False, blank=False, unique=True, help_text="Seria de pe inel. Ex: RO 123456") ... # My url path('porumbei/editare/<int:pk>/', porumbei.views.editareporumbei, name='editareporumbei') # I try somethin like this class Crescatori(admin.ModelAdmin): def has_change_permission(self, request, obj=None): if obj is not None and obj.crescator != request.user: return False return True def has_delete_permission(self, request, obj=None): if obj is not None and obj.crescator != request.user: return False return True I use login required to protect the views but I don't know how to deny a user to edit a pigeon that he don't own. 'To be more coincise, lets suppose that user A has added a pigeon with pk 5 and user B added a pigeon with … -
How to Deny Permission to sub-user to edit only one field and only admin has control to access it...?
Here is My Django Model type_choices = [ ('Yes', 'Yes'), ('no', 'no'), ] verified= models.CharField(max_length=50,default='----',choices=type_choices) name = models.CharField(max_length=50, default='', validators=[MinLengthValidator(4)]) age= models.TextField(max_length=5000, default='') I have a record called Verified and I have to Deny Permission to use the record to all Users and this record should only be used by Admins. Can you help me how to restrict other users to change this record and only readable and admin should have the privilege to change the values of the record? -
How to create a timer in an html table by using timestamp from django model?
I am trying to create a vehicle dashboard in django which lets user enter the vehicle details. When the model is saved the Checkintime is saved by auto_now_add = true. Now I also want to create a timer which tells how much time elapsed from the time the vehicle was checked in. I have tried parsing the date time to a javascript variable and then create a timer but without any luck. it either gives me a invalid date or doesn't return anything. # Create your models here. class Checkin(models.Model): vehicle_num = models.CharField(max_length = 13, blank = True, null = True) Driver_name = models.CharField(max_length = 20, blank = True, null = True) AIPL1 = 'AIPL-1' AIPL2 = 'AIPL-2' AIPL6= 'AIPL-6' AIPL7 = 'SAMUDRA' OUTSOURCE = 'OUTSOURCE' BU_CHOICES=( (A1,'A1'), (A2,'A2'), (A6,'A6'), (A7,'A7'), (OS,'OS'), ) BusinessUnit = models.CharField( max_length = 20, choices = BU_CHOICES, default = 'AIPL1' ) Loading = 'Loading' Unloading = 'Unloading' Type_Choices = ( (Loading,'Loading'), (Unloading,'Unloading'), ) Type = models.CharField( max_length = 20, choices = Type_Choices, default = 'Loading' ) CheckinTime = models.DateTimeField(auto_now_add = True) Can you please tell how can i calculate the difference between current time and the Checktime and display it in the html. -
After logging in (in my Django app) I get the 403 error
When I run my Django application (via python manage.py runserver) I get the login screen, however when I try to login it redirect me to the page that says: Forbidden (403) CSRF verification failed. Request aborted. Here is my settings.py """ Django settings for my_app project. Generated by 'django-admin startproject' using Django 2.1.5. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '...' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'cooking_book' ] 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', ] ROOT_URLCONF = 'my_app.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.static', 'django.template.context_processors.media', ], }, }, ] WSGI_APPLICATION = 'my_app.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), … -
Set django admin to display all the columns of the database
I am using django to create a website for my school project, but the thing is django admin doesn't represent its database like xamp does (tables, rows columns), instead it displays just one column. Is there anyway I can set it to bring out all the information in the database just like in xamp or wamp -
How create nested object in drf with validation?
I want to create nested objects with django-rest-framework serializers(drf). Initially, I create such serializers: class CollectionCreateSerializer(ModelSerializer): citizens = CitizenSerializer(many=True) ## Some definition of serializer fields def create(self, validated_data): collection = Collection.objects.create() citizens = validated_data.pop('citizens') for citizen in citizens: citizen_serializer = CitizenSerializer(data=citizen, context={'citizens': citizens) citizen_serializer.is_valid(raise_exception=True) citizen_serializer.save() return collection class CitizenSerializer(serializers.ModelSerializer): ## Some defenition of serializer fields def validate(self, attrs): print('in validate citizen') citizens = self.context['citizens'] ## Some validation logic with citizens context return super().validate(attrs) But that did not work, because validate method calls from create method, and before it when validation of collection happens. And the problem is that in the first case context contains 'request' and some other info. And in the second case context contains defined in create method context. So validate method on each citizen called twice with different context info. Then I tried to delete is_valid method from create method. And the next logical error occurred: You must call `.is_valid()` before calling `.save()`. Then I tried to make citizens value real-only to prevent internal validation. But then the citizens field is not included in the validated data in the create method. So I expect that some flag that turns off the internal nested objects validation? Or maybe … -
I need that when I click on an article <> it’s called the name of the article
I need that when I click on an article <> it’s called the name of the article For example, now, when I click on an article, I go to url address news / 1, but I need instead of 1, there was a name similar to this picture. Or here’s another premiere, I call the article “How to Skip School” and url the address will be like this news/how-to-skip-school views.py class ArticleIndex(ListView): model = Articles template_name = 'news/posts.html' def ArticleDetailView(request, pk): tag=None Articles.objects.filter(pk=pk).update(view=F('view') + 1) Articles.objects.all() article_details = Articles.objects.filter(pk=pk).first() if request.method == 'POST': comment_form = Comments(request.POST) comment_form.save() else: comment_form = Comments() commentss = CommentModel.objects.all() return render(request, 'news/post.html', {'article_details': article_details, 'comment_form': comment_form, 'comments': commentss, 'tag': tag }) urls.py path('', ArticleIndex.as_view(), name='articles_list'), path('<int:pk>/', views.ArticleDetailView, name='article_detail'), models.py class Articles(models.Model): title = models.CharField(max_length= 200) post = models.TextField() date = models.DateTimeField() img = models.ImageField(upload_to='', default="default_value",verbose_name='Каритинка 260х180') tags = TaggableManager() article_like = models.IntegerField(default='0') article_dislike = models.IntegerField(default='0') view = models.IntegerField(default='0') datesArticle = models.DateTimeField(auto_now=True) class Meta: ordering = ['-datesArticle'] def __str__(self): return self.title -
djongo.sql2mongo.SQLDecodeError: FAILED SQL: SELECT COUNT(*) FROM with mongodb django
I getting the below error on a select query with MongoDb in Django. SELECT COUNT(*) FROM (SELECT DISTINCT "datacollection_computed_host_details"."id" AS Col1, "datacollection_computed_host_details"."HOST" AS Col2, "datacollection_computed_host_details"."TYP" AS Col3, "datacollection_computed_host_details"."isBM" AS Col4, "datacollection_computed_host_details"."Kernal" AS Col5, "datacollection_computed_host_details"."os_version" AS Col6, "datacollection_computed_host_details"."SID" AS Col7, "datacollection_computed_host_details"."DBSID" AS Col8, "datacollection_computed_host_details"."IS_VLAB" AS Col9, "datacollection_computed_host_details"."ZHCODE" AS Col10, "datacollection_computed_host_details"."DC" AS Col11, "datacollection_computed_host_details"."SYSTEMROLE" AS Col12, "datacollection_computed_host_details"."MEMORY" AS Col13, "datacollection_computed_host_details"."EUDP" AS Col14 FROM "datacollection_computed_host_details" WHERE ("datacollection_computed_host_details"."IS_VLAB" = %(0)s AND "datacollection_computed_host_details"."SID" iLIKE %(1)s)) subquery ERROR : djongo.sql2mongo.SQLDecodeError: Version: 1.2.33 Django Version 2.1.8 Python 3.7.2 Background : I am working on a Django project that uses rest_framework_datatables for Datatable integration. I am able to receive the data in frontend and able to sort the data. But when I apply the search I am getting 500 in the Django side. It will be really great if you help me to solve this problem. I am stuck for more than a week 😥. I think its a MongoDB error : I saw reply in https://github.com/nesdis/djongo/issues/156 Since i am new to django and MongoDB i am unable to perform your solution. MongoDB error : djongo.sql2mongo.SQLDecodeError: FAILED SQL: SELECT COUNT(*) FROM (SELECT DISTINCT "datacollection_computed_host_details"."id" AS Col1, "datacollection_computed_host_details"."HOST" AS Col2, "datacollection_computed_host_details"."TYP" AS Col3, "datacollection_computed_host_details"."isBM" AS Col4, "datacollection_computed_host_details"."Kernal" AS Col5, … -
How to add link fields to serializer dynamically
I would like to create a general serializer for a ManyToMany link, which will include linked models data. from rest_framework import serializers def get_model_serializer(model, fields_to_serialize): class BaseSerializer(serializers.ModelSerializer): class Meta: model = model fields = fields_to_serialize return BaseSerializer def get_many_to_many_serializer(many_to_many_model, first_model, second_model, fields_to_serialize) serializer = get_model_serializer(many_to_many_model, fields_to_serialize) class BaseSerializer(serializer): pass # only when I directly set the attributes upon class definition it works #attendee = get_model_serializer(first_model)() #operation = get_model_serializer(second_model)() # This does not work setattr(BaseSerializer, first_model.__name__.lower(), get_model_serializer(first_model)()) setattr(BaseSerializer, second_model.__name__.lower(), get_model_serializer(second_model)()) #Or this #setattr(BaseSerializer, 'operation', get_model_serializer(first_model)()) #setattr(BaseSerializer, 'attendee', get_model_serializer(second_model)()) return BaseSerializer The problem is, that when I set the attribute using setattr, the linked models are not serialized. I guess there is some magic upon class creation or whatever? Any ideas, how can I go around this? -
Managing Accessibility of a user to other users profile pages
I'm new to django Need some advise to manage social network like website. Here is a problem. When a user logged in, in the all users page he sees himself among users. Need to manage that logged in user sees only other users. Thanks a lot -
Python Django | How to run and time running of other python scripts in background and see their log
I am new to Django and i would like to get an advise from someone experienced in it. What i am trying to do is basic application for controlling other Python scripts. For example, i have script n.1. I come to the application and click to run script n.1. The application will write me the log from the script (all the prints() or errors from the interpreter). But because the script n.1 can run long time i can leave the application and the script will continue running. When i came back to the application part, which controls script n.1., i would liked to see as it continues running with the whole log from the beggining. My idea is i will have to run these scripts asynchronous, right? What can i use in Django? What would be the best way to achieve this goal? There can run multiple this scripts in the background. Also i need solution, where it would be possible to run these scripts regularly in certain time the user sets. -
nginx Returning 500 for POST Image Request with Django Rest Framework
Preface I have done a lot of research for solutions to similar problems I have been having, but have still yet to solve this major problem I am experiencing. As a last resort, as a lot of cases seem application-specific, I have decided to create a post here with my configuration in the hope that someone may see a possible solution. Framework Django 2.1.7 nginx/1.14.2 djangorestframework==3.9.2 The Problem On my local setup of my server with the above framework, I can POST an image through my client app (specifically a react-native app, which is likely not important information) just fine. However, when trying to make the same POST request with the same image and URL path to my remote server, it returns the following 500 error (snapshotted from Google Chrome Console debugger). I have strongly deduced that nginx is the culprit for just image uploads, as the django logs of my remote server show no indication that it has even received the POST request, as my local server does. A normal POST request without image uploading, however, works just fine on both the remote and local server. What I Have Tried As found in other posts, I have increased the … -
slugify() got an unexpected keyword argument 'allow_unicode'
When I want to create new object from product I got this error: slugify() got an unexpected keyword argument 'allow_unicode' This is my models: class BaseModel(models.Model): created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True,) slug = models.SlugField(null=True, blank=True, unique=True, allow_unicode=True, max_length=255) class Meta: abstract = True class Product(BaseModel): author = models.ForeignKey(User) title = models.CharField() # overwrite your model save method def save(self, *args, **kwargs): title = self.title # allow_unicode=True for support utf-8 languages self.slug = slugify(title, allow_unicode=True) super(Product, self).save(*args, **kwargs) I also ran the same pattern for other app(blog) ,and there I didn't run into this problem. What's wrong with this app? -
404 error after submitting form with ImageField on Django admin
I have created a Django admin using documentation tutorial. I have created a model Author and added 2 CharFields and one ImageField. If I want to add a new author, the page admin/app/author/add/ works. I add everything and then, when I press Submit, I will be redirected on the same page admin/app/author/add/, but I will get the following error: Page not found (404) Request Method: POST Request URL: ******/admin/app/author/add/ Raised by: django.contrib.admin.options.add_view Using the URLconf defined in ******.urls, Django tried these URL patterns, in this order: - admin/ - app/ [name='index'] The current path, app/author/add/, didn't match any of these. The requested URL is admin/app/author/add/, but for some reason it searches for app/author/add/. I tried to remove the ImageField and everything works fine, so I assume that the problem is ImageField. I have installed Pillow. I have done everything about static and media files deployment. class Author(models.Model): name = models.CharField(max_length=200) role = models.CharField(max_length=200) image = models.ImageField(upload_to='images/authors/', blank=True, null=True) def __str__(self): return self.name