CreateView form_valid上的404错误超过1个争论

时间:2018-04-21 16:43:01

标签: python django python-3.x django-views django-urls

我的证明应用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'),

1 个答案:

答案 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,因此您稍后会在代码中收到错误。