I am trying to hide the submitted by field in my forms.py because I don't want user to upload the assignment on the behalf of some other user. So what I am doing is I am hiding the field but before hiding I am setting the value of logged in user to that input text using javascript but I am getting this error. (Hidden field submitted_by) This field is required. forms.py
class assignmentUploadForm(ModelForm):
class Meta:
model = Submissions
fields = ('submitted_by', 'submitted_to',
'submission_title', 'submission_file', 'submission_status')
widgets = {
'submitted_by': forms.TextInput(attrs={'class': 'form-control', 'type': 'hidden', 'id': 'user', 'value': ''}),
'submitted_to': forms.Select(attrs={'class': 'form-control'}),
'submission_title': forms.Select(attrs={'class': 'form-control'}),
}
template
<form method="post" enctype="multipart/form-data" style="margin-left: 240px;">
{% csrf_token %}
{{form.as_p}}
<input type="submit">
var name = "{{user.username}}"
document.getElementById('user').value = name;
views.py
class AddAssignmentView(CreateView):
model = Submissions
form_class = assignmentUploadForm
template_name = 'project/assignment.html'
CodePudding user response:
It would be better to not have it in the form at all.
All someone needs to do is inspect element and change the type from hidden.
You can set the value of submitted_by to the current user in the form_valid()
class assignmentUploadForm(ModelForm):
class Meta:
model = Submissions
fields = ('submitted_to', 'submission_title',
'submission_file', 'submission_status')
widgets = {
'submitted_to': forms.Select(attrs={'class': 'form-control'}),
'submission_title': forms.Select(attrs={'class': 'form-control'}),
}
class AddAssignmentView(CreateView):
model = Submissions
form_class = assignmentUploadForm
template_name = 'project/assignment.html'
def form_valid(self, form):
self.object = form.save(commit=False)
self.object.submitted_by = self.request.user
self.object.save()
return HttpResponseRedirect(self.get_success_url())