I'm using python 3.5 and Django 1.10 and trying to test my app in tests.py, but an error appeared, it said: ValueError: Cannot assign "1": "NewsLetter.UserID" must be a "User" instance.
so how to test a fk value here?
here is the code:
class NewsletterModelTest(TestCase):
@classmethod
def setUpTestData(cls):
#Set up non-modified objects used by all test methods
NewsLetter.objects.create(NewsLetterID=1, Email='[email protected]', Connected=False,UserID=1)
class NewsLetter(models.Model):
NewsLetterID = models.AutoField(primary_key=True)
Email = models.CharField(max_length=255)
Connected = models.BooleanField(default=False)
UserID = models.ForeignKey(User, on_delete=models.CASCADE)
class Meta:
db_table = 'NewsLetter'
Introduction to Django Foreign Key. A foreign key is a process through which the fields of one table can be used in another table flexibly. So, two different tables can be easily linked by means of the foreign key. This linking of the two tables can be easily achieved by means of foreign key processes.
The preferred way to write tests in Django is using the unittest module built-in to the Python standard library. This is covered in detail in the Writing and running tests document. You can also use any other Python test framework; Django provides an API and tools for that kind of integration.
Create a (default) object of the foreign model. It will automatically have id=1 (if no object existed yet). Change your foreignkey field by replacing null=True, blank=True by default=1 to associate that new object you created to all existing rows.
Your intermediate model must contain one - and only one - foreign key to the source model (this would be Group in our example). If you have more than one foreign key, a validation error will be raised.
In your setupTestData method you have to create a User object, and pass it into the NewsLetter object create method.
@classmethod
def setUpTestData(cls):
#Set up non-modified objects used by all test methods
user = User.objects.create(<fill params here>)
NewsLetter.objects.create(NewsLetterID=1, Email='[email protected]', Connected=False,UserID=user)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With