我想为用户添加一个表单,以添加评分和评论注释,从而从另一个应用程序(评分应用程序和项目应用程序)更新模型。 我已经为此苦苦挣扎了一段时间。 现在我有:
评分MODELS.py
class Avaliacao(models.Model):
RATING_CHOICES = (
(1, '1'),
(2, '2'),
(3, '3'),
(4, '4'),
(5, '5'),
)
created_at = models.DateTimeField(auto_now=True)
usuario = models.ForeignKey(get_user_model(),on_delete=models.CASCADE)
safra = models.ForeignKey(Safra,blank=False,on_delete=models.SET_NULL,null=True)
nota = models.IntegerField(choices=RATING_CHOICES)
comment = models.TextField()
forms.py
class NotaFormulario(ModelForm):
class Meta:
model = Avaliacao
fields = ['nota','comment']
urls.py
urlpatterns = [
url(r'^safra/(?P<safra_id>[0-9]+)/add_review/$',views.add_review, name='add_review')
]
views.py
def add_review(request, safra_id):
safra = get_object_or_404(Safra, pk=safra_id)
form = NotaFormulario(request.POST)
if form.is_valid():
nota = form.cleaned_data['nota']
comment = form.cleaned_data['comment']
usuario = request.user
avaliacao = Avaliacao()
avaliacao.safra = safra
avaliacao.usuario = usuario
avaliacao.nota = nota
avaliacao.comment = comment
avaliacao.created_at = datetime.datetime.now()
avaliacao.save()
# Always return an HttpResponseRedirect after successfully dealing
# with POST data. This prevents data from being posted twice if a
# user hits the Back button.
return HttpResponseRedirect(reverse('vinhos:safra_detalhes', args=(safra.id,)))
return render(request, 'vinhos/safra_detail.html', {'safra': safra, 'formulario': form})
template.html(这是我从另一个应用程序获得的详细信息模板)
<form action="{% url 'notas:add_review' safra.id %}" method="post" >
{% csrf_token %}
{{ formulario }}
<input type="submit" value="Enviar" class="btn btn-primary btn-large">
</form>
表单所在的模板(其他应用程序的详细视图页面)的urls.py
路径为
path('safra/<int:pk>/',views.SafraDetalhes.as_view(), name='safra_detalhes'),
字段未呈现。 HTML看起来像这样:
<form action="/safra/6/add_review/" method="post" >
<input type="hidden" name="csrfmiddlewaretoken" value="ofbt2lvghvsNhPuSVRDtAgP3gYoGI55AIoXcA8EpUE29Sp">
<input type="submit" value="Enviar" class="btn btn-primary btn-large">
</form>
该表单仅在我点击一次send后呈现,然后呈现“此字段为必填”警告。
总的来说,我一直在Django中苦苦挣扎,因为在我要开发的应用程序上,总是有这种形式的横截面在一个应用程序的模型上创建实例,而在另一个模型的详细视图上创建实例来自另一个应用程序。