在基于django类的通用视图CreateView中设置表单字段

时间:2018-02-26 14:04:23

标签: django django-views django-class-based-views

我正在使用django' CreateView将图片添加到图书中。我将书的id传递给基于类的视图作为url中的参数。 booklanguage等表单字段不会在模板上呈现,而是在图书ID的帮助下获得。

# views.py
class PictureCreateView(CreateView):
    model = Upload
    fields = "__all__"
    book_id = None

    def get_initial(self):
        initial = super(PictureCreateView, self).get_initial()
        initial = initial.copy()
        self.book_id = self.kwargs['book_id']
        book = Book.objects.get(id=self.book_id)
        initial['book'] = book
        initial['language'] = language
        initial['uploader'] = self.request.user
        return initial

    # set book_id so it used in the template
    def get_context_data(self, **kwargs):
        context = super(PictureCreateView, self).get_context_data(**kwargs)
        context['book_id'] = self.book_id
        return context

    def form_valid(self, form, **kwargs):
        print('Form is valid')
        self.object = form.save()
        files = [serialize(self.object)]
        data = {'files': files}
        response = JSONResponse(data, mimetype=response_mimetype(self.request))
        response['Content-Disposition'] = 'inline; filename=files.json'
        return super(PictureCreateView, self).form_valid(form)

    def form_invalid(self, form):
        print('Form invalid!')
        print(form.errors)
        data = json.dumps(form.errors)
        return HttpResponse(content=data, status=400, content_type='application/json')

# models.py
class Upload(models.Model):
    image = models.ImageField(upload_to=get_upload_path, help_text='Image to process')
    uploader = models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE, related_name='uploader')
    language = models.ForeignKey(Language, models.CASCADE)
    book = models.ForeignKey(Book, models.CASCADE)

问题是我收到错误消息,表示表单无效,并且需要字段uploaderbooklanguage。我该如何解决这个问题?

0 个答案:

没有答案