0
「Comentario」というモデルを作成しました。そこでは、ログに記録されたユーザーが自分のコメントを作成できます。ログに記録されたユーザーのコメントの作成者として自動的に保存する方法を教えてください。 現在のユーザーをコメントのautor(DJANGO)
class ComentarioForm(forms.ModelForm):
class Meta:
model = Comentario
fields = [
'titulo',
'texto',
'tag',
]
labels = {
'titulo': 'Titulo',
'texto' : 'Descripcion',
'tag' : 'Etiquetas',
}
widgets = {
'titulo':forms.TextInput(attrs={'class':'form-control'}),
'texto':forms.TextInput(attrs={'class':'form-control'}),
'tag':forms.CheckboxSelectMultiple(),
}
Perfil
forms.py
class ComentarioCreate (LoginRequiredMixin,CreateView):
model = Comentario
form_class = ComentarioForm
template_name = 'home/comentario_form.html'
success_url = reverse_lazy ('home:listar')
def save(self):
autor=self.request.user.username
user.save()
class Comentario (models.Model):
titulo = models.CharField(max_length=50)
texto = models.CharField(max_length=200)
autor = models.ForeignKey (Perfil, editable=False, blank=True)
fecha_publicacion = models.DateTimeField(auto_now_add=True)
tag = models.ManyToManyField(Tags, blank=True)
def __str__(self):
return (self.titulo)
views.py
がAbstractUserを形成継承するモデルであるmodels.py:ここで私は自分のスキーマを示しています。 models.py クラスPerfil(AbstractUser): nom_puesto = models.ForeignKey(Puesto、空白=真)
def __str__(self):
return '{}'.format(self.username)
にはどうすればフィールド 'autor' にログインしたユーザのユーザ名を持って行うことができますか?
ありがとうございました!
それは動作します!あなたの答えをありがとう! – JohnWire