Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Wagtail Page.objects.descendant_of(inclusive=False) Error
I'm using Django 2.0 with the latest version of Wagtail CMS. I am pretty new to Wagtail and I am trying to query the children of EventIndexPage which is EventPage and have them appear on my HomePage. I am trying to use this line of python in home app models.py below: special_events = EventIndexPage.objects.descendant_of(inclusive=False) But It returns: return getattr(self.get_queryset(), name)(*args, **kwargs) TypeError: descendant_of() missing 1 required positional argument: 'other' When I try putting "EventPage" in before "inclusive=false" I get a type error because its an array not an integer. docs: http://docs.wagtail.io/en/v2.0/reference/pages/queryset_reference.html Models.py of the home app: from django.db import models from event.models import EventIndexPage from wagtail.core.models import Page from wagtail.core.fields import RichTextField from wagtail.admin.edit_handlers import FieldPanel class HomePage(Page): body = RichTextField(blank=True) special_events = EventIndexPage.objects.descendant_of(inclusive=False) content_panels = Page.content_panels + [ FieldPanel('body', classname="full"), ] Models.py of event app from django.db import models from wagtail.core.models import Page from wagtail.core.fields import RichTextField from wagtail.admin.edit_handlers import FieldPanel from wagtail.search import index class EventIndexPage(Page): intro = RichTextField(blank=True) content_panels = Page.content_panels + [ FieldPanel('intro', classname="full") ] class EventPage(Page): date = models.DateField("Post date") intro = models.CharField(max_length=250) body = RichTextField(blank=True) search_fields = Page.search_fields + [ index.SearchField('intro'), index.SearchField('body'), ] content_panels = Page.content_panels + [ FieldPanel('date'), FieldPanel('intro'), FieldPanel('body', classname="full"), ] -
Get site-specific user profile fields from user-created object
I am using Django sites framework (Django 2.1) to split an app into multiple sites. All of my models except the User model are site-specific. Here is my Post model: post.py class Post(models.Model): parent = models.ForeignKey( 'self', on_delete=models.CASCADE, related_name='children', related_query_name='child', blank=True, null=True, ) title = models.CharField( max_length=255, blank=True, ) body_raw = models.TextField() body_html = models.TextField(blank=True) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) site = models.ForeignKey(Site, on_delete=models.CASCADE) on_site = CurrentSiteManager() I have no problem separating posts out by site. When I want to get the posts, I call: posts = Post.on_site.filter(...) I have a separate model called UserProfile. It is a many-to-one profile where there is a unique profile created for each user-site combination (similar to profile implementation at SE). The profile has a reputation attribute that I want to access when I get any post. user_profile.py class UserProfile(models.Model): user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) reputation = models.PositiveIntegerField(default=1) site = models.ForeignKey(Site, on_delete=models.CASCADE) on_site = CurrentSiteManager() How do I access the user's username (on the User model) as well as the user's reputation (on the UserProfile model) when I get Posts from a query? -
Django, object-level permissions and calculated fields
I've been scouring the internet for answers, but my Google-fu isn't quite working. I need to have object-level permissions and calculated fields based on the fields a user has access to. I must use Django. I am allowed to import addons. For example, consider the following use case: A business would like to provide an inventory tracking system for sales clerks and managers. The system tracks how much inventory each sales clerk starts the month with, how much they have sold that month, and how much inventory they have remaining (calculated field :(start_inventory - sold_inventory = currentInventory)). A sales clerk can only see the start, sold and current inventory for themselves. A manager can see all the start, sold and current inventory for the sales clerks that they manage. Now, start and sold inventory are recorded in the model - and it seems quite simple to use something like django-guardian's get_objects_for_user() just for the start and sold inventory... but for current inventory? My first thought was to define a function or a manager with a function in the model.py that returns the model + the calculated current inventory field. However, because that method is in the model.py... I can't use … -
Django Admin Static Files No Longer Working: "Did you forget to register or load this tag?"
I am able to create a Django Project and and my admin site works fine initially. After I create an app, register it, setup static files, the Django Admin page actually starts complaining that I failed to give it static files at all. (Something I don't consider myself to be on the hook for) So when I hit: http://127.0.0.1/admin (like I always do), somewhere in the timeline, I face an error that says: TemplateSyntaxError at /admin/login/ Invalid block tag on line 4: 'static', expected 'endblock'. Did you forget to register or load this tag? Okay so that seems like a silly question, but why am I being asked if I registered the static tag? What about my static tag destroyed theirs? I'm not even sure which files I should be looking at right now. In settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp', ] DEBUG = True ... snip - irrelevant stuff # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.1/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'comics', 'static'), ] The file that is breaking down isn't mine to edit. It's the admin one. Where should I be looking? I should also note that my own app … -
Best way to implement models with many overlapping fields in Django?
I need to implement the following logic: there is a big model Base with many fields and several smaller models sharing some field subsets with it and with each other. For example, let's say that Base has fields a, b, c, d, e and f; model A has fields a, b, g; model B has fields b, c, d, g; model C has fields d, e, f, g. Trying to do proper inheritance from abstract models will very quickly lead to a mess, but making manual copies of fields also seems suboptimal, since every field from the main model is present in the smaller ones and so will have to be listed twice. What's a good way to approach this? -
Docker error using python 3.7: Generator expression must be parenthesized
Hi I am following the django tutorial (Quickstart: Compose and Django) of .. and I have this error: SyntaxError: Generator expression must be parenthesized traceback root@localhost:~# docker-compose up Starting root_db_1 ... done Starting root_web_1 ... done Attaching to root_db_1, root_web_1 db_1 | 2018-09-09 00:09:10.440 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 db_1 | 2018-09-09 00:09:10.440 UTC [1] LOG: listening on IPv6 address "::", port 5432 db_1 | 2018-09-09 00:09:10.442 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" db_1 | 2018-09-09 00:09:10.481 UTC [21] LOG: database system was interrupted; last known up at 2018-09-09 00:06:36 UTC db_1 | 2018-09-09 00:09:10.597 UTC [21] LOG: database system was not properly shut down; automatic recovery in progress db_1 | 2018-09-09 00:09:10.599 UTC [21] LOG: redo starts at 0/1633C88 db_1 | 2018-09-09 00:09:10.599 UTC [21] LOG: invalid record length at 0/1633CC0: wanted 24, got 0 db_1 | 2018-09-09 00:09:10.599 UTC [21] LOG: redo done at 0/1633C88 db_1 | 2018-09-09 00:09:10.632 UTC [1] LOG: database system is ready to accept connections web_1 | Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f652d99d510> web_1 | Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.7/site-packages/django/utils/autoreload.py", line 228, in wrapper web_1 | fn(*args, **kwargs) web_1 … -
NOT NULL constraint failed error in django despite having null set to true and blank set to true
Here's the code: class community(models.Model): communityName = models.CharField(max_length=280) communityID = models.BigIntegerField(null=True,blank=True) icon = models.CharField(max_length=400) def __str__(self): return self.communityName class team(models.Model): date = models.DateField() startTime = models.TimeField() teamName = models.CharField(max_length=280) community = models.ForeignKey(community, on_delete=models.CASCADE, default=None) I've done a lot of reading on this and it makes sense that I'm supposed to set null and blank to true to prevent this error however when I attempt to migrate the models I still get the following error thrown: django.db.utils.IntegrityError: NOT NULL constraint failed: scheduler_team.community_id I don't know anything about database management and this is the first project I've attempted to do that has a database involved so an ELI5 would be very much appreciated thank you! -
How do I seralize related objects in Django to use for fixtures?
How do I seralize related objects in Django to use for fixtures? class Selector(models.Model): id = models.AutoField(primary_key=True) site = models.ForeignKey(AlexaSite, on_delete=models.PROTECT, related_name='selectors') If I do something like this: selector = Selector.objects.filter(id=selector_id).all() data = serializers.serialize("json", selector) I only get the selector object, but not the related site. This becomes an issues when actually trying to use the fixture because I get a foreign key error saying “Site of id 5 does not exist”. Now I also tried serializing the selector by doing: selector = SelectorsSerializer(selector) But this gives me a Serializer object, not a string, which I can’t make a fixture out of. So I either need to be able to: a) make fixtures from related objects using serializers.serialize(“json”, selector) b) convert my Serializer object to a json string that can actually be used for a fixture. Any ideas? (edited) -
Python Django Test for One of Two Exceptions
I am trying to test that a certain instance of a model will raise one of two exceptions, but I can't figure out how to get it to work. Here is what I have: Model class AvailablePermissions(models.Model): # Main Checkbox. category = models.CharField( max_length=100, ) # Checkboxes under Main Checkbox. subcategory = models.CharField( max_length=100, ) # The view to grant permission to. view_name= models.CharField( max_length=255, unique=True, ) def full_clean_save(self): try: name = resolve(reverse(f'{self.view_name}')) self.full_clean() self.save() except NoReverseMatch as nrme: raise nrme except ValidationError as ve: raise ve return self Test # Default permission object "(**permission)" permission = { 'category': 'Category', 'subcategory': 'Subcategory', 'view_name': 'employee:create_profile', } available_permission = AvailablePermissions(**permission) class AvailablePermissionsValidationTest(TestCase): def test_AvailablePermissions_will_not_save_blank_permissions(self): for field in permission: original_value = permission[field] permission[field] = '' with self.assertRaises(ValidationError or NoReverseMatch): AvailablePermissions( **permission ).full_clean_save() permission[field] = original_value It throws the NoReverseMatch error, but I can't figure out how to look for "either or" exception. -
delete object in template - django
My main page has many sub pages and on each of the sub pages i have many items listed. Next to item i want a delete button and when you press it the item must be deleted but you must remain on the same page. Is there a way that when i press the delete button i send the id of the object to view but still remain on the same page ? In view of each subpages i would have code like this: if request.method == 'GET' and 'delete' in request.GET: Now i need a way to get id of object that is next to delete button so i can delete it. I saw some solutions online using urls but the problem is i would have to write a special url for each of the 7 subpages. -
django using a link containing turkish characters
I am creating django project. Django allow using turkish characters (ş,ü,ö,İ,ğ,ı,ç) in auth.User models. But I want to use usernames in links. For instance, app.com/şüöİğıç. There is no problem when I'm working some links (contain turkish characters) on a computer. Is there any problem when ı publish project. I cant using slugify because one user can be 'şam' and one user can be 'sam'. So it can be conflict. I want to create username validator for using just english letters. How can I do? Briefly, Is there any problem when using turkish letters on links(app.com/şüöİğıç) and if there is problem How can I solve this problem. forms.py: class registerForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) class Meta: model = User fields = ["email","first_name","last_name","password","username"] #model = ACCOUNTS #fields=['email','name','surname','username','password','birthday','gender','language'] -
I want import python code in htm file with django
{% for post in posts %} {{post.name}} {{post.content}} {% endfor %}I created html file and i'm trying to use python code in html but {{}} {%%} tags not working. It show me my code like a html p tag Only i see this on browser not working codes.where is the problem libraryy?? -
media files aren't serving in django app on cpanel
I have a django app running on cpanel (I'm not sure if is a problem of my django app or cpanel server), when the debug mode is set up True. I can see all the media files, like profiles pictures or pdf files, etc. But when the debug mode is set up False, you can't see the media files on the app. This is my configuratios on the settings.py file. STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATIC_URL = '/static/' STATIC_ROOT = '/home/plataformalabora/public_html/static' # Media files MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' # Crispy Form Theme - Bootstrap 3 CRISPY_TEMPLATE_PACK = 'bootstrap3' # For Bootstrap 3, change error alert to 'danger' from django.contrib import messages MESSAGE_TAGS = { messages.ERROR: 'danger' } -
Templatedoesnotexist error in django where the template is there
I am getting Templatedoesnotexist error when i command 'run server'. I want my home.html to run when the url is '/'. and my template (home.html) is in templates directory but it says it cannot find the template. My views are fine, I used TemplateView for home page and connected it in urls.py. What should I do..? -
http POST containing a foreign key and save it
I send http request post from client. Code client. import requests payload = {'data':['12', '15'], 'timestamp':['1', '2'], 'mission':['Mission01', 'Mission01']} r = requests.post("http://127.0.0.1:8000", data=payload) print(r.url) I receive in Django http post: My models.py from django.db import models class Mission(models.Model): name = models.CharField(max_length=250) description = models.CharField(max_length=1000) type = models.CharField(max_length=500) date = models.DateField() def __str__(self): return self.name + '-' + self.description class SensorLog (models.Model): mission = models.ForeignKey(Mission, on_delete=models.CASCADE) data = models.CharField(max_length=50) timestamp = models.CharField(max_length=50) my views.py from django.shortcuts import render from django.http import Http404, HttpResponse from django.views.decorators.csrf import csrf_exempt from .models import Mission, SensorLog @csrf_exempt def home(request): context = {'request_method': request.method} if request.method == 'POST': datas = request.POST.getlist('data') timestamps = request.POST.getlist('timestamp') missions = request.POST.getlist('mission') for i in range(len(datas)): post = SensorLog.objects.create(data=datas[i], timestamp=timestamps[i], mission=missions[i]) return render(request, 'your_template_name_here', context) If I run django and client.. In django i have error: ValueError: Cannot assign "'Mission01'": "SensorLog.mission" must be a "Mission" instance. why don't i save data? why have i this error? How can i do? -
django model setting up, using foreignkey of foreignkey
so I'm doing a small project to learn django,and I'm so confused about setting up db. I have 3 Video Categories: Chelsea, Barcelona, and RealMadrid. Under that 3 videos there are seasons: Chelsea - season1 season2 .....season n same for Barcelona and RealMadrid Under the season, there are videos this is how I set it up so far but confused class Team(models.Model): name = models.CharField(max_length=255) class Season(models.Model): name = models.CharField(max_length=255) team = models.ForeignKey(Team) class Content(models.Model): name = models.CharField(max_length=255) season = models.ForeignKey(Season) So the content of the foreignkey of foreignkey. Is this the valid way?and how do I get team name from the content? -
Django forms not visible
I am trying to create a simple program that uses forms, but my forms are not appearing. I have read all of the Django docs and read multiple questions related to this issue, but I have found no solution that fixes my problem. Here are my programs: views.py from django.shortcuts import render from .forms import FileForm with open('calendar.txt') as f: file_content = f.read() def home(request): return render(request, 'main/index.html',{'file_content':file_content}) def form_get(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = FileForm(request.POST) # check whether it's valid: if form.is_valid(): pass else: form = FileForm() return render(request, 'index.html', {'form': FileForm.form}) urls.py from django.conf.urls import url from django.contrib import admin from main import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.home, name='home'), ] index.py {% extends "base.html" %} {% block content %} <h1>Welcome to the calendar!</h1> <form action="/#" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> {{form}} {% endblock content %} Link to program From what I read, the only useful information that I could find is that it may somehow relate to the urls.py... but I'm … -
python-django code works locally, but on server raise Failed to establish a new connection: [Errno 110]
ConnectionError at /backends/profile/ HTTPSConnectionPool(host='geo.egistic.kz', port=8081): Max retries exceeded with url: /rest/workspaces.xml (Caused by NewConnectionError(': Failed to establish a new connection: [Errno 110] Connection timed out',)) I am trying to connect geoserver on my server. Code works properly on my computer without errors, however on server it gives me this error Error image, which appears ` def profile(request): requests = request.user.backendrequests_set.all() return render(request, 'accounts/profile.html', { 'backend_request_form': form, 'requests': requests }) requests = request.user.backendrequests_set.all()- here exception appears because of _set.all() I have surfed the Internet, however other similar errors are not my case Thank you for any help -
django: not null constraint failed
I am getting "not null constraint failed" exception for password field in my custom user model while registering a user through the browser(ModelForm) but I can add that user through django shell successfully. I've tried deleting database and migrations and re-doing it. Any idea why this is happening? I'd be really thankful for the help! -
Python / Django: How to use html form 'placeholder' property with standard view?
I am new to Django and am using Django's user auth package (django.contrib.auth) for user login, password reset, etc. Now, while everything works just fine, on the logon form, I'd like to use the html-placeholder property. How can I use / populate this? I did find some answers but I do not understand how to extend the view / form or even the model as this gets delivered with the standard package. Thanks a lot! PS: I am new to StackOverflow; this is my first post! Thanks! -
How to add multiple slugs into one url path in Django 2.1?
I want to have a URL path like this: www.example.com/bachelor/frankfurt-university/corporate-finance As you can see, the URL path includes 3 slugs in this example. I have 3 different class for these categories. And slug is included inside each of them separately. What do I need to do in order to be able to achieve that type of URL paths? I can make URL path with a single slug but not with multiple slugs. Every single help or thought is highly appreciated. I can't find any source for that. URLS.py app_name = 'mnsdirectory' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), #views.index path('study/<slug:studylevelslug>/<slug:subjectslug>/', views.SubjectDetailView.as_view(), name='subject-detail'), path('study-abroad/<slug:studylevelslug>/', views.StudylevelDetailView.as_view(), name='studylevel-list'), ] VIEWS.py class IndexView(generic.ListView): model = Programmesearch template_name = 'mnsdirectory/index.html' context_object_name = 'universities' queryset = Programmesearch.objects.all()[:6] def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) context['studylevels'] = StudyLevel.objects.all()[:10] return context class SubjectDetailView(generic.DetailView): model = Programmesearch, StudyLevel template_name = 'mnsdirectory/subject_detail.html' slug_field = {'studylevelslug', 'subjectslug',} slug_url_kwarg = {'studylevelslug', 'subjectslug',} class StudylevelDetailView(generic.DetailView): model = StudyLevel template_name = 'mnsdirectory/study_level.html' slug_field = 'studylevelslug' slug_url_kwarg = 'studylevelslug' MODELS.py class Programmesearch(models.Model): study_country = models.CharField(max_length=100, choices=COUNTRY_CHOICE) full_subject_name = models.CharField(max_length=100, blank=True, null=True) def get_unique_slug(self): subjectslug = slugify(self) unique_slug = subjectslug counter = 1 while mnsdirectory.objects.filter(subjectslug = unique_slug).exists(): unique_slug = '{}-{}'.format(subjectslug, counter) counter += 1 return unique_slug subjectslug … -
How to add an image as background image inline in Django
I know there are a lot of entries about how to use the staic files in Django and how to add them into html frame. I have searched 2 hours and tried every solution, but nothing worked for me! I want to set the image as a background in a li-element. I tried all of the following: <li style="background-image: url({% static \'images/start1.JPG\'});"> <li style="background-image: url('{% static &ldquo;images/start1.JPG&ldquo;}');"> <li style="background-image: url('{% static &quot;images/start1.JPG&quot;}');"> <li style="background-image: url('{% static \"images/start1.JPG\"}');"> <li style="background-image: '/static/images/start1.JPG';"> I'm probably just making a small misstake, but I cannot find it, I would really appreciate some help. I tried loading the image in an img-element with: <img src="{% static "images/start1.JPG" %}" alt="My image"> That worked, so the image is there at the right path. Best, Lennie. -
NOT NULL constraint failed: accounts_myuser.password
I am doing a web application in django where users can create accounts. I'm storing the users' passwords in plaintext as authentication in my system does not totally depend on password but also on the otp. The problem I'm facing all of a sudden(it worked fine earlier) at the POST request of registration, is "NOT NULL constraint failed: accounts_myuser.password". I tried deleting database and migrations and re-migrated but it didn't help. I'm giving the ModelForm and the Model(custom one) below. It worked fine and I could register users successfully earlier with the code below. Could anyone please help me? forms.py class UserCreationForm(forms.ModelForm): password1 = forms.IntegerField(label='Password', min_value=0000, max_value=9999, widget=forms.PasswordInput) password2 = forms.IntegerField(label='Password Confirmation', min_value=0000, max_value=9999, widget=forms.PasswordInput) class Meta: model = User fields = ['username', 'email'] def clean_password1(self): password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords do not match!") if len(str(password1)) != 4 or len(str(password2)) != 4: raise forms.ValidationError("Passwords should be of length Four!") return password2 def save(self, commit=True): user = super(UserCreationForm, self).save(commit=False) user.password = self.cleaned_data['password1'] if commit: user.save() return user models.py class MyUserManager(BaseUserManager): def create_user(self, username, email, password=None): if not email: raise ValueError('Users must have an email') user = self.model( username = username, … -
NoReverseMatch at /ProjektAJ/songs/ Reverse for 'songs' with arguments '('all',)' not found. 1 pattern(s) tried: ['ProjektAJ\\/songs/$']
I am new in Django, I would like to return list of all songs in my project from my local sqlite HTML file <li class="{% block songs_active %}{% endblock %}"><a href="{% url 'ProjektAJ:songs' %}"><span class="glyphicon glyphicon-music" aria-hidden="true"></span>&nbsp; Songs</a></li> urls.py url(r'^songs/$', views.SongsView.as_view(), name='songs'), views.py class SongsView(generic.ListView): template_name = 'ProjektAJ/songs.html' context_object_name = 'all_songs' def get_queryset(self): return Song.objects.all() models.py class Song(models.Model): album = models.ForeignKey(Album, on_delete=models.CASCADE) file_type = models.CharField(max_length=10) song_title = models.CharField(max_length=250) is_favorite = models.BooleanField(default=False) def get_absolute_url(self): return reverse('ProjektAJ:index') def __str__(self): return self.song_title I have error like below NoReverseMatch at /ProjektAJ/songs/ Reverse for 'songs' with arguments '('all',)' not found. 1 pattern(s) tried: ['ProjektAJ\/songs/$'] Request Method: GET Request URL: http://127.0.0.1:8000/ProjektAJ/songs/ Django Version: 2.0.6 Exception Type: NoReverseMatch Exception Value: Reverse for 'songs' with arguments '('all',)' not found. 1 pattern(s) tried: ['ProjektAJ\/songs/$'] Exception Location: G:\Python\Python36-32\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 636 Python Executable: G:\Python\Python36-32\python.exe Python Version: 3.6.3 Python Path: ['C:\Users\Adrian Skibiński\ProbaDjango\django_projekt', 'G:\Python\Python36-32\python36.zip', 'G:\Python\Python36-32\DLLs', 'G:\Python\Python36-32\lib', 'G:\Python\Python36-32', 'G:\Python\Python36-32\lib\site-packages'] Server time: Sat, 8 Sep 2018 16:29:51 +0000 Could you tell me what I do wrong in this case? -
Django inline formsets updating a model
I'm pulling my hair out trying to get Django's formsets to work when updating a model. I've got 2 models, Product and ProductSize. I'm using an inline formset to link my ProductSizes to the Products when adding or edit the Product. Adding the object is fine, but when I trying editing the Product, I can't submit the form. I get [{'id': ['This field is required.']}] output in the print below. Here are my views: class ProductAdd(AddModelView): model = Product form_class = UpdateProductForm template_name = 'intake_goods_form.jinja' title = 'Add Product Type' formset_class = ProductSizesFormSet def form_valid(self, form): obj = form.save() formset = self.formset_class(self.request.POST) if formset.is_valid(): formset.instance = obj formset.save() else: print(formset.errors) return self.form_invalid(form) return super().form_valid(form) def get_context_data(self, **kwargs): if self.request.POST: formset = self.formset_class(self.request.POST, instance=self.object) else: formset = self.formset_class(instance=self.object) return super().get_context_data(formsets=formset, **kwargs) product_type_add = ProductAdd.as_view() class ProductEdit(ProductAdd, UpdateModelView): model = Product form_class = UpdateProductForm product_type_edit = ProductEdit.as_view() And here are my forms: class UpdateProductForm(SVModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) class Meta: model = Product exclude = {'material'} class ProductSizeForm(SVModelForm): title = 'Product Type Sizes' class Meta: model = ProductSize fields = ['sku_code', 'bar_code', 'size'] ProductSizesFormSet = forms.inlineformset_factory(Product, ProductSize, ProductSizeForm, extra=1, can_delete=False) Can anyone help? Thanks