Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Test form __init__ with request from get_form_kwargs
How can I test UpdateUserForm.__init__ to check if payment_method field is in form depending of user.is_company_admin value? My try is in test_forms.py. Should I get form from response and check if this field exists? forms.py class UpdateUserForm(forms.ModelForm): def __init__(self, request, *args, **kwargs): super(UpdateUserForm, self).__init__(*args, **kwargs) if request.user.is_company_admin: del self.fields['payment_method'] else: self.fields['payment_method'].required = True ... views.py class UserUpdateView(LoginRequiredMixin, SuccessMessageMixin, UpdateView): form_class = UpdateUserForm model = User ... def get_object(self): return User.objects.get(pk=self.request.user.pk) def get_form_kwargs(self): kwargs = super(UserUpdateView, self).get_form_kwargs() kwargs.update({'request': self.request}) return kwargs test_forms.py def test_update_user_form_payment_method_in_fields(self): request = self.factory.get(reverse('users:update')) request.user = self.user middleware = SessionMiddleware() middleware.process_request(request) request.session.save() # response = views.UserUpdateView.as_view()(request) form = UpdateUserForm(request) if self.user.role == 'company_admin': print('payment_method' in form.fields) -
Django noob: AttributeError: 'module' object has no attribute 'index' (Official tutorial)
Traceback: Sahands-MBP-2:mysite sahandz$ python manage.py runserver Performing system checks... Unhandled exception in thread started by <function wrapper at 0x10e045c08> Traceback (most recent call last): File "/Library/Python/2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/Library/Python/2.7/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "/Library/Python/2.7/site-packages/django/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/Library/Python/2.7/site-packages/django/core/management/base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "/Library/Python/2.7/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/Library/Python/2.7/site-packages/django/core/checks/urls.py", line 16, in check_url_config return check_resolver(resolver) File "/Library/Python/2.7/site-packages/django/core/checks/urls.py", line 26, in check_resolver return check_method() File "/Library/Python/2.7/site-packages/django/urls/resolvers.py", line 254, in check for pattern in self.url_patterns: File "/Library/Python/2.7/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Library/Python/2.7/site-packages/django/urls/resolvers.py", line 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Library/Python/2.7/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Library/Python/2.7/site-packages/django/urls/resolvers.py", line 398, in urlconf_module return import_module(self.urlconf_name) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/sahandz/Documents/Programming/Learning Web development/Django/mysite/mysite/urls.py", line 20, in <module> url(r'^polls/', include('polls.urls')), File "/Library/Python/2.7/site-packages/django/conf/urls/__init__.py", line 50, in include urlconf_module = import_module(urlconf_module) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/sahandz/Documents/Programming/Learning Web development/Django/mysite/polls/urls.py", line 6, in <module> url(r'^$', views.index, name='index'), AttributeError: 'module' object has no attribute 'index' mysite/mysite/urls.py: from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^polls/', include('polls.urls')), url(r'^admin/', admin.site.urls), ] mysite/polls/urls.py: … -
Add user to ManyToManyField
I'm failing to add user into a ManyToManyField. Using Django 1.11. Following this documentation: https://docs.djangoproject.com/en/1.11/ref/models/relations/#django.db.models.fields.related.RelatedManager.set My template: <ul> {% for a in stories %} <li><a href="{% url 'story:add_story' a.id %}">{{ a }}</a></li> {% endfor %} </ul> My view: def add_story(request, park_id): story = get_object_or_404(Story, pk=story_id) story.users.add(request.user) stories = Story.objects.filter(users=request.user) context = { 'stories': stories, } return render(request, 'story/manage.html', context) My model: class Story(models.Model): story_name = models.CharField(max_length=550) users = models.ManyToManyField(User, related_name='subscriber') dateAdded = models.DateTimeField(auto_now_add=True) userAdded = models.ForeignKey(User) I can't figure out where I'm going wrong. I get no errors at all. -
manage.py makemigrations works but manage.py migrate did not
enter image description here how to solve the error.I first created the model with only one class and the makemigrations and migrate work perfect. but now i add another class in model but now migrate did not work the output is in pic. django version is 1.11 and i also register it in admin.py -
Django query for the below scenerio to get count
Table1 : **name status** shankar Good vimal Bad Sekar Good Shankar Good Shankar Good I would like to get count like this Good 2 Bad 1 Anyone help me find django query for the above scenerio -
something wrong with all-auth Facebook setting (Django Admin)
I'm getting 400 error when I pass the valid Facebook token to my localserver. Hint From my mobile(react native), I sent HTTP body of { access_token: "access_token }". Django 'Social Applications > App_name' Provider: Facebook Name: App_name Client id: App_ID from facebook developer console Secret key: Secret key from facebook developer console Choose sites: 10.0.2.15, 10.0.2.2, 127.0.0.1, localhost This is my server side (settings.py) - I had no problem with all features but facebook: ALLOWED_HOSTS = ['10.0.2.2','localhost'] AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ) Error from Postman: { "non_field_errors": [ "Incorrect value" ] } Thanks for reading -
Python mock patch syntax trouble with different arguments number
## tests file @mock.patch('profiles.models.create_stripe_charge', StripeMocks._mock_raises_stripe_error) def my_test(self): # ... stuff ## logic file def create_stripe_charge(customer, amount_in_cents, capture=True): # ... stuff ## mocks file class StripeMocks: def _mock_raises_stripe_error(self): raise stripe.error.StripeError When running my test, I got a _mock_raises_stripe_error() takes 1 positional argument but 3 were given' error. I understand that I'm trying to mock a 3-args method with a 1-arg method, but what if I just want to tell Python: please, no matter how many arguments my create_stripe_charge method has, I just want to simulate that it raises an Exception. What is the correct syntax to do this? Thanks. -
Django: Adding more fields to each ManyToMany Field option
Is It possible to add one or more Char Fields to each ManyToMany field option? Currently My model looks like this My Models: class engineeringUni(models.Model): field2 = models.CharField(max_length=200) des_eng = models.CharField(max_length=1000, default='Add description') def __str__(self): return self.field2 def description_eng_universities(self): return self.des_eng class engineering_courses(models.Model): course_name = models.CharField(max_length=400) course_description = models.CharField(max_length=1000, default='This is a description') course_offered_by = models.ManyToManyField(engineeringUni, related_name='course_offered_by') course_duration = models.IntegerField(blank=False, default='2') def __str__(self): return self.course_name def description_course(self): return self.course_description def offered_by_courses(self): return self.course_offered_by def duration_courses(self): return str(self.course_duration) As you can see in the image, I have the options in the ManyToMany field. Those options are: University 1 University 2 University 3 What I want to have is an additional text (Char) field next to each of these options (University 1, University 2, University 3). Is this possible? -
Django: no module named settings
When I try to run python manage.py runserver I get this error: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Users/user/lokvi/lokvi_env/lib/python2.7/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/Users/user/lokvi/lokvi_env/lib/python2.7/site-packages/django/core/management/__init__.py", line 307, in execute settings.INSTALLED_APPS File "/Users/user/lokvi/lokvi_env/lib/python2.7/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/Users/user/lokvi/lokvi_env/lib/python2.7/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/Users/user/lokvi/lokvi_env/lib/python2.7/site-packages/django/conf/__init__.py", line 110, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named settings I have python 2.7 in my virtualenv. I noticed strange thing at the last lines of my stack trace, the line before the last line has path that goes like that: /lokvi_env/lib/python2.7 etc But the last line goes like that System/Library/Frameworks etc, so it seems like path has changed from virtualenv to system. Is it ok? -
Fetching Salesforce Attachment content with django-salesforce
Basically I need to make attachments in SF available for download on my django app (using django-salesforce), from what I see on the Attachment model I can access the rest URL for the body, but is it there a way I can get the actual content of the attachment without having to implement an oauth client just for this? -
Run terminal commands from python using Subprocess
I'm trying to run a terminal command from my django but getting an error. Here's the command I want to run: kubectl apply -f <(istioctl kube-inject -f FILE_PATH) Here's what I have tried: From views.py nodesvc = subprocess.call('kubectl apply -f <(istioctl kube-inject -f ' + os.path.join(path) + '/nodeService.yaml)', shell=True) I'm creating a file in temporary directory and pass it's path here, which is correct. Here's the error : /bin/sh: -c: line 0: syntax error near unexpected token `(' /bin/sh: -c: line 0: `kubectl apply -f <(istioctl kube-inject -f /var/folders/g2/8fzl8mjj5xxfqdfvrl7v3q_40000gn/T/tmpstfcq3es/nodeService.yaml)' I think that something wrong with curly braces '(', How can I resole this issue, help me please! Thanks in advance! -
Django IntegrityError with DateField - when creating objects with get_or_create
I'm having an issue with Django's get_or_create, when ever I create same objects with same dates integrity error pops up. I have field in my model as follows. class Cart(models.Model): created = models.DateTimeField( pgettext_lazy('Cart field', 'created'), auto_now_add=True) last_status_change = models.DateTimeField( pgettext_lazy('Cart field', 'last status change'), auto_now_add=True) user = models.ForeignKey( settings.AUTH_USER_MODEL, blank=True, null=True, related_name='carts', verbose_name=pgettext_lazy('Cart field', 'user')) email = models.EmailField( pgettext_lazy('Cart field', 'email'), blank=True, null=True) def add(self,hoarding, date_from, date_until): cart_line, created = self.lines.get_or_create( hoarding=hoarding,date_from=date_from,date_until=date_until) class CartLine(models.Model): cart = models.ForeignKey( Cart, related_name='lines', verbose_name=pgettext_lazy('Cart line field', 'cart')) hoarding = models.ForeignKey( Hoarding, related_name='+',blank=True, null=True, verbose_name=pgettext_lazy('Cart line field', 'hoarding')) date_from = models.DateField(blank=True, null=True, verbose_name=pgettext_lazy('Cart line field', 'from')) date_until = models.DateField(blank=True, null=True, verbose_name=pgettext_lazy('Cart line field', 'until')) error arises when i try to add same objects to cart with same from-date and until-date: IntegrityError at /hoardings/hoardings-demo-2-5/add/ UNIQUE constraint failed: cart_cartline.cart_id, cart_cartline.date_from, cart_cartline.date_until get_or_create will return an IntegrityError when creating objects with same dates.I added unique features in datefield but got the same error. So I'm wondering if there's any other solution. I use Django 1.11 and Python 2.7 I reset database few times but it doesn`t help, db is Postgres/sqlite. -
How to set SMTP for customer in production?
What is the best practice for setting customer's SMTP in Django? Can I make them to set itself? I can't do that inside settings, otherwise they would have to tell me their password. EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'futilestudio@gmail.com' EMAIL_HOST_PASSWORD = '*****' Is there a way? Maybe allow them to set credentials through Django admin? -
Render XML Sitemap from Django View
The following code in a Django view: def sitemap(request): return render(request, 'sitemap.xml', content_type = 'text/xml') yields the following error: Exception Type: UnicodeDecodeError Exception Value: 'utf8' codec can't decode byte 0xff in position 0: invalid start byte How can I resolve this? All I'm trying to do is to render an XML sitemap. Any help would be appreciated. Thanks. -
django-nested-inline missing fields when adding new inline row
In our project, i've been making use of the latest version of django-nested-inlines v0.3.7 with django 1.7 I have the following definition in my django admin to display the inlines class SpecsGroupedContentInline(NestedStackedInline): model = SpecificationGroupedContent extra = 1 fk_name = "specification" fields = ["field_unit"] class SpecsContentInline(NestedStackedInline): model = SpecificationListContent extra = 1 fk_name = "specification" fields = ["content"] class SpecsInline(NestedStackedInline): model = Specification inlines = [SpecsContentInline, SpecsGroupedContentInline] extra = 1 fk_name = "product" class ProductAdmin(NestedModelAdmin): inlines = [ SpecsInline ] list_display = ('name', 'sku') form = ProductAdminForm When the page loads, the page looks like this Initial product page load It's a bit hard to see but the specs section has a title, an inline for Listed Contents and an inline for Grouped Contents. Afterwards, there's an empty Specs section with an empty title, empty Listed Contents, and empty Grouped Contents. When I press the "Add another Specification" button at the bottom of the Specification inline to add a new row, the result of the new entry looks like this New Specification entry image As you can see, the Grouped Content field "Field Unit" is missing. I'm not sure if my setup is incorrect, but i found this stack overflow … -
MS Edge not submitting form
I'm using django and bootstrap, and have a template which contains a form. The form is passed throught a view via context. I then display it as follows. Everything works in Mozilla FF, Chrome, IE, but not in Edge (I know I could ignore it, but due to other factors, Edge should work as well). Simply, after pressing on the input "Confirm" nothing happens. Like nothing would even be sent. Template file: <div class="box-body"> <form class="" accept-charset="utf-8" action="" method="POST"> {% csrf_token %} {{ form|crispy }} <div class="form-actions pull-right"> <input class="btn btn-primary" type="submit" name="submit" value="Confirm" /> <input class="btn btn-danger" type="button" value="Cancel" onclick="history.back()" /> </div> </form> </div> Thank you! -
Django .values() after F() expression filter
It seems that Django can not group values after you use a filter with an F() expression. For example: (models.py) class Athlete(models.Model): name = models.CharField(max_length=30) nationality = models.CharField(max_length=30) class TrainingSession(models.Model): training_date = models.DateTimeField() location = models.CharField(max_length=30) athlete = models.ForeignKey(Athlete) class Run(models.Model): run_time = models.IntegerField() training = models.ForeignKey(TrainingSession) (views.py) I want the number of runners for every location where they had their best run. r = Run.objects.all() # Annotate the best time from the training session and filter r = r.annotate(best_run_time = Min('trainingsession__run__run_time')) r = r.filter(run_time = F('best_run_time')) # Group by location r = r.values('location') r = r.annotate( athlete_count = Count('trainingsession_athlete', distinct=True)) When I don't use the F() expression, the .values('location') will group the result per location. However, when I use it, every location is given multiple time with an athlete_count of 1. -
defining the x-axis on ggplot using yearqtr
I am using the following sample data quarterly data. date rgdp cpi_qoq cpi_core m3 m2 m1 1996/1 221.54 35.007923 39.45 258.1 243.6 73.5 1996/2 217.95 36.029932 40.42 269.84 255.05 76.09 1996/3 238.44 37.377543 41.4 268.08 254.77 72.92 1996/4 240.18 37.768802 42.38 283.55 267.83 79.24 1997/1 222.14 39.556134 43.37 298.38 282.96 82.64 1997/2 218.54 41.621361 44.36 296.61 281.02 81.66 1997/3 239.08 40.607534 45.37 293.45 274.17 81.27 1997/4 240.82 40.949663 46.54 7615:26:24 294.05 91.06 1998/1 229.59 42.826062 46.01 311.08 288.07 86.66 1998/2 225.88 42.860627 47.93 314.6 291.23 89.78 1998/3 247.1 43.399143 48.72 318.31 296.15 89.95 1998/4 248.91 42.46247 48.1 328.32 303.75 94.72 1999/1 234.42 43.401984 48.01 340.56 313.69 103.66 1999/2 230.63 44.944958 50.82 340.62 309.8 104.79 1999/3 252.31 46.32018 53.29 336.83 302.98 103.42 date is character. i converted the date to yearqtr: newtime=as.yearqtr(bookk2$date, format="%Y/%q") book2=cbind(book2, newtime) plot: ggplot(data=bookk, aes(x=newtime, y=cbr))\ + geom_line(colour="red")\ + scale_x_yearqtr(format="%Y-Q%q", expand=c(0, 0))\ + theme(axis.text.x=element_text(angle=-30, hjust=.01)) the graph is ok but i have issues with the x-axis scale. i would love to view more periods(eg 2 quarters per year) and the starting point be 1996q1 (rather than 1995q1) i have perused many quesions but dont seem to get a perfect solution. any help out there? -
Sitemap in Django 1.10.7
I'm having issues getting the Django setup to generate a sitemap for me. I have added the following to my settings file 'django.contrib.sites', 'django.contrib.sitemaps', and im my urls.py file i have the following: from django.conf.urls import include, url from django.contrib import admin from cms.sitemaps import CMSSitemap from django.contrib.sitemaps.views import sitemap from ames import views admin.autodiscover() urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^contact/', include('contact.urls')), url(r'^news/', include('news.urls')), url(r'^sitemap.xml$', sitemap, {'sitemaps': {'cmspages': CMSSitemap}}), url(r'^$', views.home), url(r'^', include('cms.urls')), ] After deploying these files, I should be able to see the .xml file at /sitemap.xml but i'm getting a 404 error: Page not found (404) Request Method: GET Request URL: http://xxxxxxxxxxxxxx.co.uk/sitemap.xml/ Raised by: cms.views.details Using the URLconf defined in ames.urls, Django tried these URL patterns, in this order: ^admin/ ^contact/ ^news/ ^sitemap.xml$ ^$ ^ ^cms_wizard/ ^ ^(?P<slug>[0-9A-Za-z-_.//]+)/$ [name='pages-details-by-slug'] ^ ^$ [name='pages-root'] The current URL, /sitemap.xml/, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. Any thoughts greatly appreciated. -
Why pytest removes db records with reuse-db flag and scope=session after the first test case?
I use pre-created postgres database for my tests. Here the pytest setup: pytest.ini: [pytest] DJANGO_SETTINGS_MODULE = src.settings.testing norecursedirs = frontend static .svn _build tmp* addopts = --reuse-db testing.py: from .base import * DEBUG = True DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'db', 'USER': 'root', 'PASSWORD': 'pass', 'HOST': 'localhost', 'PORT': '5432', } } test fixtures: @pytest.fixture(scope='session') def user(): return User.objects.create(name='Test', ) test cases: import pytest pytestmark = pytest.mark.django_db def test_user(user): print(user.pk) # returns pk of newly created user print(User.objects.all()) # returns queryset with one user def test_user2(user): print(user.pk) # returns the same value as in the previous test print(User.objects.all()) # returns empty queryset I can't understand behavior of pytest fixtures. Model instance is created once per session and it is the same in several test cases. But actual db value is different. Pytest remove the user value after the first test case. How can I prevent that behavior and keep my db records saved for all test session? -
django admin panel list_display for foreign keys
how to link foreign key into appropriate admin change form in Django admin panel list display? I can't display foreign key in Django admin panel list display however force the link to go to appropriate admin change form -
Django template: Show a link only once if a user belongs in more than one groups
I have a template in django that shows a link if a user has group name different than patient. My code is: {% if user.is_authenticated %} {% for group in user.groups.all %} {% if group.name != 'Patient' %} <li {% if request.get_full_path == modules_url %} class="active" {% else%} class="inactive"{% endif %}> <a href="{% url 'modules' %}"><b style="color:#ff9904;">Modules</b></a> </li> {% endif %} {% endfor %} {% endif %} In case a user is a member of four different groups, the link Modules is shown 4 times in the template. Is there any way to show it only once? -
How can I put data is parsed from excel to model?
I parsed excel and get row data in list. It is like [empty:'', text:’1', text:’1’, text:’40’, text:''] [empty:'', text:’2’, text:’5’, text:’23’, text:’●’] [empty:'', text:’3’, text:’9’, text:’52’, text:''] My excel(data.xlsx) is so list output is ok.Now I wanna put this list to model(User). User model in models.py is class User(models.Model): user_id = models.CharField(max_length=200) name_id = models.CharField(max_length=200) age = models.CharField(max_length=200) man = models.BooleanField() The last code of man = models.BooleanField() means man or woman,if ’●’ in excel,it means the user is man and true wanna be put in man variable. Now views.py is #coding:utf-8 from django.shortcuts import render import xlrd book = xlrd.open_workbook('../data/data.xlsx') sheet = book.sheet_by_index(1) for row_index in range(sheet.nrows): row = sheet.row(row_index) print(row) # I had to add codes connect controller & model I do not know how to send these list data to model and model has these data.Strictly speaking,I wanna write these list data to sqlite3.Is this code import app.models for x in row: User.user_id = row[1] User.name_id = row[2] User.age = row[3] User.man = row[4] good way to write model?(or is it wrong way?) Is there other more efficient way to do it? -
How to write query with in a model with foreign key relation?
class Categorie(models.Model): name = models.CharField(max_length=200) description = models.TextField(max_length=2000) status = models.BooleanField(default=True) added_date = models.DateTimeField(auto_now_add=True) def __unicode__(self): return u'%s' % self.name class GroupQuestion(models.Model): category = models.ForeignKey(Categorie, related_name='%(class)s_name_related', null=True) name = models.CharField(max_length=200) added_date = models.DateTimeField(auto_now_add=True) status = models.BooleanField(default=True) class Meta: verbose_name = 'Group of Questions' verbose_name_plural = 'Group of Questions' def __unicode__(self): return u'%s' % self.name class Question(models.Model): category = models.ForeignKey(Categorie, related_name='%(class)s_name_related', null=True) group = models.ForeignKey(GroupQuestion, related_name='%(class)s_name_related') name = models.TextField(max_length=200) added_date = models.DateTimeField(auto_now_add=True) status = models.BooleanField(default=True) #select_choice = models.CharField(max_length=5, choices=QUESTION_CHOICES, null=True) positive_answer = models.PositiveIntegerField() negative_answer = models.PositiveIntegerField() def __unicode__(self): return u'%s' % self.name I have these three model. When I pass category_id from my API wants to get QuestionGroups and Questions related to that group? Some thing like this "data": [ { id:1 name = ABC "question":[ { "id":1 "name":ABC } { "id":1 "name":ABC } ] } { id:1 name = ABC "question":[ { "id":1 "name":ABC } { "id":1 "name":ABC } ] } } I am new in django some can help me how to write query in view and how to serialize data. -
FileField doesn't appear in template [Django, Python]
I was searching for answer for hours, but couldn't find an answer :( I have problem with displaying FormField in my template. If I change attachment = forms.FileField(required=False) to attachment = forms.CharField(widget=forms.Textarea) CharFiels displays correctly. HERE'S MY CODE: If someone prefers, here is code on paste.ofcode.org: https://paste.ofcode.org/xpJsKa4PWTAXe7Jsy24qEs forms.py class NotificationMessageForm(forms.Form): content = forms.CharField(widget=forms.Textarea) attachment = forms.CharField(widget=forms.Textarea) views.py @login_required def notification_details(request, pk): notification = Notification.objects.get(pk=pk) notification_messages = NotificationMessage.objects.filter(for_notification=pk).order_by('created_date') notification_message_form = NotificationMessageForm() if request.method == 'POST': notification_message_form = NotificationMessageForm(request.POST, request.FILES) if notification_message_form.is_valid(): content = notification_message_form.cleaned_data['content'] for_notification = notification author = request.user created_date = timezone.now() attachment = notification_message_form.cleaned_data['attachment'] notification_message_to_save = NotificationMessage(content=content, for_notification=for_notification, author=author, created_date=created_date, attachment=attachment) notification_message_to_save.save() return render(request, 'panel/notification-details.html', {'notification': notification, 'notification_messages': notification_messages, 'notification_message_form': notification_message_form}) template.html <form method="POST" enctype="multipart/form-data"> <div class="form-group"> <label for="exampleInputEmail1">Treść wiadomości:</label> {{ notification_message_form.content|add_class:"form-control" }} <small id="emailHelp" class="form-text text-muted"></small> </div> <div class="form-group"> <label for="exampleInputFile">Załącznik</label> {{ notification_message_form.attachment }} <small id="fileHelp" class="form-text text-muted">Opcjonalnie</small> </div> <button type="submit" class="btn btn-primary" value="Submit">Wyślij wiadomość</button> {% csrf_token %} </form> Please, help me :( I would be very grateful for your help.