Reputation: 371
I get an error when I try to add a widget to the form.
The error:
File "C:\Users\lib\site-packages\django\forms\fields.py", line 558, in __init__
super().__init__(**kwargs)
TypeError: __init__() got an unexpected keyword argument 'attrs'
The model
class Video(models.Model):
author = models.ForeignKey(Account, on_delete=models.CASCADE)
video = models.FileField(upload_to='post-videos')
title = models.CharField(max_length=100)
description = models.TextField(null=True, blank=True)
video_poster = models.ImageField(max_length=255, upload_to='post-videos')
The views
def VideosUploadView(request, *args, **kwargs):
all_videos = Video.objects.all()
V_form = Video_form()
video_added = False
if not request.user.is_active:
# any error you want
return redirect('login')
try:
account = Account.objects.get(username=request.user.username)
except:
# any error you want
return HttpResponse('User does not exits.')
if 'submit_v_form' in request.POST:
print(request.POST)
V_form = Video_form(request.POST, request.FILES)
if V_form.is_valid():
instance = V_form.save(commit=False)
instance.author = account
instance.save()
V_form = Video_form()
video_added = True
contex = {
'all_videos': all_videos,
'account': account,
'V_form': V_form,
'video_added': video_added,
}
return render(request, "video/upload_videos.html", contex)
The form
class Video_form(forms.ModelForm):
class Meta:
model = Video
fields = ('title', 'description', 'video', 'video_poster')
widgets = {
'title': forms.TextInput(attrs={'class': 'form-control'}),
'description': forms.TextInput(attrs={'class': 'form-control'}),
'video': forms.FileField(widget=forms.FileInput(attrs={'class': 'form-control'})),
'video_poster': forms.ImageField(attrs={'class': 'form-control'}),
}
Upvotes: 0
Views: 131
Reputation: 371
My problem was style the form fields and I explored a good way to styling the fields by add the field name after the form name Like this way
<span class="control-fileupload">
<!--here what I mean--> {{ V_form.video }}
<label for="file1" class="text-left">click to choose a Video on your computer.</label>
</span>
and here also
<label>{{ V_form.title }}</label>
Upvotes: 0
Reputation: 5854
You must assign valid widget in the Video_form
:
widgets = {
'title': forms.TextInput(attrs={'class': 'form-control'}),
'description': forms.TextInput(attrs={'class': 'form-control'}),
'video': forms.FileInput(attrs={'class': 'form-control'}),
'video_poster': forms.ClearableFileInput(attrs={'class': 'form-control'}),
}
forms.FileField
and forms.ImageField
are fields not widgets.
Upvotes: 2