Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Nested Django view with .html inserted using include tag
I would like to know if anyone has any best practice recommendations for what I am trying to do. Which is essentially to render a Django view (from and within an already rendered view) using the include tag so that the html is structured as I would like (it is part of a bootstrap navbar). The .html I would like to have is a sort of dropdown menu. I am currently just rendering the dropdown using the include tag. So it using the same Django view as the rest of the page. And I am doing all the context passing to the main view which is then used also in the included template. I would like to give this dropdown its own Django view so that I only perform certain database queries and other calculations if the dropdown is opened, and also to keep some code separate where possible. It would be nice if someone with experience in this could let me know what they think, and if it even makes sense to try and split this into 2 views. -
How to use Django's RestAPI's update() function in models with swift?
I'm currently trying to link swift and a database (MySQL) using Django's Rest-API Framework. I've already Django and have it connected and it gets Post requests and Get requests fine. I'm just wondering if its possible to lets say, have a user fill in basic login info on one screen (username passcode, etc.) but then later fill in the rest of the information (like name, and address) at a later point and have Django update the row with their information on it. I'm planning to do this by having the user id in a variable (in swift) so it'll edit the row/column by the users id. This is what I have for django as the model and serializer: Serializer: from rest_framework import serializers from .models import Data class CasaSerializer(serializers.ModelSerializer): class Meta: model = Data fields = ('id', 'first_name', 'last_name', 'email', 'password', 'buyerorseller', 'creditscore', 'min_salary') Model: from django.db import models # Create your models here. class Data(models.Model): first_name = models.CharField(max_length = 50, default="") last_name = models.CharField(max_length = 50, default="") email = models.CharField(max_length = 50, default="", unique=True) password = models.CharField(max_length = 20, default="") buyerorseller = models.CharField(max_length = 6, default="") creditscore = models.IntegerField() min_salary = models.IntegerField() def __str__(self): return(self.last_name, self.first_name) I'm just wondering … -
How to pass the id of one class object to another class object in django views.py
This is for a library management web app, I need to filter a specific book object by it's id and make it as ISSUED when I click on issue button. Here I need to get the specific book that I selected by it's id. How can I implement it? Post.objects.filter(id=self.request.GET.get('id')).update(issued=True) -
My session isn't storing what i'm asking it to store, when I try to view whats in the session an empty list is returned
I am trying to add something to a session by performing a post request via a form, when I try to view what's in the session by going to a page and a empty list is returned (I see this []), I have looked around toher questions and tried adding this request.session.modified = True but it hasn't worked as I thought that the session may not have been saving. Can anyone suggest any possible solutions? Views def cart(request): cartSession = request.session['cart'] context={ 'cartSession': cartSession } return render(request, "OsbourneSpiceWebsite/cart.html", context=context) def menu(request): request.session['cart'] = [] context = { "items": Menu.objects.all(), } return render(request, "OsbourneSpiceWebsite/menu.html", context) def addToCart(request): if request.method == 'POST': request.session.modified = True itemID = request.POST['productId'] getItemFromPost = Menu.objects.get(itemid=itemID) if getItemFromPost is None: return HttpResponse("Error there is no data") cartSession = request.session['cart'] for item in cartSession: if item['Itemname'] == getItemFromPost.itemname: item['Qty'] += 1 break else: cartSession.append({ 'Itemname': getItemFromPost.itemname, 'Itemprice': int(getItemFromPost.itemprice), 'Qty': 1 }) request.session['cart'] = cartSession context = { "cartSession": cartSession } request.session.modified = True return render(request, "OsbourneSpiceWebsite/cart.html", context=context) Form <form action="{% url 'addToCart' %}" method="POST"> {% csrf_token %} <input name="productId" type="hidden" value="{{ item.itemid }}"> <div class="addToCartButtonContainer"> <button aria-label="Add" class="addButton " type="submit">+</button> </div> </form> Cart page (page that should display … -
Error when rebuilding search index in ElasticSearch/Django
When I run ./manage.py search_index --rebuild I get the following error: elasticsearch.exceptions.RequestError: RequestError(400, 'mapper_parsing_exception', 'Root mapping definition has unsupported parameters: [bodystyle : {type=text}] [model : {type=text}] [carclass : {type=text}] [version : {type=text}]') I have tried to change the version of my elasticsearch. My current version is: $ curl -XGET 'localhost:9200' { "name" : "MOkbeEQ", "cluster_name" : "elasticsearch", "cluster_uuid" : "pF_Z62bBTl-Jq31HSuAhQA", "version" : { "number" : "5.6.8", "build_hash" : "688ecce", "build_date" : "2018-02-16T16:46:30.010Z", "build_snapshot" : false, "lucene_version" : "6.6.1" }, "tagline" : "You Know, for Search" } My documents.py code is as below: from django_elasticsearch_dsl import Document from django_elasticsearch_dsl.registries import registry from products.models import Product_Model @registry.register_document class CarDocument(Document): class Index: # Name of the Elasticsearch index name = 'cars' # See Elasticsearch Indices API reference for available settings settings = {'number_of_shards': 1, 'number_of_replicas': 0} class Django: model = Product_Model # The model associated with this Document # The fields of the model you want to be indexed in Elasticsearch fields = [ 'model', 'version', 'carclass', 'bodystyle', ] -
How to connect heroku and godaddy correctly?
I am trying to park a django website hosted on heroku on godaddy but unfortunately I am unable to do so correctly. I have tried using heroku domains:add and also followed several tutorials. Project Specification Django website run in heroku free dyno Heroku dns configurations - Heroku DNS Panel GoDaddy dns configurations - GoDaddy DNS Panel I have assigned DNS targets from heroku to godaddy and kept the 'A' type entry default as Heroku does not support it. -
Which is the best python REST framework (preferably async platform) for an API gateway which would frontend the requests to these micro-services?
Are there any evaluations done for the python/async based platform (that is running in production)? Specifically looking at starlette, sanic, falcon or aiohttp? We are having more than a dozen of micro-services that are running in AWS on kubernetes platform. Designing an API gateway which would frontend the requests to these micro-services. We would be hitting close to 10K requests per sec during the peak, and the average trend of about 1k requests per sec during off peak. Flask and Django posed some issues, since most of these calls are inline calls to these micro-services (will be blocked anywhere from 1 to 3 secs range per request/response roundtrip). Would be great to get insights and feedback on the above frameworks. Flask and Django posed some issues, since most of these calls are inline calls to these micro-services (will be blocked anywhere from 1 to 3 secs range per request/response roundtrip) -
I am new in django framework and I dont know how to update data in postgres using django framework , can you give an simple example of how to update?
update data in postgresql using django html -
How can I update a Model field inside DetailView with a button click
I've created a maintenance App that allows the user to create and view the maintenance details. I have a page "maintenance-details.html" where I show all the details of a particular maintenance. Here is my views.py: class MaintenanceDetailView(DetailView): template_name = 'maintenance/maintenance-details.html' model = Maintenance def get_context_data(self, **kwargs): contacts_suppliers = ContactsSupplier.objects.filter(supplier__maintenance=self.object) hora_atual = datetime.datetime.now() context = super().get_context_data(**kwargs) context['contacts_supplier'] = contacts_suppliers context['hora_atual'] = hora_atual return context I have created a button on my template named "Mark as done". My Maintenance model has a BooleandField "done" with the purpose to set the task as done or not. What I'm looking for is the best way to update the model and set the "done" as "True" when the user clicks it. My models.py here: class Maintenance(models.Model): category = models.ForeignKey(SuppliersCategory, models.DO_NOTHING, db_column='Category') # Field name made lowercase. property = models.ForeignKey(Property, models.DO_NOTHING, db_column='Property_Reference') # Field name made lowercase. name = models.CharField(db_column='Name', max_length=25) # Field name made lowercase. created_date = models.DateTimeField(db_column='Date', auto_now_add=True) # Field name made lowercase. staffmember = models.CharField(db_column='StaffMember', max_length=25, blank=True, null=True) # Field name made lowercase. supplier = models.ForeignKey(Suppliers, db_column='Supplier') # Field name made lowercase. description = models.CharField(db_column='Description', max_length=500, blank=True, null=True) # Field name made lowercase. photo = models.ImageField(upload_to='maintenace/', db_column='Photo', blank=True, null=True) # Field name made … -
Why Django CheckConstraint doesn't works on MySQL
When I create one class with constraint like below: constraints = [ models.CheckConstraint( check=models.Q('plan' == 1), name="custom_constraint" ) ] I receive the message: (models.W027) MySQL does not support check constraints. HINT: A constraint won't be created. Silence this warning if you don't care about it. Why Django CheckConstraints works with PostgreSQL and not with MySQL? -
Django: How to apply the built-in password validators?
I like to test the django built-in validators on my registration form. So i added this... settings.py AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 'OPTIONS': { 'min_length': 9, } }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] forms.py from django.contrib.auth.models import User from django import forms import django.contrib.auth.password_validation as validators class UserRegistrationForm(forms.ModelForm): password = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Repeat password', widget=forms.PasswordInput) class Meta: model = User fields = ('username', 'first_name', 'email') # --- check duplicate def clean_password2(self): cd = self.cleaned_data if cd['password'] != cd['password2']: raise forms.ValidationError('Passwords don\'t match.') return cd['password2'] # --- django built-in validator def pass_validate(self): password = self.cleaned_data('password') try: validators(password, self.instance) except forms.ValidationError as error: self.add_error('password', error) return password views.py <...> def register(request): if request.method == 'POST': user_form = UserRegistrationForm(request.POST) if user_form.is_valid(): # Create a new user object but avoid saving it yet new_user = user_form.save(commit=False) # Set the chosen password new_user.set_password( user_form.cleaned_data['password']) # Save the User object new_user.save() return render(request, 'account/register_done.html', {'new_user': new_user}) else: user_form = UserRegistrationForm() return render(request, 'account/register.html', {'user_form': user_form}) <...> Unfortunately i can still register as a user with passwords like "123". So the min_length does not work. The pass_validate Function in forms.py was an approach, to add the … -
the image uploaded is not stored on the database
i'm creating a 'create an account view ' which the user can store his image, name ,lastname .... on my database the name,lastname... are registred but the image is not stored.why? in models.py: from django.db import models class information(models.Model): name=models.CharField(max_length=50) lastname=models.CharField(max_length=50) email=models.CharField(max_length=50) password=models.CharField(max_length=50) img=models.ImageField(upload_to='media',blank=True) in forms.py: from app1.models import information from django import forms class create_form(forms.ModelForm): class Meta: model=information fields=[ 'name', 'lastname', 'email', 'password', 'img' ] in views.py: def create_view(request,*args,**kwargs): my_form=create_form(request.POST or None) if my_form.is_valid(): my_form.save() print(my_form.cleaned_data['img'])**#########print :None** context={"form":my_form} return render(request,'first create.html',context ) in templates: <main> <section> <form action="" method="Post"> {% csrf_token %} {{form.as_p}} <input type="submit" value="save"/> </form> </section> </main> -
cannot run mange.py runserver after updating to Django 2.2.4 and python 3.7 (toml.py)
When running python manage.py runserver --settings=project.settings_dev I get: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 60, in execute super().execute(*args, **options) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 95, in handle self.run(**options) File "/usr/local/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 102, in run autoreload.run_with_reloader(self.inner_run, **options) File "/usr/local/lib/python3.7/site-packages/django/utils/autoreload.py", line 600, in run_with_reloader start_django(reloader, main_func, *args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/utils/autoreload.py", line 585, in start_django reloader.run(django_main_thread) File "/usr/local/lib/python3.7/site-packages/django/utils/autoreload.py", line 303, in run self.run_loop() File "/usr/local/lib/python3.7/site-packages/django/utils/autoreload.py", line 309, in run_loop next(ticker) File "/usr/local/lib/python3.7/site-packages/django/utils/autoreload.py", line 349, in tick for filepath, mtime in self.snapshot_files(): File "/usr/local/lib/python3.7/site-packages/django/utils/autoreload.py", line 365, in snapshot_files for file in self.watched_files(): File "/usr/local/lib/python3.7/site-packages/django/utils/autoreload.py", line 264, in watched_files yield from iter_all_python_module_files() File "/usr/local/lib/python3.7/site-packages/django/utils/autoreload.py", line 103, in iter_all_python_module_files return iter_modules_and_files(modules, frozenset(_error_files)) File "/usr/local/lib/python3.7/site-packages/django/utils/autoreload.py", line 131, in iter_modules_and_files if spec.has_location: AttributeError: 'str' object has no attribute 'has_location' This is the function that errors: https://github.com/django/django/blob/master/django/utils/autoreload.py#L131 @functools.lru_cache(maxsize=1) def iter_modules_and_files(modules, extra_files): """Iterate through all modules needed to be watched.""" sys_file_paths = [] for module in modules: # During debugging (with PyDev) the 'typing.io' and 'typing.re' objects # are added to … -
First django form is submitted, then second form will open. When second form will be submitted and validated, I wantI first form data to store in db
I am doing user registration with Phone verification using OTP. I have two forms: UserRegisterForm and PhoneOTP form. When user will submit UserRegisterForm then I want to save this form data temporary and then open the PhoneOTP form to take OTP from the user. When this form will submit and validated, then only I will take the UserRegisterForm data and will save to the database. So, how can I access the first form i.e. UserRegisterForm data when PhoneOTP is submitted?? I was trying to use Django Form Wizard. But, I thought that Form wizards are used only if a single form is split into multiple pages. But, in my case, I have two different forms. -
White line between divs
I'm trying to add some css to my site i'm working on, in order to practice django. So, i bumped into some problems with two divs, more precisely with a space or white line between them. If i type simple text, everything is ok and there's no white line. Also, i had an issue with p and other tags, but eventually figured it out and got rid of white line by setting paddings and margins to 0. But what i am supposed to do with these block content - i don't know. <!DOCTYPE html> <html lang="en"> <head> <style> body{ padding: 0px; margin: 0px; } .sidebar{ background-color: red; } .main-content{ background-color: blue; margin: 0; padding: 0; } </style> <title>{% block title %}{% endblock %}</title> </head> <body> <div class="sidebar"> <a href="#">Home</a> <a href="#">Lists</a> <a href="#">Create</a> </div> <div class="main-content"> {% block content %}{% endblock %} </div> </body> </html> So, there's a white line between two divs (.sidebar and .main-content) and i have no idea why would it show up there. I also tried overflow: hidden, but it didn't quite solve the problem. It substituted the white line with padding or something i have no control over, meaning couldn't get rid of it anyways. … -
How to set Django to default None if a database query for a FileField fails? (e.g. a ValueError)
I have to make a series of queries for FileFields linked to a database's entries; for optimal succinctness I figured putting all the queries in a single dictionary, like {"<code>.mml</code> File":musicXMLObject.mmlFile.url,"<code>.m2</code> File":musicXMLObject.m2File.url,"<code>.wav</code> File":musicXMLObject.wavFile.url} would suffice. All of these FileFields have null=True and blank=True set, so it's inevitable that a ValueError will be triggered if it so happens that a database entry doesn't have a file on hand. Is there by chance an option to default failed queries that would otherwise trigger ValueError to instead output None? I know that a quick and easy workaround to this problem would be to simply use if statements, something like if musicXMLObject.mmlFile: //do stuff if musicXMLObject.m2File: //do stuff if musicXMLObject.wavFile: //do stuff but that option isn't nearly as succinct as a single dictionary. Thoughts? -
A way to define recurring with string or json?
I am looking for a way to define recurring with string or json string I need a non-hardcoded way to define recurring, for example, some client want to do some work every two weeks, some want to do it every half month. I cannot hardcode such recurring. Instead I want a way to define for each client in database, something like 'every two weeks, starting 2019-09-01', and then a existing class to parse it and return a well-formed result to use. -
With Django, how can validate input wiht unique_togther for two columns on two different tables?
I'm working on a rest API to track inventory of Laptops and Monitors. Each item is its own table and its own model, and I need away to have an "asset_tag" field unique across both. Both models inherit the "asset_tag" attribute from an abstract class "TaggedItem" as shown in the code. I've done some digging and I I know that the model option unique_together can validate uniqueness across fields in the same table. But I don't know how to get it to reference fields in different tables. from django.db import models class TaggedItem(models.Model) ASSET_TAG = models.CharField(max_length=8) class Meta: abstract = True unique_together = [] # <-- This is the part that isn't working class Laptop(TaggedItem): NOTES = models.CharField(max_length=255, default="") class Monitor(TaggedItem) NOTES = models.CharField(max_length=255, default="") -
Unable to display file pdf in template
I am creating a website where a user can answers few questions and upload PDFs. The upload works, in fact my media/documents folders contains the uploaded PDF files. In addition, if I enter the admin panel and click on the PDF, it opens a new windows containing the PDF. HOWEVER I am not able to create a clickable link that allows the user to visualise the PDF. Basically, in my template, I want the user to click a link and visualise the PDF he has just uploaded. To do so I wrote: templates.html <a href="{{ MEDIA_URL }}{{project.thirdquestiondetail.third_seven.url}}">Click here to see the file</a> settings.py STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'mysite/static/') ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/ main project urls.py urlpatterns = [ path('', TemplateView.as_view(template_name='home.html'), name='home'), path('conditions/', TemplateView.as_view(template_name='conditions.html'), name='conditions'), path('admin/', admin.site.urls), path('users/', include('users.urls')), path('users/', include('django.contrib.auth.urls')), path('projects/', include('projects.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py class Thirdquestion(models.Model): third_one = models.TextField() third_two = models.TextField() third_three = models.TextField() third_four = models.TextField() third_five = models.TextField() third_six = models.TextField() third_seven = models.FileField(upload_to='documents/') third_eight = models.TextField() third_nine = models.TextField() third_ten = models.FileField(upload_to='documents/') developer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) project = models.OneToOneField(Project, on_delete=models.CASCADE) Now, if the user clicks the link Click here to see the … -
Python: How to convert json comma separated key to a dictionary
I have a JSON in below format: { '166, 175': 't2', '479': 't3' } I want to convert this to a map: 166: 't2' 175: 't2' 479: 't1' -
How to fix FieldError at /?
I've been trying to get my categories set up for a blog, I've tried deleting the "migrations" directory and db.sqlite3 to recreate my models and now I am receiving a FieldError. FieldError: Cannot resolve keyword 'categories' into field. Choices are: category, category_id, comment_count, comments, content, featured, id, overview, post_img, slug, timestamp, title Models.py from django.db import models from django.urls import reverse from tinymce import HTMLField from django.utils import timezone class CategoryTag(models.Model): title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique=True) class Meta: verbose_name = ('category') verbose_name_plural = 'categories' def __str__(self): return self.title class Post(models.Model): title = models.CharField(max_length=250) overview = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) content = HTMLField('Content') comment_count = models.IntegerField(default=0) post_img = models.ImageField() category = models.ForeignKey('CategoryTag', on_delete=models.CASCADE) featured = models.BooleanField() slug = models.SlugField(max_length=250, unique=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={ 'id': self.id }) ``` -
chained dropdown menu is not working properly
I have three chained dropdown menus which are not working properly. these three menus based on three variables passed from previous page. I want to connect them together. So when one item is selected other menu will have option based on this item. The three menus are for city, category, and subcategories. This is ads-classified website. I used Django 1.11.4 as a frame work combined with ajax to do this feature. For now, I connect only the second menu with the third one (category with sub-category). When I changed the second menu, the third one gives me an empty menu. I tried to figure it out but with no luck. Following is the code I wrote: The url: # url for the load_subcategories url(r'^ajax/load-subcategories/$', views.load_subcategories, name='ajax_load_subcategories'), # url for list page: url(r'^(?P<post_city>[\w\ ]+)/(?P<category_name>[\w\ ]+)/(?P<sub_category_name>[\w\ ]+)$', views.list_page, name='list_page'), The view functions are as follow: def load_subcategories(request): category_name_id = request.GET.get('category_id') sub_categories = Post_Sub_Category.objects.filter(category_name_id=category_name_id).order_by('sub_category_name') return render(request, 'towns/salehslist/sub_categories_dropdown_list_options.html', {'sub_categories': sub_categories}) def list_page(request, post_city, category_name, sub_category_name): template = 'towns/salehslist/list_page.html' if post_city is None: post_city = 'الرياض' if category_name is None: category_name = 'للبيع' if sub_category_name is None: sub_category_name = 'سيارات' # main (header) search query_fc = request.GET.get('h_qc') query_fcc = request.GET.get('h_qcc') query_fsc = request.GET.get('h_qsc') if query_fc: … -
How to relate an object and feild in django?
Actually i didn't know how to ask this question. Say i have choices for subjects in my code with a subject code and subject name where i will use the get_object_display ORM to display the subject name. ... SUBJECTS = (('MA8151','Engineering Mathematics'),('PH8151','Physics-1'),...) subject = models.CharField(max_length=10, choices=SUBJECTS) What I want is, i want to add another feature to the choice, that each choice has subject name, subject code and a credit point for it. I thought of creating a model ... subname = models.CharField(max_length=100) subcode = models.CharField(max_length=6) credit = models.SmallPositiveInteger() But since i'm new to django, i don't know how this will work on linking an object the name of a choice? On the whole, if i assign a subcode for a student, i want his records to be updated with relevant subname and relevant credit points. Help me out reaching the solution. Thanks in advance! -
Django ORM and GROUP BY
Newcommer to Django here. I'm currently trying to fetch some data from my model with a query that need would need a GROUP BY in SQL. Here is my simplified model: class Message(models.Model): mmsi = models.CharField(max_length=16) time = models.DateTimeField() point = models.PointField(geography=True) I'm basically trying to get the last Message from every distinct mmsi number. In SQL that would translates like this for example: select a.* from core_message a inner join (select mmsi, max(time) as time from core_message group by mmsi) b on a.mmsi=b.mmsi and a.time=b.time; After some tries, I managed to have something working similarly with Django ORM: >>> mf=Message.objects.values('mmsi').annotate(Max('time')) >>> Message.objects.filter(mmsi__in=mf.values('mmsi'),time__in=mf.values('time__max')) That works, but I find my Django solution quite clumsy. Not sure it's the proper way to do it. Looking at the underlying query this looks like this : >>> print(Message.objects.filter(mmsi__in=mf.values('mmsi'),time__in=mf.values('time__max')).query) SELECT "core_message"."id", "core_message"."mmsi", "core_message"."time", "core_message"."point"::bytea FROM "core_message" WHERE ("core_message"."mmsi" IN (SELECT U0."mmsi" FROM "core_message" U0 GROUP BY U0."mmsi") AND "core_message"."time" IN (SELECT MAX(U0."time") AS "time__max" FROM "core_message" U0 GROUP BY U0."mmsi")) I'd appreciate if you could propose a better solution for this problem. Thanks ! -
Djano inineformset save and delete
I am trying to do something really simple. But, there is a problem I cannot figure out, so I appreciate any help. Here is my code: # in views.py def post(self, request, *args, **kwargs): assembly_id = kwargs.get('assembly_id', None) active_assembly_project = assembly_instance = Assembly.objects.get(id = assembly_id) # Second, if the specified assembly does not belong to the active development project, then PartTypeInlineFormSet = inlineformset_factory(Assembly, PartType, formset = BasePartTypeInlineFormSet, fields = __all__ can_delete = True ) kwargs = {'assembly_project': active_assembly_project, } part_type_formset = PartTypeInlineFormSet(request.POST, request.FILES, instance = assembly_instance) if part_type_formset.is_valid(): part_types_cd = part_type_formset.cleaned_data forms_marked_for_deletion = part_type_formset.deleted_forms # <== Correctly identifies the forms marked for deletion part_type_formset_kwargs = {'assembly_project': active_assembly_project,} assembly_development_types = part_type_formset.save(**part_type_formset_kwargs) # forms.py class BaseDevelopmentTypeInlineFormSet(BaseInlineFormSet): def clean(self, *args, **kwargs): forms = self.forms if any(self.errors): errors = self.errors return for form in self.forms: should_delete_form = form.cleaned_data.get('DELETE', False) print ('should_delete_form: ', should_delete_form) # <= Correctly shows the forms that have 'DELETE': on if self.can_delete and should_delete_form: continue def save(self, commit = True, *args, **kwargs): ''' Custom save to save the development projects when saving development types''' the_assembly_project = kwargs.pop('assembly_project', None) instances = super(BasePartTypeInlineFormSet, self).save(commit=False, *args, **kwargs) assert False #<== gives me instances = [] !!! for instance in instances: if commit: instance.save() else: …