I wish I could remove the user from my formset and it instantiates the value "logged_user" which is the user logged ... How can I do to instantiate the value of a field?
I have this 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
})
and this forms.py :
class ReplyForm(forms.ModelForm):
class Meta:
model = Reply
fields = ('question','answer','user')
my template :
<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>
EDIT :
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
I find myself with multiple form where I can choose the user off I would like the user to define what the person is connected "logged_user"
Exclude the user from the list of fields,
then set it when you are saving the formset.