django display ManyToManyField as a form field - django

I am trying to display a ManyToManyField in my template:
class GvtCompo(models.Model):
startDate=models.DateField(max_length=10, blank=False, null=False)
endDate=models.DateField(max_length=10, blank=False, null=False)
gvtCompo= models.CharField(max_length=1000, blank=False, null=False)
class Act(models.Model):
gvtCompo= models.ManyToManyField(GvtCompo)
In my view, I can display the object, no problem:
for gvtCompo in act.gvtCompo.all():
print gvtCompo.gvtCompo
In my template, I have a list of "GvtCompo Object" with this code (not nice):
{% for field in form %}
<div class="fieldWrapper">
{{ field.errors }}
{{ field }}
</div>
{% endfor %}
I have tried to make it nicer, but the following code just not work (nothing appears):
{% for field in form %}
{% if field.name == "gvtCompo" %}
{% for gvtCompo in field.gvtCompo.all %}
{{ gvtCompo.gvtCompo }}
{% endfor %}
{% endif %}
{% endfor %}
What's wrong?
*Edit: *
If I don't use the form but an instance of the model (act) passed to render_to_response it displays the ManyToManyField values
{% for gvtCompo in field.gvtCompo.all %}
changed to
{% for gvtCompo in act.gvtCompo.all %}
However there is not form field anymore, so it can't be modified, validated and saved!

You are skipping a step. You first need to create a form.
In forms.py you can create a ModelForm. A ModelForm is a form based on your model:
from django.forms import ModelForm
from myapp.models import Act
class ActForm(ModelForm):
class Meta:
model = Act
Then your view:
from myapp.models import Act
from myapp.forms import ActForm
def add_view(request):
if request.method == 'POST':
form = ArticleForm(request.POST)
if form.is_valid():
form.save()
else:
form = ActForm() # Creating a empty form.
return render_to_response("template.html", {
"form": form,
})
def edit_view(request):
obj = Act.objects.get(pk=1)
if request.method == 'POST':
form = ArticleForm(request.POST)
if form.is_valid():
form.save()
else:
form = ActForm(instance=obj) # Creating form pre-filled with obj.
return render_to_response("template.html", {
"form": form,
})
If you want to implement this situation more than once. DRY: https://docs.djangoproject.com/en/1.5/topics/class-based-views/intro/#handling-forms-with-class-based-views
In your template.html:
{{ form }}
Disclaimer: This code is not tested.
https://docs.djangoproject.com/en/1.5/ref/forms/
https://docs.djangoproject.com/en/1.5/topics/forms/modelforms/
Update:
You can pass multiple forms to one <form>...</form> in your template. So create two forms. One Act form (see above) and one GvtCompo formset. The formset contains all GvtCompo's that have a relation to Act.
from django.forms.models import modelformset_factory
act = Act.objects.get(pk=1) #The same act as you used to create the form above.
GvtFormSet = modelformset_factory(GvtCompo)
formset = GvtFormSet(queryset=act.gvtCompo.all())
Template can be:
<form ...>
{% for field in form %}
{% if field.name == "gvtCompo" %}
{{ formset }}
{% else %}
{{ field }}
{% endif %}
{% endfor %}
</form>
Note: If your form and formset have colliding field names use prefix="some_prefix":
Django - Working with multiple forms

When looping over the form, it should be:
{% for field in form %}
{% if field.name == "gvtCompo" %}
{% for gvtCompo in form.instance.gvtCompo.all %}
{{ gvtCompo.gvtCompo }}
{% endfor %}
{% endif %}
{% endfor %}
field itself has no related field.gvtCompo.

Related

Manually laying out fields from an inline formset in Django

