Python Forum
Creating few models with one submit depending on the selected items from multiselect?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Creating few models with one submit depending on the selected items from multiselect?
#1
A'm beginner at Django. Sry for my bad english. I'm ukrainian)

There are 2 models: 1.RelationType; 2. RequestRelation. The second model is connected with the first through MTM field.

There is a multiple select form based on a list of “relationship types”. Need to create few models of when RequestRelation submitting, depending on the selected items of the multi-select?

F.e., *if "husband / wife / son" is chosen, need to create 3 models accordingly*. Distinctive in them are only the types of relationships.

The form.is_valid(), the correct values ​​come.

But so far, only one model is created, with lists of all selected relationship types.

Also in my code there is a bug. The model is created immediately when the page is loaded, not when it is submitted.

Thank you in advance.

models.py

    class RelationType(models.Model):
        title = models.CharField(max_length=40)
    
        def __unicode__(self):
            return self.title
    
    class RelationRequest(models.Model):
        creator = models.ForeignKey(User, related_name='creator')
        relation = models.ForeignKey(User, related_name='relation')
        type_of_relation = models.ManyToManyField(RelationType, related_name='type_relation',
            verbose_name=_('type_relation'))
        status = models.BooleanField(_('status'), default=False)
    
        created = models.DateTimeField(_('created'), auto_now_add=True)
        updated = models.DateTimeField(_('updated'), auto_now=True)
html

    <form action="" method="POST" multiple="multiple">
        {% csrf_token %}
        {{ relation_form.type_of_relation }}
        <input type='submit' value='ok'>
    </form>
forms.py
    class RelationRequestForm(forms.ModelForm):
        class Meta:
            model = RelationRequest
            fields = ('type_of_relation',)
            widgets = {
                'type_of_relation': forms.SelectMultiple(
                    attrs={
                        'class': 'select2',
                        'style': 'width: 235px',
                    }
                ),
            }
    
        def __init__(self, *args, **kwargs):
            super(RelationRequestForm, self).__init__(*args, **kwargs)
            self.fields['type_of_relation'].empty_label = None
            self.fields['type_of_relation'] = forms.ModelMultipleChoiceField(queryset=RelationType.objects.all())
    
        def clean(self):
            type_of_relation = self.cleaned_data.get('type_of_relation')
views.py

    def post(self, request, *args, **kwargs):
            self.object = self.get_object()
            relation_form = RelationRequestForm(request.POST)
            if relation_form.is_valid():
                req_rel = relation_form.save(commit=False)
                req_rel.creator = request.user
                relation_user_id = int(filter(lambda x: x.isdigit(), request.path))
                req_rel.relation = User.objects.get(id = relation_user_id)
                req_rel.save()
                relation_form.save_m2m()
            context = self.get_context_data(relation_form = relation_form)
            return self.render_to_response(context)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Photo After using models.Model on my class Im getting 'ImproperlyConfigured' error Django khavro 1 2,167 Apr-05-2021, 03:11 PM
Last Post: SheeppOSU
  Using Python request without selenium on html form with javascript onclick submit but eraosa 0 3,163 Jan-09-2021, 06:08 PM
Last Post: eraosa
  Django - Am I in the right direction for creating the models of my Phone Review appli shawnmichaels583583 0 1,824 Oct-15-2019, 06:25 AM
Last Post: shawnmichaels583583
  Posting html values to views/models in Django Malt 1 2,151 Sep-04-2019, 01:44 PM
Last Post: fishhook
  data base models IMuriel 1 2,098 Jan-14-2019, 08:55 PM
Last Post: Gribouillis
  Error while creating new Creating Models on Django aniyanetworks 2 5,311 Jul-13-2018, 12:57 PM
Last Post: aniyanetworks
  Submit button not working when using form tuannv562 0 5,547 Apr-23-2018, 03:49 AM
Last Post: tuannv562
  submit element from a list into a post request Godzilla 0 3,940 Mar-24-2018, 02:35 PM
Last Post: Godzilla

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020