I get an error when I try to add a widget to the form.
The error:
File "C:Userslibsite-packagesdjangoformsfields.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'}), }
Advertisement
Answer
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.