我无法在测试时更新模型实例

I can't update the Model instance while Testing

我正在更新时测试 CBV,每次模型实例似乎都无法更新。

控制台输出

>       self.assertEqual(product.showoff, data['showoff'])
E       AssertionError: 'uMsvXoRJbwFeieMvoCmR' != 'showoff 33333'
E       - uMsvXoRJbwFeieMvoCmR
E       + showoff 33333

views.py

class ProductUpdateView(LoginRequiredMixin, SuccessMessageMixin, UpdateView):
    model = Product
    form_class = ProductForm
    template_name = "mainapp/product_update.html"
    success_message = 'Successfully Updated a Product entry'

    def dispatch(self, *args, **kwargs):
        return super(self.__class__, self).dispatch(self.request, *args, **kwargs)

    def form_valid(self, form):
        self.object = form.save(commit=False)
        #migh need to remove that line
        #self.object.author = self.request.user
        return super(self.__class__, self).form_valid(form)


product_update = login_required(ProductUpdateView.as_view())

tests.py

def test_ProductUpdateView_should_update_the_product_content(self):
    #Delete all Products
    Product.objects.all().delete()

    #Create user (fixture)
    user = mixer.blend('auth.User', is_superuser=True)

    #create a Product (fixture)
    product = mixer.blend('mainapp.Product')

    #Fields to update
    data = dict( showoff='showoff 33333', )

    #Preparing to post to the Update url
    url = reverse('wadiyabi:product_update', kwargs={'pk': product.pk})
    request = RequestFactory().post(url, data=data)

    #assign a user
    request.user = user

    #Post to Update URL
    response = views.ProductUpdateView.as_view()(request, pk=product.pk)

    #Assertion: status code
    self.assertEqual(response.status_code, 200)
    #Refresh the db and Get the latest Product
    product.refresh_from_db()
    product = Product.objects.get(pk=product.pk)
    #pytest.set_trace()

    #Assertion
    self.assertEqual(product.showoff, data['showoff'])

forms.py

class ProductForm(ModelForm):
    class Meta:
        model = Product
        fields = ['photo', 'showoff', 'quantity', 'price']

仅当表单有效时才保存模型。这是你的表格

class ProductForm(ModelForm):
    class Meta:
        model = Product
        fields = ['photo', 'showoff', 'quantity', 'price']

它有四个字段。但是你的模拟表格 post 只有一个字段

data = dict( showoff='showoff 33333', )

#Preparing to post to the Update url
url = reverse('wadiyabi:product_update', kwargs={'pk': product.pk})
request = RequestFactory().post(url, data=data)

所以你的表格永远不会有效。结果模型永远不会被保存。因此结果。