I have created an inline formset for the profile information which is added to the user form:
UserSettingsFormSet = inlineformset_factory(
User,
Profile,
form=ProfileForm,
can_delete=False,
fields=(
"title",
...
),
)
class SettingsView(UpdateView):
model = User
template_name = "dskrpt/settings.html"
form_class = UserForm
def get_object(self):
return self.request.user
def get_context_data(self, **kwargs):
context = super(SettingsView, self).get_context_data(**kwargs)
context["formset"] = UserSettingsFormSet(
instance=self.request.user, prefix="user"
)
return context
This works and calling {formset} in the template file renders the complete form for both User and Profile.
Yet, I would like to lay out the individual inputs myself. This works for fields belonging to User:
<input
type="text"
name="{{form.last_name.html_name}}"
id="{{form.last_name.auto_id}}" value="{{form.last_name.value}}">
But doing the same for fields of the formset does not work. Here the attribute formset.form.title.value appears to be empty. All other attributes, e.g. formset.form.title.auto_id exist though.
Why does {{formset}} render completely with values but values are missing individually?
To answer your questions shortly:
The reason why profile fields are not showing is that they belong to a context data formset instead of form.
If you check the source code of UpdateView, it inherits from a ModelFormMixin, which defines methods related to forms, such as get_form_class.
Why this matter?
Because get_form_class grab the attribute form_class = UserForm or from your model attribute, and pass an context variable to your template called form. Thus in your template, the form variable only refers to UserForm, not your formset.
What is a context variable?
To make it simple that is a variable passed to your template, when your view is rendering the page, it will use those variables to fill in those {{}} slots.
I am sure you also use other generic views such as ListView, and probably you have overwritten the get_context_data method. That basically does the same thing to define what data should be passed to your template.
So how to solve?
Solution A:
You need to use formset in your template instead of form, however this would be quite complicated:
<form action="" method="post" enctype="multipart/form-data">
{{ form_set.management_form }}
{{ form_set.non_form_errors }}
{% for form in formset.forms %}
{% for field in form.visible_fields %}
{# Include the hidden fields in the form #}
{% if forloop.first %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% endif %}
{{ field.errors.as_ul }}
{{ field }}
{% endfor %}
{{ form.non_field_errors }}
{% endfor %}
{# show errors #}
{% for dict in formset.errors %}
{% for error in dict.values %}
{{ error }}
{% endfor %}
{% endfor %}
</form>
Solution B:
Pass correct variable in your view, which will be easier to use:
class SettingsView(UpdateView):
model = User
#...
def get_context_data(self, **kwargs):
data = super().get_context_data(**kwargs)
if self.request.POST:
data["formset"] = UserSettingsFormset(self.request.POST, instance=self.object)
else:
data["formset"] = UserSettingsFormset(instance=self.object)
return data
Then in your template you can simply do:
<h1>User Profile</h1>
<form method="post">{% csrf_token %}
{{ form.as_p }}
<h2>Profile</h2>
{{ formset.as_p }}
<input type="submit" value="Save">
</form>
I think in your formest the form attribute is not necessary form=ProfileForm,, by default inlineformset_factory will look for a ModelForm as form, and in this case is your User model.
Solution C: Is that really necessary to use a formset? Formest is usually used to generate multiple forms related to an object, which means should be considered to use in a many-to-one relationship.
Usually, for the case of User and Profile, they are inOneToOne relationship, namely, each user only has one profile object. In this case, you can just pass your profile form into your template:
class SettingsView(UpdateView):
model = User
template_name = "dskrpt/settings.html"
form_class = UserForm
#...
def get_context_data(self, **kwargs):
data = super().get_context_data(**kwargs)
profile = self.request.user.profile
# your Profile model should have an one-to-one field related with user, and related name should be 'profile'
# or profile = Profile.objects.get(user=self.request.user)
data['profile_form'] = ProfileForm(instance=profile)
return data
Then in your template, you can refer to the profile form by profile_form only.
As a conclusion, I will suggest using solution C.
More detailed example for inline formsets: check this project

How to get value especific from ModelForm field in django framework?

I am creating one web system and need to get one value especific from ModelForm for store in another system, in addition to storing in django. Example: get field "nome" from Model Form for to store in LDAP server
model.py
class Orientado(models.Model):
nome = models.CharField(max_length=100,)
telefone = models.CharField(max_length=20)
email = models.EmailField(max_length=100)
forms.py
class OrientadoForm(forms.ModelForm):
class Meta:
model = Orientado
fields = ['nome', 'telefone','email']
views.py
def person_new(request):
form = OrientadoForm(request.POST or None, request.FILES or None)
autor = User.objects.get(username=request.user.username)
if form.is_valid():
form.save()
return redirect('person_list')
return render(request, 'person_form.html',{'form': form, 'autor': autor})
html
{% block main %}
<h3>Novo Orientado</h3>
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.non_field_errors }}
{{ form.source.errors }}
{{ form.source }}
{{ form|bootstrap }}
<button type="submit" class="btn btn-primary">Salvar</button>
</form>
{% endblock %}

