一次提交即可创建多个模型

时间:2019-03-18 03:07:24

标签: python django

是Django的初学者。抱歉我的英语不好)

有2种型号:1。#carouselExampleControls3 {opacity: 0; transition: 1.5s opacity;} #carouselExampleControls3.active {opacity: 1; cursor: pointer; animation: zoomin 1.5s alternate infinite; animation-iteration-count: 1; animation-fill-mode: forwards;} ; 2. RelationType。第二个模型通过RequestRelation与第一个模型连接。

有一个基于“关系类型”列表的多选表单。是否需要根据MTM field的选定项目来创建RequestRelation提交时的几种模型?

例如,如果选择“丈夫/妻子/儿子”,则需要相应地创建3个模型。它们之间的区别仅在于关系的类型。

multi-select是正确的值。

但是到目前为止,仅创建了一个模型,其中列出了所有选定的关系类型。

在我的代码中也有一个错误。该模型是在页面加载后立即创建的,而不是在提交页面时创建的。

谢谢。

models.py

form.is_valid()

html

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)

forms.py

<form action="" method="POST" multiple="multiple">
    {% csrf_token %}
    {{ relation_form.type_of_relation }}
    <input type='submit' value='ok'>
</form>

views.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)

呈现的HTML

@method_decorator(login_required, name='dispatch')
class ProfileView(DetailView):
    model = User
    queryset = User.objects.filter(is_active=True)

    def get(self, request, *args, **kwargs):
        self.object = self.get_object()
        content_type = ContentType.objects.get_for_model(User)
        content_type_post = ContentType.objects.get_for_model(Post)
        posts = Post.objects.filter(
            enabled=True,
            for_content_type=content_type,
            for_object_id=self.object.id,
        )
        comments = Comment.objects.filter(
            content_type=content_type_post, object_id__in=posts.values_list('id')
        ).order_by('-id')
        posts = posts.prefetch_related(
            'from_content_type', 'for_content_type',
            'from_object', 'for_object',
            Prefetch('comments', queryset=comments),
        )
        if request.GET.get('page'):
            posts = posts.filter(
                created_at__lte=datetime.strptime(
                    request.GET.get('time'), '%Y%m%d%H%M%S'
                )
            )

        posts = paginator_factory(request, posts, 20)
        post_list = []
        for post in posts.object_list:
            comments = post.comments.all()[:3]
            comment_form = CommentForm(prefix=post.id)
            post_list.append({
                'post': post,
                'comment_form': comment_form,
                'comments': comments
            })
        form_set = formset_factory(PostImageForm, extra=1)
        form = PostForm()
        popup_search_form = PeoplePopupSearchForm()
        user_confirmeds = UserConfirm.objects.filter(
            sender=request.user, is_real=True
        ).count()
        accept_request_all = UserConfirm.objects.filter(
            recipient=request.user,
            sender__slug=kwargs.get('slug')
        )
        accept_request = accept_request_all.filter(is_real=True)
        not_accept_request = accept_request_all.filter(is_real=False)
        circle = UserCircle.objects.get_or_create(user=request.user)[0]
        circle_users = circle.users.all()
        post_next = posts.has_next()


        context = self.get_context_data(
            form=form,
            post_list=post_list,
            form_set=form_set,
            circle_users=circle_users,
            post_next=post_next,
            time=now(),
            popup_search_form=popup_search_form,
            user_confirmeds=user_confirmeds,
            accept_request=accept_request,
            not_accept_request=not_accept_request,
        )
        if request.is_ajax():
            template_ajax = render_to_string(
                template_name='communication/post_list.html',
                context={
                    'post_list': post_list,
                    'request': request
                }
            )
            return JsonResponse({
                'success': True,
                'template': template_ajax,
                'next': post_next,
            })
        return self.render_to_response(context)

    def post(self, request, *args, **kwargs):
        self.object = self.get_object()
        relation_form = RelationRequestForm(request.POST or None)
        if relation_form.is_valid():
            for rt in relation_form.cleaned_data['type_of_relation']:
                relation_user_id = int(filter(lambda x: x.isdigit(), request.path))
                rq = RelationRequest.objects.create(
                    creator = request.user,
                    relation = User.objects.get(id = relation_user_id),
                )
                rq.type_of_relation.add(rt)
        context = self.get_context_data(relation_form = relation_form)
        return self.render_to_response(context)

1 个答案:

答案 0 :(得分:1)

ModelForm链接到您在其Meta类中指定的Model实例。 form.save_m2m()允许创建m2m连接,但根据您的情况,它将创建RelationType,据我了解,您想创建RelationRequest实例。

我建议编写一个带有Form字段的常规forms.ModelMultipleChoiceField(queryset=RelationType.objects.all()),并遍历用户输入以创建RelationRequest下您需要的所有form.is_valid()