Django Formset without instance - python

In this Django Doc explain how to create a formset that allows you to edit books belonging to a particular author.
What I want to do is: Create a formset that allows you to ADD new book belonging to a NEW author... Add the Book and their Authors in the same formset.
Can you gime a light? thanks.

When you're instantiating the form and formset for the initial display, you don't need to provide an instance - so you will just get blank forms.
When you pass in the data on POST, you can do the form first, save it, and get an instance. Then you can pass that instance into the formset, so that it correctly saves the related objects.

This depends on whether you're doing it yourself, or using the built-in admin.
If you're using the admin, you can use inlines.
If you're doing this in your own application, then it's up to you. Create a single form which has fields for a new author and book. When the user submits the form, it's your job to create the new records.

Related

How can I reuse django form for searching?

I am programming an application in django, and I have a model where I defined some fields that are necessary to be filled. This way, when te user doesn't fill one of these fields, Django authomatically indicates to the user to fill it to create the specific object defined by the model.
But myquestion comes here: I want to reuse the same form to search objects defined by that model. And in this case, all the fields that before were necessary, now are OPTIONAL. But, as I have already defined the model so that the fields are necessary, django doesn´t let me define those fields as optional.
Is there any way to reuse that form where the fields are necessary, but making them OPTIONAL? Or I must create another different model or form in html? I know that creating another form manually in the html code the problem is solver, but I have curiosity to know if it can be reused.
Thank you so much!
You can programmatically change properties of a field within a form using its fields dictionary. So you could create a new form class that is derived from your current form class and in its __init__ set the required property of the fields you desired to be optional to be False like so:
self.fields['title'].required = False

Django form to create several objects with one-to-one relation

I have several models with one-to-one relation. For example
class Task(models.Model):
initial_comment = models.OneToOneField('Comment')
# A pack of other fields
class Comment(models.Model)
body = RichTextField()
# A pack of other fields
I want to create "create view" based on form, that gives user ability to create task and initial comment there.
I can't use CreateView because it is based on only one model
I can't use ModelForm because it is based on only one model
I can create several forms, but I can't join them into one formset (forms are different)
I feel "inlineformset_factory" (InlineFormSet) should be used here, but I am not sure it suits best. Is there any 3rd party Django app to do that?
Sure I can create form myself, but I do not want to copy/paste all fields, their types, localized labels, validations and so on. I just want to list their names (like fields attibute).
I can also have 2 forms and support them everywhere and track dependencies manually (save comments first), like in How can create a model form in django with a one-to-one relation with another model , but I hope there has to be better solution.
If you wonder why do I need one-to-one: Comments are used heavily in other places and have different relations with different models.
The inline_formset factory is correct. There are no standard generic views for this, but there is a third party package with generic views to do what you are wanting. Its in the standard Django way of doing things.
https://github.com/AndrewIngram/django-extra-views
You probably want to use the CreateWithInlinesView for that.
Well, I found solution.
CreateWithInlinesView works perfectly with OneToOneField (after all, 1-to-1 is just a foreign key with constraint), but my main model here is Comment, not Task. So I should set Comment as model field in this view and Task as inline. It looks silly. I will create custom form or review my model structure.

Saving additional information to the database conditionally when using a modelfrom in django

I have a modelform and aside from the fields on the form i need to update one more column in the database depending on if there is a registered user submitting information or not. I read that you can use the save method with the argument "commit=False" which will create the database object but not save it to the database so i can check if the user is logged in and then also save additional information if i need to, and then call save myself. Does this seem like a reasonable approach to solve this problem ?
Yes, that is exactly the right thing to do.
if form.is_valid():
object = form.save(commit=False)
if request.user.is_authenticated():
object.user = request.user
object.save()

Django Multiple Checkbox Generation

I am trying to generate a webpage that shows a list of objects pulled from a database with a certain state. The list of objects should include a checkbox next to each object, so that if the user checks the object and presses submit, the server will change the state of that object. Since the list of objects is generated on the fly, I'm confused on how to properly write a Django form that will create the necessary checkboxes.
Any ideas?
Thanks,
Alex
You need a model formset
https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#model-formsets
This will generate a series of forms, one for each item in the queryset you give it.
Assuming the state is saved as a field on the model, you make a custom ModelForm which only has the state field (if it's a BooleanField it'll show as a checkbox by default)
https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#modelform
You can then use this custom form in your model formset:
https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#changing-the-form

Filter a User list using a UserProfile field in Django Admin

I'm trying to filter the User list in Django using a UserProfile Field... I need to implement a queue system where new users are put in a queue until an Admin approves them.
I simply added a is_in_queue boolean field to my UserProfile model... However, when displaying the user list in my Admin area, I realized that you can't filter the list using a Model's foreign key field (in this case, a field of UserProfile)
Apparently, list_display items can be callables but list_filter can't, so I can list IF a user is in the queue without a problem, but the admin would have to scroll through the whole user list to spot which ones are in the queue which makes no sense... Filtering only users that are in the queue (using userprofile.in_queue) would be much more practical...
Finally, I thought about adding a custom view to my admin area that would list only the user in the queue, but that custom view does not show up on the Admin area Index page, and putting together a whole new AdminSite only for a new filtering option seems a bit over the top...
So basically to sum it up: Can I filter my User list based on a
UserProfile field? If not, can I add a custom view that's accessible
from the front page without having to create a completely new
AdminSite only for that?
Django 1.3 fixed that - list_filter now allows to span relations:
https://docs.djangoproject.com/en/1.3/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_filter
You may want to take a look in to using a custom manager for the admin_objects of your model.
class UserAdminManager(models.AdminManager):
"""
Custom manager for the User model.
"""
def get_query_set(self):
"""
Overwrites the get_query_set to only return Users in the queue.
"""
return super(UserAdminManager, self).get_query_set().filter(userprofile__queue=True)
By overwriting the get_query_set method you can filter the results. Then just assign this to the admin_objects property of your User model.
admin_objects = UserAdminManager()
Some of the property names in my example may be wrong, as I don't know your model setup, but hopefully you get the idea.
You can research this further by checking out the django docs and searching for "custom managers".
It sounds to me like the quickest and easiest option is to add a new admin view to your application, specifically for your custom user model. See the Django admin docs for details, though it sounds like you know how to use Admin already.
Once the admin page is specific to your model, all your custom fields will no longer be foreign keys. This would make filtering easy.

Categories