Je suis confronté à un problème lors de l'édition/mise à jour d'un formulaire avec un champ manytomany. Je ne sais pas comment implémenter la logique pour enregistrer un formulaire avec un champ manytomany. Le modèle Sam est un utilisateur, qui gère différents comptes et sur une période de temps les comptes qu'il gère changent. Il devrait donc y avoir de la flexibilité dans l'ajout ou la suppression des comptes qu'il gère via le Samprofileupdateform qui inclut un champ manytomany pour Account. Pouvez-vous s'il vous plaît m'aider comment mettre en œuvre cela?Comment éditer/mettre à jour un modèle via Django avec un champs manytomany?
models.py
class Account(models.Model):
accnt_nagp = models.CharField(max_length=30, unique=True, primary_key=True)
#sam_name = models.ManyToManyField(Sam)
def __unicode__(self):
return self.accnt_nagp
class Sam(models.Model):
SUNNYVALE = 'SVL'
NORTHCAROLINA = 'RTP'
EUROPE = 'EMEA'
INDIA = 'NB'
AUSTRALIA = 'AUS'
suppaccntmgr = 'SAM'
MANAGER = 'SAM_MGR'
REGION_CHOICES = (
(SUNNYVALE, 'Sunnyvale'),
(NORTHCAROLINA, 'RTP'),
(EUROPE,'EMEA'),
(INDIA,'NB'),
(AUSTRALIA,'AUS'),
)
DESIGNATION_CHOICES = (
(suppaccntmgr, 'SAM'),
(MANAGER, 'SAM_MGR'),
)
user = models.OneToOneField(User)
designation = models.CharField(max_length=8, choices=DESIGNATION_CHOICES,
default=suppaccntmgr)
mgr = models.ForeignKey(SamMgr)
accnt = models.ManyToManyField(Account)
def __unicode__(self):
return u'%s' % self.user.username
Views.py:
class SamProfileUpdateView(views.LoginRequiredMixin, UpdateView):
model = Sam
form_class = SamProfileUpdateForm
success_url = reverse_lazy('risklist')
template_name = 'samrunbook/samaccntassociate.html'
forms.py
class SamProfileUpdateForm(forms.ModelForm):
class Meta:
model = Sam
fields = ('accnt','mgr')
def __init__(self, *args, **kwargs):
super(SamProfileUpdateForm, self).__init__(*args, **kwargs)
self.helper = FormHelper(self)
self.helper.form_method = 'POST'
self.helper.form_class = 'form-horizontal'
self.helper.label_class = 'col-md-3'
self.helper.field_class = 'col-md-6'
self.helper.layout = Layout(
'accnt',
'mgr',
FormActions(
Submit('map', 'Map Your Account', css_class="btn-primary col-md-offset-3 col-md-6")
)
)
templates.py
{% extends 'samrunbook/base_risk.html' %}
{% load crispy_forms_tags %}
{% block content %}
<h3 class="col-md-offset-5">Login | Risk Register</h3>
{% csrf_token %}
{% crispy form %}
{% endblock %}