quiero crear un formulario del tipo:
<form>
<fieldset>
<legend>Deportes:</legend>
<input type="checkbox" name="futbol" value="3"> futbol<br>
<input type="checkbox" name="basket" value="4"> basket<br>
<input type="checkbox" name="natacion" value="6"> natación<br>
<input type="checkbox" name="voley" value="7"> voley<br>
</fieldset>
<fieldset>
<legend>Música:</legend>
<input type="checkbox" name="clasica" value="8"> Clásica<br>
<input type="checkbox" name="rock" value="5"> Rock<br>
<input type="checkbox" name="pop" value="10"> Pop<br>
</fieldset>
<input type="submit" name="submit" value="guardar">
</form>
en models.py tengo:
class User(AbstractUser):
name = models.CharField(_('Name of User'), blank=True, max_length=255)
surname = models.CharField(_('Surname'), blank=True, max_length=255)
preferences = models.ManyToManyField(Preferences, related_name='preferences_user', blank=True)
class Meta:
ordering = ['username']
def __str__(self):
return self.username
def get_absolute_url(self):
return reverse('users:detail', kwargs={'username': self.username})
class Preferences(models.Model):
name = models.CharField(_('Preference'), blank=False, max_length=100)
parent = models.IntegerField(_('Parent preference'))
def __str__(self):
return self.name
class Meta:
ordering = ('parent',)
En la tabla "Preferences" tengo los datos de la siguiente manera:
ID name parent
1 Deportes 0
2 Música 0
3 futbol 1
4 basket 1
5 Rock 2
etc...
he probado de varias maneras con UpdateView y forms.. etc y no consigo hacer que las preferencias en las que parent == 0 ponerlas como "legend" en el en la etiqueta html "fieldset"
Gracias
Vale, añado la vista y form
forms.py
class PreferencesForm(forms.ModelForm):
class Meta:
model = User
fields = ('preferences',)
widgets = {'preferences': forms.CheckboxSelectMultiple(attrs={'class': 'mi-clase'})}
views.py
class UserPreferences(LoginRequiredMixin, UpdateView):
model = User
template_name_suffix = '_preferences_form'
form_class = PreferencesForm
# send the user back to their own page after a successful update
def get_success_url(self):
return reverse('users:detail',
kwargs={'username': self.request.user.username})
def get_object(self):
# Only get the User record for the user making the request
return User.objects.get(username=self.request.user.username)
def get_context_data(self, **kwargs):
context = super(UserPreferences, self).get_context_data(**kwargs)
context['form1'] = Preferences.objects.all()
return context
Template
<form method="post" action="{% url 'users:update_preferences' %}" enctype="multipart/form-data">
{% csrf_token %}
{{ form }}
<button type="submit" class="btn">Update</button>
</form>