Django: How to unit test Update Views/Forms

2024/11/15 17:55:07

I'm trying to unit test my update forms and views. I'm using Django Crispy Forms for both my Create and Update Forms. UpdateForm inherits CreateForm and makes a small change to the submit button text. The CreateView and UpdateView are very similar. They have the same model, template, and success_url. They differ in that they use their respective forms, and CreateView inherits django.views.generic.CreateView, and UpdateView inherits django.views.generic.edit.UpdateView.

The website works fine. I can create and edit an object without a problem. However, my second test shown below fails. How do I test my UpdateForm?

Any help would be appreciated. Thanks.

This test passes:

class CreateFormTest(TestCase):def setUp(self):self.valid_data = {'x': 'foo','y': 'bar',}def test_create_form_valid(self):""" Test CreateForm with valid data """form = CreateForm(data=self.valid_data)self.assertTrue(form.is_valid())obj = form.save()self.assertEqual(obj.x, self.valid_data['x'])

This test fails:

class UpdateFormTest(TestCase):def setUp(self):self.obj = Factories.create_obj()  # Creates the objectdef test_update_form_valid(self):""" Test UpdateForm with valid data """valid_data = model_to_dict(self.obj)valid_data['x'] = 'new'form = UpdateForm(valid_data)self.assertTrue(form.is_valid())case = form.save()self.assertEqual(case.defendant, self.valid_data['defendant']
Answer

When pre-populating a ModelForm with an object that has already been created you can use the instance keyword argument to pass the object to the form.

form = SomeForm(instance=my_obj)

This can be done in a test, such as in the OP< or in a view to edit an object that has already been created. When calling save() the existing object will updated instead of creating a new one.

https://en.xdnf.cn/q/71860.html

Related Q&A

Why is Python faster than C++ in this case?

A program in both Python and C++ is given below, which performs the following task: read white-space delimited words from stdin, print the unique words sorted by string length along with a count of eac…

Python - write headers to csv

Currently i am writing query in python which export data from oracle dbo to .csv file. I am not sure how to write headers within file. try:connection = cx_Oracle.connect(user,pass,tns_name)cursor = con…

Opening/Attempting to Read a file [duplicate]

This question already has answers here:PyCharm shows unresolved references error for valid code(31 answers)Closed 5 years ago.I tried to simply read and store the contents of a text file into an array,…

How to pass custom settings through CrawlerProcess in scrapy?

I have two CrawlerProcesses, each is calling different spider. I want to pass custom settings to one of these processes to save the output of the spider to csv, I thought I could do this:storage_setti…

numpy how to slice index an array using arrays?

Perhaps this has been raised and addressed somewhere else but I havent found it. Suppose we have a numpy array: a = np.arange(100).reshape(10,10) b = np.zeros(a.shape) start = np.array([1,4,7]) # ca…

How to import _ssl in python 2.7.6?

My http server is based on BaseHTTPServer with Python 2.7.6. Now I want it to support ssl transportation, so called https.I have installed pyOpenSSL and recompiled python source code with ssl support. …

Unexpected Indent error in Python [duplicate]

This question already has answers here:Im getting an IndentationError (or a TabError). How do I fix it?(6 answers)Closed 4 years ago.I have a simple piece of code that Im not understanding where my er…

pyshark can not capture the packet on windows 7 (python)

I want to capture the packet using pyshark. but I could not capture the packet on windows 7.this is my python codeimport pyshark def NetCap():print capturing...livecapture = pyshark.LiveCapture(interf…

How to get the Signal-to-Noise-Ratio from an image in Python?

I am filtering an image and I would like to know the SNR. I tried with the scipy function scipy.stats.signaltonoise() but I get an array of numbers and I dont really know what I am getting.Is there an…

Python and OpenCV - Cannot write readable avi video files

I have a code like this:import numpy as np import cv2cap = cv2.VideoCapture(C:/Users/Hilman/haatsu/drive_recorder/sample/3.mov)# Define the codec and create VideoWriter object fourcc = cv2.VideoWriter_…