Я создал форму для ее добавления, унаследованную от ModelForm, так как считаю, что так логичнее (так как она напрямую взаимодействует с БД). Проблема в том, что я не могу добавить это поле в Форму, так как оно не может быть заполнено; его нужно взять из самого запроса.
Код: Выделить всё
author = request.user.pk
Единственный способ — наследовать его от класса Form? Мне не очень хочется этого делать... Я подумывал о 'переопределении' метода save(), чтобы у него был еще один аргумент - идентификатор автора:
Код: Выделить всё
form.save(author=request.user.pk)
Вот код моей формы:
Код: Выделить всё
class ArticleForm(ModelForm):
class Meta:
model = Article
fields = ['title', 'content']
widgets = {'title' : TextInput(attrs={'class' : 'create_article_title',
'placeholder' : 'Enter the heading...' }),
'content' : Textarea(attrs={'class' : 'create_article_content',
'placeholder' : 'Your article...' })}
Код: Выделить всё
class Article(Model):
title = CharField(max_length=30)
content = CharField(max_length=5000)
author = ForeignKey(User, on_delete=CASCADE)
rating = IntegerField(default=0)
created = DateField(auto_now_add=True)
last_updated = DateField(auto_now_add=True)
articles = ArticleManager()
objects = Manager()
Код: Выделить всё
class AddArticle(View):
template_name = 'myapp/addarticle.html'
def get(self, request):
context = {'add_article_form' : ArticleForm()}
return render(request, self.template_name, context=context)
def post(self, request):
form = ArticleForm()
form.save()
return redirect('index')
Подробнее здесь: https://stackoverflow.com/questions/786 ... orm-django