I have a form with only one field (name of family members).
class FamilyMemeberItem(forms.Form):
name= forms.CharField(label=_('name'), max_length=20)
Now I want my form be sorted (arbitrary order) defined by the user. For example in a family, I want to show A first, then B and then C, while the creation sequence may be C, B and A. Is there anyway to do that?
I searched and realized I should add an order field to my form and override the __iter__() method. Is that the only way? If there is no way to do that without change in form?
And could anyone please tell me about the field can_order of formset_factory? When I add it, an extra filed is loaded next to my form, and that's and integer presenting the number of that field. Can I change and save that so that the order changes?
I answered a similar question you posted.
I'll just repeat the last part here:
If you want to store the order in the database, you need to define a new field in you model and store the order in that. The order of formsets is only present inside a single request/response, after that its gone.
Related
I have a django model form for which I allowed partial form save since its a long form. Now I want the user to come back and complete the form later.
There is one hindrance however that my database cannot accept duplicate entries with same primary key. So should I remove primary key in my database to solve this or is there another way to make it possible? Suggestions please.
Why not keep only one row per user for that form? Just add one boolean field to check whether the form is submitted or is a draft. Something like is_submitted=models.Boolean(default=False). Keep updating the row with the new values on each partial save (a separate button for Save or an AJAX call for auto save).
When the form is submitted, just mark the field is_submitted = True and perform whatever actions you want after that.
Let say I have two fields in a django form country and state.I want the values of state to relatively change with the values of country.i.e. I want the state field to list out the states of the country that user has selected. Also the state field should be empty during form initiation.I know that this can be done using java script and other scripts.But,I would like to know if there are any conventional methods exists in django to do the same.???
Sounds like you need to create a model for Country and State.
State model should have a foreign key linking to Country. This means many states can be related to one country. Then, populate the tables with all countries and states you want.
In your form, you can override the 'init' method with custom behavior. So, if you have declared a field 'state' then you can do something like self.fields['state'].choices = State.object.filter(country_id=some_country_id). This assumes you have some_country_id already and you can pass this through as a kwarg during instantiation.
I want to attach a field value (id) to a QS like below, but Django throws a 'str' object has no attribute 'lookup' error.
Book.objects.all().annotate(some_id='somerelation__id')
It seems I can get my id value using Sum()
Book.objects.all().annotate(something=Sum('somerelation__id'))
I'm wondering is there not a way to simply annotate raw field values to a QS? Using sum() in this case doesn't feel right.
There are at least three methods of accessing related objects in a queryset.
using Django's double underscore join syntax:
If you just want to use the field of a related object as a condition in your SQL query you can refer to the field field on the related object related_object with related_object__field. All possible lookup types are listed in the Django documentation under Field lookups.
Book.objects.filter(related_object__field=True)
using annotate with F():
You can populate an annotated field in a queryset by refering to the field with the F() object. F() represents the field of a model or an annotated field.
Book.objects.annotate(added_field=F("related_object__field"))
accessing object attributes:
Once the queryset is evaluated, you can access related objects through attributes on that object.
book = Book.objects.get(pk=1)
author = book.author.name # just one author, or…
authors = book.author_set.values("name") # several authors
This triggers an additional query unless you're making use of select_related().
My advice is to go with solution #2 as you're already halfway down that road and I think it'll give you exactly what you're asking for. The problem you're facing right now is that you did not specify a lookup type but instead you're passing a string (somerelation_id) Django doesn't know what to do with.
Also, the Django documentation on annotate() is pretty straight forward. You should look into that (again).
You have <somerelation>_id "by default". For example comment.user_id. It works because User has many Comments. But if Book has many Authors, what author_id supposed to be in this case?
I'm using a formset to collect multiple forms worth of data on one page but something I realized is that the .as_table display for a formset is slightly suboptimal for what I'm trying to do, rather than print each form element as a new table row I was thinking of printing each form itself as an individual row and having a table header with the field names since I know my formset would have the same fields for each form instance. In this way you get a grid of data that a use can fill in. I've done it manually through the template where the form is printed but I was wondering if there was any way I could override formset.as_table to print it in that form rather than in the way it's presently done. Is this possible, has it already been done somewhere or if not how would you suggest I go about it?
You can always create your own Formset (and possibly Form) subclass that overrides the as_table method to output the forms any way you want.
My suggestion, though, is to consider using django-crispy-forms and good CSS definitions.
Override as_table in the class you use for the formset (not the class that uses the formset). Super() the as_table into a variable. Convert that to a string, then repr. Replace "\n" with an empty string. Remove the quote marks at the beginning and end of the repr. Convert that to a string. Call the mark_safe method of the django framework to the resulting string, and return that.
I have a model in my django project called "change" and it has a field called "change_type". There are multiple values within the change_type field to include "move", "new", "edit" and others with new types being added randomly over any given period of time. I am currently using normal django queries to select groups of entries within the change model.
Is there a quick method to determine what unique entries are in the change_type field? Is there a quick method to return a count of each entry type?
After finding the solution, it is really simple.
Change.objects.all().values('change_type').distinct()
Putting it together:
occurrences = {}
change_types = Change.objects.values_list('change_type', flat=True).distinct()
for type in change_types:
occurrences[type] = Change.objects.filter(change_type=type).count()
http://docs.djangoproject.com/en/dev/topics/db/managers/ maybe that will be helpful for You.
This can now be much more effectively implemented using aggregation:
Change.objects.values('change_type').annotate(Count('change_type'))
The output contain change_type__count field for each respective change_type.