Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework and Knox Login view works with Postman but returns 400 with Vue.js
I created a backend API using Django, django-rest-framework and Django-rest-knox, I am also using Vue.js for my frontend. Serializers.py class LoginUserSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() def validate(self, data): user = authenticate(**data) if user and user.is_active: return user raise serializers.ValidationError("Invalid Details.") Views.py class LoginAPI(generics.GenericAPIView): authentication_classes = [BasicAuthentication] permission_classes = [permissions.AllowAny] serializer_class = LoginUserSerializer 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] }) Urls.py urlpatterns = [ path('api/login/', LoginAPI.as_view(), name='login') ] Vue.js action in store.js const requestOptions = { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: { username: { username: authData.username }, password: { password: authData.password } } } fetch(`${baseURL.domain}/login/`, requestOptions) .then(response => response.json()) .then(response => { console.log('Request Sent', response) localStorage.setItem('user', response.token) // store the token in localstorage }) .catch(err => { localStorage.removeItem('user') // if the request fails, remove any possible user token if possible }) }) The problem with this is that the code works very fine when I try it with postman, but whenever I run the API in the browser, it returns a 400 error. POST http://127.0.0.1:8000/api/login/ 400 (Bad Request) Error: Request failed with status code 400 -
how to get sum row into xls by xlwt
I have a tuple like t = ((a,b,1,2),(a,b,3,4),(a,c,1,3),(c,d,3,6)) I used xlwt's wb to write a .xls file. But now I neeed add a sum row below like: C1 | C2 | C3 | C4 a | b | 1 | 2 a | b | 3 | 4 a | c | 1 | 3 c | d | 3 | 6 total: | 8 | 15 How to do this? -
Can Django apps have separate localisation domains?
I'm building a group of websites that will each share two common apps. I want to be able to localise the text in each site, as per client requirements. Using i18n / l10n localisation is working well for this, but I'd like to separate out the translation strings for each app to make it both easier to manage, and prevent string clashes between apps. In other environments (e.g. WordPress) I can specify a separate domain for each app. From what I can tell, I've only got the domains 'django' (for all server-side code) and 'djangojs' (for browser JS). Is there some way of specifying a different domain for each app, so that I can split them appropriately? Sure, I can abuse the l10n context with pgtext() but that means I lose the ability to manage contextual differences within each app. I'd much rather use domains, which is what they're meant for, and keep contextual markers for their intended purpose. -
Django- How to check formset field values in ModelForm init?
I'm new to Django. I can check form data using if field in self.data and grab field value like product_id = int(self.data.get('product')) that's all I know. I really don't have any idea how to check dynamic formset data and grab field value in __init__ method. I did a lot of searching and didn't understand how to do it. Please help me to get out of it, I will be grateful. class PurchaseOrderForm(forms.ModelForm): class Meta: model = PurchaseOrder class PurchaseOrderDetailsForm(forms.ModelForm): class Meta: model = PurchaseOrder_detail fields = ('product', 'product_attr', 'order_qnty', 'recvd_qnty', 'amount_usd', 'amount_bdt', 'unit_price', 'sales_price', 'commission_price') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if 'product' in self.data: product_id = int(self.data.get('product')) self.fields['product_attr'].queryset = ProductAttributes.objects.filter(product_id=product_id) PurchaseOrderItemsFormset = inlineformset_factory(PurchaseOrder, PurchaseOrder_detail, form=PurchaseOrderDetailsForm, fields='__all__', fk_name='order', extra=1, can_delete=True) Rendered Forms: <table class="table"><input type="hidden" name="PurchaseOrder-TOTAL_FORMS" value="3" id="id_PurchaseOrder-TOTAL_FORMS"> <input type="hidden" name="PurchaseOrder-INITIAL_FORMS" value="2" id="id_PurchaseOrder-INITIAL_FORMS"> <input type="hidden" name="PurchaseOrder-MIN_NUM_FORMS" value="0" id="id_PurchaseOrder-MIN_NUM_FORMS"> <input type="hidden" name="PurchaseOrder-MAX_NUM_FORMS" value="1000" id="id_PurchaseOrder-MAX_NUM_FORMS"> <thead> <tr> <th>Product</th> <th>Product attr</th> <th>Order Qnty</th> <th>Recv. Qnty</th> <th>Amount ($)</th> <th>Amount (৳)</th> <th>Cost Price</th> <th>Sale Price</th> <th>Comm. Price</th> <th>Delete</th> </tr> </thead> <tbody> <tr class="formset_row-PurchaseOrder dynamic-form"> <td><input type="hidden" name="PurchaseOrder-0-order" value="1" id="id_PurchaseOrder-0-order"> <input type="hidden" name="PurchaseOrder-0-id" value="1" id="id_PurchaseOrder-0-id"> <div id="div_id_PurchaseOrder-0-product" class="form-group"> <div class=""><select name="PurchaseOrder-0-product" data-minimum-input-length="0" data-allow-clear="true" data-placeholder="" class="setprice product select2widget form-control django-select2 select2-hidden-accessible" style="width:100%" required="true" id="id_PurchaseOrder-0-product" data-select2-id="id_PurchaseOrder-0-product" tabindex="-1" aria-hidden="true"> … -
New Entry of Data overwrites all past entries in column , how do i correct this?
Using Django, when the User fills out the webform, one of the saved Data overwrites all pass entered data for that column. How do i stop it from overwriting it the other past data for that column ? Models.py file below, from django.db import models from django.utils import timezone from django.contrib.auth.models import User class ansquestions(models.Model): m_invested = models.CharField(max_length=100) p_return = models.CharField(max_length=100) years = models.CharField(max_length=100) inflation_yes_no = models.CharField(max_length=100) date_answered = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) results = models.ForeignKey('results', on_delete=models.CASCADE, null=True) # null=True def __str__(self): return self.m_invested + ' ' +self.p_return class results(models.Model): # second table for output and add other data from ansquestions table as foreign keys r_output = models.CharField(max_length=500) author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) def __str__(self): return self.r_output # Important : this dunder method above __str__(self) for r_ouptput was how the actual r_output value gets displayed on admin interface. important since it was foreign key Here is the 2nd View Function, This is where i'm having the trouble with the latest.objects('id') command, i found this as a solution, but it's overwriting all of the rows for that "Results" Column def formulafv(request): if makeup_infl=='no': i_return = (float(perc_r)) elif makeup_infl=='yes' and int(years_i)<=5: i_return = (2+float(perc_r)) elif makeup_infl=='yes' and int(years_i)>5 and int(years_i)<=9.99 … -
How to connect Django media storage to Dokku persistence storage?
I deployed my Django app on server with Dokku. Staticfiles seems to be working as CSS is perfectly fine in admin dashboard, I can upload file but I cannot reach the file. I discovered that I should be using Dokku persistence storage anyway. So I set it up (I suppose). Then I setup my Nginx. Before Nginx, Django was showing "page not found" for the file path. Now, I get "The page you were looking for doesn't exist.". How can I correctly connect my app to persistence storage? Static and media settings on Django # STATIC # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#static-root STATIC_ROOT = str(ROOT_DIR / "staticfiles") # https://docs.djangoproject.com/en/dev/ref/settings/#static-url STATIC_URL = "/static/" # https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS STATICFILES_DIRS = [str(APPS_DIR / "static")] # https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders STATICFILES_FINDERS = [ "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", ] # MEDIA # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#media-root MEDIA_ROOT = str(APPS_DIR / "media") # https://docs.djangoproject.com/en/dev/ref/settings/#media-url MEDIA_URL = "/media/" Nginx media.conf settings location /media/ { alias /var/lib/dokku/data/storage/dokkuappname:/media; } dokku storage:list dokkuappname result dokkuappname volume bind-mounts: /var/lib/dokku/data/storage/dokkuappname:/media -
use variable in django DB subquery
I have been working on this but I can't seem to get there. I would like to make a query that will do the calculations in the database, store the results in variables I can pull back into Django environment. Objective is: qs = TimeLog.objects.filter(user_id=1, date__gte='2021-01-01').values() run a subquery on qs to calculate: 2a) Sum the hours_worked for the year(year_hours) 2b) Sum the wages for the year (year_wages) 2c) Sum the hours_worked for the the current month (month_hours) 2d) Sum the wages for the current month (month_wages) Here are some of things I have been trying qs.aggregate(Sum('wages')) qs.aggregate(year_wages=(F('time_worked') * F('hourly_rate'))) qs.filter(date__lte='2021-01-01').aggregate(Sum('wages'), Sum('time_worked')) Is there a way to do this in one query using DB expressions like F expression or Q objects or any other way so that it is handled by the DB and pull the variables (year_hours, month_hours, year_wages, month_wages) back in Django environment. Thanks in advance. NOTE I'm using PostgreSQL. -
Should I make 2 Form for readonly and update Django
I have a form for an account and I wish to make it ReadOnly and Updatable. Should I make a separate form for readonly then load them create a separate view? Or is there a DRY solution for this? -
How to override admin's password change view logic?
Django docs says to use path('accounts/', include('django.contrib.auth.urls')) but I don't want it to have "accounts/" url instead I only want it to remain as "admin/". However I tried overriding it as seen like so # project urls.py urlpatterns = [ path('admin/', admin.site.urls), path('admin/password_change/', CustomPasswordChangeView.as_view(), name='password_change'), ] from django.contrib.auth.views import PasswordChangeView from django.contrib.auth.forms import PasswordChangeForm class CustomPasswordChangeView(PasswordChangeView): form_class = PasswordChangeForm success_url = reverse_lazy('password_change_done') template_name = 'registration/password_change_form.html' title = _('Password change21312312313132133') def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs['user'] = self.request.user print(kwargs['user']) print(self.success_url) return kwargs def form_valid(self, form): form.save() # Updating the password logs out all other sessions for the user # except the current one. update_session_auth_hash(self.request, form.user) return super().form_valid(form) I tried to change the title variable value so that I would see if it worked but it doesn't seem to use the custom view that I've made. Any idea why and how to fix it? -
Django admin postgres Error: must appear in the GROUP BY clause
I have below django model, class DetectionJob(models.Model): """A detector job """ owner = models.ForeignKey(Account, on_delete=models.CASCADE) media = models.ForeignKey(UploadedMedia, related_name='jobs', on_delete=models.CASCADE) detector_api_id = models.CharField( max_length=36, blank=True, help_text="Detection API Task ID (UUID)", ) FACE_MANIPULATION = 'face_manipulation' And below django admin page, class DetectionJobAdmin(admin.ModelAdmin): readonly_fields = ('created_at', 'updated_at') admin.site.register(DetectionJob, DetectionJobAdmin) I am keep getting below error, column "detector_detectionjob.id" must appear in the GROUP BY clause or be used in an aggregate function LINE 1: SELECT "detector_detectionjob"."id", "detector_detectionjob"... I am using postgres as database. There are multiple links on which people ask about similar error but I did not find anything relevant to my problem. Kindly advise what I am doing wrong? -
How can I get the username of the logged in user in Django?
I'M new to Django, looking to get first name and last name of the logged-in user in Django, login method am using LDAP authentication. when i login as admin i was able to see the LDAP user in User information tab. Tried request.user.first_name didn't work, is there any other method to get the details? -
How to deal with Nan Values in Postgresql with Django REST API
I have copied a pandas dataframe to PostgreSQL, Now the DB has Nan Values entered by the df, this is easy to solve in pandas but i was wondering how to do this in a DB as i have a huge DB and dont want to again write data to DB. The Django REST Framework is throwing the error 'Out of range float values are not JSON compliant: nan'. I'm using React at the frontend. -
Django model instance of abstract model class raises error when calling super()
I have an abstract model: class CustomModel(models.Model): update = True class Meta: abstract = True def delete(self, *args, **kwargs): try: super().delete(*args, **kwargs) except models.ProtectedError as e: protected_objects_to_return = '' first = True for protected_object in e.protected_objects: if not first: protected_objects_to_return + '/' first = False protected_objects_to_return = protected_objects_to_return + "[{}]{}".format(protected_object._meta.verbose_name, protected_object) raise CustomValidation(_("No fue posible eliminar el registro porque existen registros dependientes: {}".format(protected_objects_to_return)), self.__class__.__name__, status.HTTP_400_BAD_REQUEST) And a model class derived from the abstract class: class Family(CustomModel): name = models.CharField(max_length=100, unique=True, verbose_name=_("Nombre de Familia")) code = models.CharField(max_length=10, verbose_name=_("Clave")) commission = models.PositiveIntegerField(null=True, blank=True,default=0, verbose_name=_("Comisión")) length_field = models.PositiveIntegerField(null=True, blank=True, verbose_name=_("Longitud de Campo")) type_field = models.CharField(max_length=20, choices=FIELD_TYPE_CHOICES,default='ALPHANUMERIC', verbose_name=_("Tipo de Campo")) commission_type = models.CharField(max_length=30, choices=COMISSION_TYPE_CHOICES,default='FIXED_COMMISSION', verbose_name=_("Tipo de Comisión")) is_commission = models.BooleanField(default=False, verbose_name=_("Tiene Comisión?")) tabulator = models.OneToOneField(Tabulator, null=True, blank=True, on_delete=models.PROTECT, related_name='family', verbose_name=_("Tabulador")) product_or_service_sat = models.ForeignKey(ProductServiceSAT, null=True, blank=True, on_delete=models.PROTECT, related_name='families', verbose_name=_("Producto o Servicio SAT")) unit_of_measure_sat = models.ForeignKey(UnitOfMeasureSAT, null=True, blank=True, on_delete=models.PROTECT, related_name='families', verbose_name=_("Unidad de Medida SAT")) is_active = models.BooleanField(default=True, verbose_name=_("Esta Activo?")) code_tc = models.PositiveIntegerField(null=True, blank=True, verbose_name=_("Código de Migración")) class Meta: verbose_name = _("Familia") verbose_name_plural = _("Familias") def __str__(self): return "[{}] {}/{}".format(self.id, self.name, self.tabulator) def save(self): if self.is_commission: if self.tabulator is None: self.tabulator = self.create_tabulator(self.name, self.commission_type) super().save() def create_tabulator(self, name, commission_type): tabulator = Tabulator(name=name, commission_type=commission_type) tabulator.save() return tabulator The … -
Allauth Account Management email addresses not listed in account_email view
I am working on my first django project with allauth and working through customising the allauth templates with my own styles. I have linked the user to the email.html template so that they can view the email addresses associated with their account. When I check this out on my deployed site there are no email addresses shown where it should list them. This is despite having checked 'verified' from admin panel. I can add a new email and it successfully shows in the admin panel and resend verification emails that successfully arrive in my mail box. Is there something I need to do in the settings somewhere to get the email set to show? -
Processing Django Migrations
We have a multiple database Django project that uses database routers. For some reason when we run a migration the reference to the migration end up in the django_migrations table but no actual migrations are actually run - that is - there is no change in target database. How can you manually force a migration to take effect? -
Django migration not applied to the DB
I had an Django2.2.3 app, it was working fine. But I had to chane the name of a field in a table, and add another field. Then I ran ./manage.py makemigrations && ./manage.py migrate. Besides the terminal prompt: Running migrations: No migrations to apply. No error is throwed. But then when I go to the MySQLWorkbench to check the database, it is exactly as I didn't make any change. I tried deleting the migrations and making again, the process ends with no errors but the database don't change. I create another empty database, change the name on settings.py and make migrations and migrate again, and it worked, but when I put the old database name on the settings, it just did not work. Can someone explain this behavior for me? There is any kind of cache for these information migrations or something? I realy want to know why this is not winrkig as I espect. -
how can I add a post as an admin?
I have a blog app in my project with posts. I am able to create posts if I go to the admin in the link, but I want to use CRUD. so if my user is a super user another option will appear to add posts. however I am not able to because it keeps saying that it cannot find the template.` I'm not sure what to add in the models and views. I've tried many things but it's still not working. would appreciate any help! here is my code: from django.urls import path from . import views urlpatterns = [ path('', views.posts, name='posts'), path('posts/<slug:slug>/', views.PostDetail, name='post_detail'), # path('add_post/', views.add_post, name='add_post'), ] views: def posts(request): """ A view to show all posts, including sorting """ posts = Post.objects.all() sort = None direction = None if request.GET: if 'sort' in request.GET: sortkey = request.GET['sort'] sort = sortkey if sortkey == 'title': sortkey = 'lower_title' posts = posts.annotate(lower_title=Lower('title')) if 'direction' in request.GET: direction = request.GET['direction'] if direction == 'desc': sortkey = f'-{sortkey}' posts = posts.order_by(sortkey) current_sorting = f'{sort}_{direction}' context = { 'posts': posts, 'current_sorting': current_sorting, } return render(request, 'blog/posts.html', context) -
How can I display my updated output in browser django
Hello guys hope you are fine... I want to ask something from you I really need help from you because I am stuck in this problem... I deployed my (django) app in heroku and in that app I used apscheduler which works fine (which basically get historical weather data from api and then train my model on that data and gives me predictions ) and I shows that new prediction values on console but not in browser which I wants to every time when my scheduler runs and got new prediction values then those new values should be shown on my browser instead of old values. How can I achieve this task?? Thanks in advance.... -
Django: Separate queryset into two sets
I have a Book class and a Wish class. Users can search for a book title and see a list of all users who have this book in their (available for trade) Book list. I want to separate this list into two lists of "perfect matches" and "possible matches". Perfect matches occur when another user has the book you are searching for in their Book list and your Book list contains at least one book from their Wish list. Possible matches are the rest of the users who have this book in their Book list. Here is the code I have so far: results = Book.objects.filter(Q(name__icontains=query)).distinct() books = Book.objects.filter(user=request.user) for result in results: wishes = Wish.objects.filter(user=result.user) matches = books.filter(name__in=wishes.values_list('name')) if not matches: print("Not a perfect match.") else: print("This is a perfect match!") How can I separate "results" into two separate querysets/lists of perfect matches and possible matches? -
Querying jsonb fields in PostgreSQL using Django: IN vs. CONTAINS
When Django's ORM translates a JSONB query using CONTAINS into SQL it uses the ->> operator which is working fine. For example, something like: "metadata__my_field_name__icontains": "1234" runs as: ...WHERE UPPER(("table"."metadata" ->> my_field_name)::text) LIKE UPPER(%9740253%)... which works great. However, when I try to use the IN operator and a list of values: "metadata__my_field_name__in": my_list the SQL generated uses the JSON, as opposed to JSONB operator like this: ..."table"."metadata" -> gbif_taxon) IN ('9405810', '2480631', ... While it runs, it does not return the expected values (empty set). By contrast, if I manually run the same query using the JSONB operator, ->>, the expected values are returned. The metadata field in this case is generated in a view using the jsonb_object_agg function (unmanaged by Django) and is defined in Django code as a JSONField() from django.contrib.postgres.fields. Is there a way to force Django to use the JSONB operator? -
Failed to fetch due to cors
I cant seem to make this alert in the console dissappear: Access to fetch at 'https://streamlabs.com/api/v1.0/user' from origin [mywebsite] has been blocked by CORS policy: Request header field access_token is not allowed by Access-Control-Allow-Headers in preflight response. I looked into already answered questions, but couldnt make it work. I have this in my settings.py: MIDDLEWARE = [ ... 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ] INSTALLED_APPS = [ ... 'corsheaders', ... ] ALLOWED_HOSTS = ['*'] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = False Also I tried removing 'django.middleware.clickjacking.XFrameOptionsMiddleware' to check if this was the problem, but still didn't work. Any ideas? This is my fetch: <script> window.onload = function() { fetch("https://streamlabs.com/api/v1.0/user", { method: "GET", headers: { 'access_token': '{{request.user.streamlabs_access_token}}', } }) .then(response => { console.log(response); }) .catch(err => { console.error(err); }); } </script> -
Django: Testing LoginView throwing AssertionError
Quesiton I'm building a testing suite for my login process and immediately ran into a hiccup. I believe the issue is that LoginView is a 'class' while the code is testing it as a function. What is the proper way to assert that the URL resolved to the LoginView? urls.py from . import views from users.views import * from django.urls import path from django.contrib.auth.views import LoginView, LogoutView from users.forms import LoginForm urlpatterns = [ path('', views.user_home_view, name='user_home'), path('sign_up', views.SignUpView.as_view()), path('login', LoginView.as_view(authentication_form=LoginForm), name='login'), path('logout', LogoutView.as_view(), name='logout') ] tests.py from django.test import SimpleTestCase from django.urls import reverse, resolve from django.contrib.auth.views import LoginView, LogoutView from users.forms import LoginForm from users.views import * # Create your tests here. class UrlTestCase(SimpleTestCase): def test_login_url_resolved(self): url = reverse('login') self.assertEquals(resolve(url).func, LoginView) Testing Results (./manage.py test) AssertionError: <function LoginView at 0x7f970ca05320> != <class 'django.contrib.auth.views.LoginView'> -
Django update part of page - Class based View
I'm having the following doubt: my app has a html with a navbar with all menu items and when you click in one of them, it refresh all page. This was made with {% extend %} and {% block %} for no-repeat code. In the back, I use default Django Views (CreateView, UpdateView, List..) with their basic function use.. get_context_data().. post().. Now, I need to update the page when you click any menu button, but ONLY should change de {% block %} content. Is not nice updating also menu and all page everytime you navegate. I tried using Ajax requesting the endpoint of any view and changing the DOM elements. It works in the front.. but when I submit, the backend obviosly still "thinking" in the previous class view and validate fields that NOT exist.. For example.. you are in Book html, creating one of them, then you click on Create Person.. html change.. but when submit, it still ask for Book Title.. Is there any nice way to do this?? I hope it understood! Thank u in advance! -
How to provide different sets of data to different users in django?
I'm a newbie to the django framework and trying to make a watchlist for stocks. I've already made the crux of the webapp, where-in, a user can search for a quote and add it to their watchlist, along with relevant data about that quote. What I want to do now is, to save the separate watchlists that different users are creating (after creating an account on my site) and upon logging in to my site, they can view their personalized watchlist and edit it. I'm using a model for storing the data for the watchlist quotes and looking for a way to provide the different personalized watchlist data depending upon the logged in user. Can anyone give me a lead on how to employ the logic for this? Do I need to use two data bases - one for the data of the users and the other one for storing the respective user watchlists? If yes, how do I connect everything? -
TypeError: 'Post' object is not callable
I'm new to Django and I keep getting this error on my project. I have tried to fix it by examining similar problems, but I keep struggling to find the problem. Here is the code for models.py file. class Post(models.Model): publisher = models.ForeignKey(User, related_name='posts_published', on_delete=models.CASCADE) category = models.ForeignKey(Category, related_name='posts', on_delete=models.CASCADE) subject = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique=True) overview = models.TextField() published = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-published'] def __str__(self): return self.subject class Module(models.Model): post = models.ForeignKey(Post, related_name='modules', on_delete=models.CASCADE) subject = models.CharField(max_length=200) add_desc = models.TextField(blank=True) order = OrderField(blank=True, for_fields=['post']) class Meta: ordering = ['order'] def __str__(self): return f'{self.order}. {self.subject}' A snippet from views.py class PostUpdateViewModel(TemplateResponseMixin, View): template_name = 'publications/manage/module/formset.html' post = None def get_formset(self, data=None): return PostsModuleFields(instance=self.post, data=data) def dispatch(self, request, pk): self.post = get_object_or_404(Post, id=pk, publisher=request.user) return super().dispatch(request, pk) def get(self, request, *args, **kwargs): formset = self.get_formset() return self.render_to_response({'post': self.post, 'formset': formset}) def post(self, request, *args, **kwargs): formset = self.get_formset(data=request.POST) if formset.is_valid(): formset.save() return redirect('posts_list_merge') return self.render_to_response({'post': self.post, 'formset': formset}) My formset.html {% extends "home.html" %} {% block title %} Edit "{{ post.subject }}" {% endblock %} {% block content %} <h1>Edit "{{ post.subject }}"</h1> <div class="module"> <h2>Course modules</h2> <form method="post"> {{ formset }} {{ formset.management_form }} {% csrf_token …