Django: ModelFormSet saving first entry only

Update:
The issue seemed to be in the coding for Django-formset. I was processing it as an inline formset and not a model formset. The answer below was also correct. Thanks!
I am working with a model formset for an intermediate model. I am using django-formset js to add additional formset fields on the template. Most everything works OK except that when I go to save the formset only the first entry is being saved to the DB. The first entry is saved and assigned correctly but any after than just disappear. It is not throwing any errors so I am not sure what is going wrong. Thanks!
The Model
class StaffAssignment(models.Model):
study = models.ForeignKey(Study, related_name='study_set', null=True, on_delete=models.CASCADE)
staff = models.ForeignKey('account.UserProfile', related_name='assigned_to_set', null=True, on_delete=models.CASCADE)
role = models.CharField(max_length=100, null=True)
assigned_on = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ('-role',)
def __str__(self):
return '{} is assigned to {}'.format(self.staff, self.study)
The Form:
class AddStaff(forms.ModelForm):
model = StaffAssignment
fields = ('staff',)
def __init__(self, *args, **kwargs):
super(AddStaff, self).__init__(*args, **kwargs)
for field in self.fields:
self.fields[field].widget.attrs.update({'class': 'form-control'})
The View:
def add_staff(request, study_slug):
study = get_object_or_404(Study, slug=study_slug)
staff_formset = modelformset_factory(StaffAssignment, form=AddStaff, fields=('staff',), can_delete=True)
if request.method == 'POST':
staffList = staff_formset(request.POST, request.FILES)
if staffList.is_valid():
for assignment in staffList:
assigned = assignment.save(commit=False)
assigned.study = study
assigned.role = assigned.staff.job_title
assigned.save()
return HttpResponseRedirect(reverse('studies:studydashboard'))
else:
HttpResponse('Something is messed up')
else:
staffList = staff_formset(queryset=StaffAssignment.objects.none())
return render(request, 'studies/addstaff.html', {'staffList': staffList, 'study': study})
The Template:
<form action="{% url 'studies:addstaff' study.slug %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="box-body">
{% for list in staffList %}
<div class="form-group" id="formset">
{% if list.instance.pk %}{{ list.DELETE }}{% endif %}
{{ list.staff }}
{% if list.staff.errors %}
{% for error in list.staff.errors %}
{{ error|escape }}
{% endfor %}
{% endif %}
</div>
{% endfor %}
{{ staffList.management_form }}
</div>
<div class="box-footer">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
You are not including the primary key field in the template, as required by the docs. Add
{% for list in staffList %}
{{ list.pk }}
...
{% endfor %}

Django: Only update fields that have been changed in UpdateView

I'm using an UpdateView to update a series of fields. However, I only want fields that have been modified to be saved to the database. If a value was not provided for a field during update process, I want the previous value to be used as the default. If a new value was provided for a field then only that field should be updated. How do I go about accomplishing this?
#views.py
class AccountUpdate(UpdateView):
""" Updates an account; unchanged fields will not be updated."""
context_object_name = 'account'
form_class = UpdateForm
template_name = 'accounts/update_account.html'
success_url = '/accounts/home'
def get_object(self, queryset=None):
return self.request.user
def form_valid(self, form):
clean = form.cleaned_data
#encrypt plain password
form.instance.password = hash_password(clean['password'])
context = {}
self.object = context.update(clean, force_update=False)
return super(AccountUpdate, self).form_valid(form)
#templates
{% extends 'base.html' %}
<title>{% block title %}Update Account{% endblock %}</title>
{% block content %}
{{ account.non_field_errors }}
<div class="errors" style="list-style-type: none;">
{% if account.first_name.errors %}{{ account.first_name.errors }}{% endif %}
{% if account.last_name.errors %}{{ account.last_name.errors }}{% endif %}
{% if account.email.errors %}{{ account.email.errors }}{% endif %}
{% if account.password.errors %}{{ account.password.errors }}{% endif %}
{% if account.username.errors %}{{ account.username.errors }}{% endif %}
</div>
<form action="" name="edit" method="post">
{% csrf_token %}
<ul>
<li>Fullname</li>
<li> {{ form.first_name }}{{ form.last_name }}</li>
<li>Email</li>
<li>{{ form.email }}</li>
<li>Password</li>
<li>{{ form.password }}</li>
<li>Username</li>
<li>{{ form.username }}</li>
</ul>
<ul>
<li><input type="submit" value="update account"></li>
</ul>
</form>
<ul>
<li class="nav">cancel changes</li>
</ul>
{% endblock %}
All the fields are also declared as required in models.py. Currently the form only works if i provide a value for each field.
i'm using a custom hash during update process to encrypt passwords. When i visit the edit page and hit update button, the old password in its current encrypted form gets re-encrypted hence losing the old password
I would handle that by not including password itself in the form. Instead, I would add a new field (something like new_password) to allow entering a new password. Then, in your is_valid method, set the password to the hashed value of that field if there's content.
You should also use the sensitive value filtering tools to prevent user passwords from showing up in emailed error reports.
class UpdateForm(forms.ModelForm):
class Meta:
model = user
fields = ('first_name', 'last_name', 'email', 'username')
new_password = forms.CharField(required=False, widget=forms.widgets.PasswordInput)
And then in your view:
#sensitive_variables('new_password')
#sensitive_post_parameters('new_password')
def form_valid(self, form):
clean = form.cleaned_data
new_password = clean.get('new_password')
if new_password:
#encrypt plain password
form.instance.password = hash_password(new_password)
return super(AccountUpdate, self).form_valid(form)
The easiest way would be to pre-populate the fields with what's already there.
Do this on the template with {{ account.name }} or whatever.

