如何将隐藏字段放入表单集中并实例化该值?

How to put a hidden fields in a formset and instantiate this value?

我希望我可以从我的表单集中删除用户并实例化值 "logged_user" 这是用户登录... 如何实例化字段的值?

我有这个 views.py :

def access(request, instance):
    replies = Reply.objects.all()
    pages = Page.objects.all()
    numPages = Page.objects.get(pk=instance)
    questions = Question.objects.filter(page=instance)
    length_questions = len(questions)
    logged_user = get_logged_user_from_request(request)
    ReplyFormSet = modelformset_factory(model=Reply, fields=('question', 'answer', 'user'), extra=length_questions, can_delete=True)
    if request.method == 'POST':  
        formset = ReplyFormSet(request.POST, queryset=Reply.objects.none())
        if formset.is_valid():
            formset.save()
            return HttpResponseRedirect('/baseVisite/')
        else:
            messages.add_message(request, messages.INFO, 'Le formulaire est incorrecte !')
            return render_to_response('polls/error.html', context_instance=RequestContext(request))
    else:
        formset = ReplyFormSet(queryset=Reply.objects.none())
    return render_to_response('polls/access.html', {
     'formset': formset,
     'questions':questions,
     'logged_user':logged_user,
     'numPages' : numPages
     })

和这个 forms.py :

class ReplyForm(forms.ModelForm):
    class Meta:
        model = Reply
        fields = ('question','answer','user')

我的模板:

<form method="POST" action="">
    {{ formset.management_form }} {% csrf_token %}
    <table>
      <br>{{ formset.as_table }}<br>

    </table><br>
    <center><input type="submit" value="Submit" class="btn btn-success" />
</form>

编辑:

def get_logged_user_from_request(request):
    if 'logged_user_id' in request.session:
        logged_user_id = request.session['logged_user_id']
        # On cherche un étudiant ici
        if len(Etudiant.objects.filter(id=logged_user_id)) == 1:
            return Etudiant.objects.get(id=logged_user_id)
        # On cherche un Employe ici
        elif len(Employe.objects.filter(id=logged_user_id)) == 1:
            return Employe.objects.get(id=logged_user_id)
        # Si on trouve rien -->
        else:
            return None
    else:
        return None

我发现自己有多种形式,我可以在其中选择用户我希望用户定义连接的人"logged_user"

从字段列表中排除用户,

ReplyFormSet = modelformset_factory(model=Reply, fields=('question', 'answer'), extra=length_questions, can_delete=True)

然后在保存表单集时设置它。

if request.method == 'POST':  
    formset = ReplyFormSet(request.POST, queryset=Reply.objects.none())
    if formset.is_valid():
        new_instances = formset.save(commit=False)
        for new_instance in new_instances:
            new_instance.user = logged_user
            new_instance.save()