我的证明应用CreateView
有2个参数"用户"并且"发布"。用户要求由self.object.user = self.request.user
完成。如何满足self.object.post
要求。我是Django的新手。如果我违反任何Django规则,我道歉
models.py
User = get_user_model()
class Proof(models.Model):
user = models.ForeignKey(User, related_name='proofmade')
post = models.ForeignKey(Post, related_name='proofmade')
made_at = models.DateTimeField(auto_now=True)
image_of_task= models.ImageField()
proof_you_made_it = models.ImageField()
suggestions = models.TextField(max_length=1000)
def __str__(self):
return self.post.title
views.py
User = get_user_model()
class ProofCreate(LoginRequiredMixin, CreateView):
model = Proof
fields = ('image_of_task', 'proof_you_made_it', 'suggestions')
def form_valid(self, form, *args, **kwargs):
self.object = form.save(commit=False)
self.object.user = self.request.user
###### I think the following line may be wrong ##########
slug = self.kwargs.get('slug')
print(slug)
self.object.post = get_object_or_404(Post, slug=slug)
self.object.save()
return super().form_valid(form)
urls.py
app_name = 'proof'
urlpatterns = [
url(r'^new_proof/$', views.ProofCreate.as_view(), name='new_proof'),
答案 0 :(得分:0)
如果您想在视图中从slug
访问self.kwargs
,则您需要在网址中slug
。例如:
url(r'^new_proof/(?P<slug>[-\w]+)/$', views.ProofCreate.as_view(), name='new_proof')
您不需要username
,因为您是从self.request.user
获取用户的。在您的第二次尝试中,post.slug
不正确,因为变量名称不能包含点。
在视图中,我会使用slug = self.kwargs['slug']
,除非您希望它是可选的。目前get()
返回None
,因此您稍后会在代码中收到错误。