Retrieving models from form with ModelMultipleChoiceField

I am having difficulties with forms, specifically ModelMultipleChoiceField.
I've pieced together this code from various examples, but it sadly doesn't work.
I would like to be able to:
Search for some Works on work_search.html
Display the results of the search, with checkboxes next to each result
Select the Works I want, via the checkboxes
After pressing Add, display which works were selected.
I believe everything is okay except the last part. The page simply displays "works" :(
Here is the code - sorry about the length.
Models.py
class Work(models.Model):
title = models.CharField(max_length=200)
artist = models.CharField(max_length=200)
writers = models.CharField(max_length=200)
def __unicode__(self):
return self.title + ' - ' + self.artist
forms.py
class WorkSelectForm(forms.Form):
def __init__(self, queryset, *args, **kwargs):
super(WorkSelectForm, self).__init__(*args, **kwargs)
self.fields['works'] = forms.ModelMultipleChoiceField(queryset=queryset, widget=forms.CheckboxSelectMultiple())
views.py
def work_search(request):
query = request.GET.get('q', '')
if query:
qset = (
Q(title__icontains=query) |
Q(artist__icontains=query) |
Q(writers__icontains=query)
)
results = Work.objects.filter(qset).distinct()
form = WorkSelectForm(results)
return render_to_response("work_search.html", {"form": form, "query": query })
else:
results = []
return render_to_response("work_search.html", {"query": query })
def add_works(request):
#if request.method == POST:
form = WorkSelectForm(request.POST)
#if form.isvalid():
items = form.fields['works'].queryset
return render_to_response("add_works.html", {"items":items})
work_search.html
{% extends "base.html" %}
{% block content %}
<h1>Search</h1>
<form action="." method="GET">
<label for="q">Search: </label>
<input type="text" name="q" value="{{ query|escape }}">
<input type="submit" value="Search">
</form>
{% if query %}
<h2>Results for "{{ query|escape }}":</h2>
<form action="add_works" method="post">
<ul>
{% if form %}
{{ form.as_ul }}
{% endif %}
</ul>
<input type="submit" value="Add">
</form>
{% endif %}
{% endblock %}
add_works.html
{% extends "base.html" %}
{% block content %}
{% if items %}
{% for item in items %}
{{ item }}
{% endfor %}
{% else %}
<p>Nothing selected</p>
{% endif %}
{% endblock %}
In add_works, you're not constructing your WorkSelectForm the right way. It's expecting as a first parameter the queryset of possible/authorized choices, then the POST data.
Also, you're not accessing the selected works correctly from the form. You have to use is_valid method on the form, then use cleaned_data as described in the doc.
From what I see in your work_search view, there's no restriction on which Work objects you can search then add to the result, so you could do simply:
def add_works(request):
#if request.method == POST:
form = WorkSelectForm(Work.objects.all(), request.POST)
if form.is_valid():
# the items are in form.cleaned_data['works']
items = form.cleaned_data['works']
return render_to_response("add_works.html", {"items":items})
else:
# handle error case here
...