表单未在django视图中通过POST请求保存在数据库中

时间:2017-07-26 08:23:12

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

我的表格工作正常,但突然停止工作,我被困在这里,请帮帮我! 当我打印form.errors时,如果表单无效,则打印

  

  • user
  • 是必填字段。

    models.py

    class TarWithDocker(models.Model):
    name = models.CharField(max_length=255)
    user = models.ForeignKey(User, related_name='deployments')
    slug = AutoSlugField(populate_from='name', unique=True, name='slug')
    archive = models.FileField(upload_to='archives', name='archive')
    created_at = models.DateTimeField(default=timezone.now, editable=False)
    
    class Meta:
        ordering = ['-created_at']
    

    views.py

    class AwdDeployment(LoginRequiredMixin, CreateView):
    template_name = 'deployments/awdDeployment.html'
    
    def get(self, request, *args, **kwargs):
        return render(request, 'deployments/awdDeployment.html', {})
    
    def post(self, request, *args, **kwargs):
        if request.method == 'POST':
            form = AwdDeploymentForm(request.POST, request.FILES)
            if form.is_valid():
                deployment = TarWithDocker()
                deployment.name = form.cleaned_data['name']
                deployment.user = self.request.user
                deployment.archive = form.cleaned_data['archive']
                deployment.save()
                return HttpResponse("Submitted")
            else:
                print("not saved")
    
        else:
            print("something happnes wrong")
            form = AwdDeploymentForm()
        return HttpResponseRedirect(reverse('users:deployments:awd'))
    

    1 个答案:

    答案 0 :(得分:1)

    您有请求中的用户,但可能不在发布数据中 可能对你有所帮助:

    post_data = request.POST.copy()
    post_data.update({'user': request.user.pk})
    form = AwdDeploymentForm(post_data, request.FILES)