Mir Stephen
Mir Stephen

Reputation: 1927

Model object creation test fails in Django

I have done some testing before to create an object of a model, but this one keeps failing. This is the model I want to test:

class Contact(models.Model):
    name = models.CharField(max_length=200)
    email = models.CharField(max_length=200)
    subject = models.CharField(max_length=200)
    message = models.TextField()
    contact_date = models.DateTimeField(default=datetime.now, blank=True)
    user_id = models.IntegerField(default=0, blank=True, null=True)

and this is the test code:

class ContactTest(TestCase):
    def test_contact_create(self):
        url = reverse('contacts:contact')

        user = User.objects.create_user(
            username='johnnyjohnnyjo',
            email='[email protected]',
            password='testing321',
        )


        response = self.client.post(url, {
            "name": "marrydoe",
            "email": "[email protected]",
            "subject": "Test",
            "message": "This is a test message",
            "contact_date": timezone.now(),
            "user_id": user.id,
        })

        self.assertEqual(response.status_code, 200)
        self.assertContains(response, 'test')

I get this traceback error, I tried to trace the problem but couldn't find where the problem resides.

Creating test database for alias 'default'...
System check identified no issues (0 silenced).
.....................D:\GitHub\Portfolio\lib\site-packages\django\db\models\fields\__init__.py:1367: RuntimeWarning: DateTimeField Contact.contact_date received a naive datetime (2020-09-23 11:38:22.746360) while time zone support is active.
  warnings.warn("DateTimeField %s received a naive datetime (%s)"
[2020-09-23 11:38:22,750] log: ERROR - Internal Server Error: /contact/
Traceback (most recent call last):
  File "D:\GitHub\Portfolio\lib\site-packages\django\shortcuts.py", line 131, in resolve_url
    return reverse(to, args=args, kwargs=kwargs)
  File "D:\GitHub\Portfolio\lib\site-packages\django\urls\base.py", line 87, in reverse
    return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
  File "D:\GitHub\Portfolio\lib\site-packages\django\urls\resolvers.py", line 685, in _reverse_with_prefix
    raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'None' not found. 'None' is not a valid view function or pattern name.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:\GitHub\Portfolio\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "D:\GitHub\Portfolio\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "D:\GitHub\Portfolio\contact\views.py", line 34, in contact_us
    return redirect(request.META.get('HTTP_REFERER'))
  File "D:\GitHub\Portfolio\lib\site-packages\django\shortcuts.py", line 41, in redirect
    return redirect_class(resolve_url(to, *args, **kwargs))
  File "D:\GitHub\Portfolio\lib\site-packages\django\shortcuts.py", line 137, in resolve_url
    if '/' not in to and '.' not in to:
TypeError: argument of type 'NoneType' is not iterable
E..........
======================================================================
ERROR: test_contact_create (contact.tests.ContactTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "D:\GitHub\Portfolio\lib\site-packages\django\shortcuts.py", line 131, in resolve_url
    return reverse(to, args=args, kwargs=kwargs)
  File "D:\GitHub\Portfolio\lib\site-packages\django\urls\base.py", line 87, in reverse
    return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
  File "D:\GitHub\Portfolio\lib\site-packages\django\urls\resolvers.py", line 685, in _reverse_with_prefix
    raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'None' not found. 'None' is not a valid view function or pattern name.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:\GitHub\Portfolio\contact\tests.py", line 31, in test_contact_create
    response = self.client.post(url, {
  File "D:\GitHub\Portfolio\lib\site-packages\django\test\client.py", line 741, in post
    response = super().post(path, data=data, content_type=content_type, secure=secure, **extra)
  File "D:\GitHub\Portfolio\lib\site-packages\django\test\client.py", line 404, in post
    return self.generic('POST', path, post_data, content_type,
  File "D:\GitHub\Portfolio\lib\site-packages\django\test\client.py", line 470, in generic
    return self.request(**r)
  File "D:\GitHub\Portfolio\lib\site-packages\django\test\client.py", line 709, in request
    self.check_exception(response)
  File "D:\GitHub\Portfolio\lib\site-packages\django\test\client.py", line 571, in check_exception
    raise exc_value
  File "D:\GitHub\Portfolio\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "D:\GitHub\Portfolio\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "D:\GitHub\Portfolio\contact\views.py", line 34, in contact_us
    return redirect(request.META.get('HTTP_REFERER'))
  File "D:\GitHub\Portfolio\lib\site-packages\django\shortcuts.py", line 41, in redirect
    return redirect_class(resolve_url(to, *args, **kwargs))
  File "D:\GitHub\Portfolio\lib\site-packages\django\shortcuts.py", line 137, in resolve_url
    if '/' not in to and '.' not in to:
TypeError: argument of type 'NoneType' is not iterable

----------------------------------------------------------------------
Ran 32 tests in 6.180s

FAILED (errors=1)
Destroying test database for alias 'default'...

I am not sure but I think maybe return redirect(request.META.get('HTTP_REFERER')) could be a potential problem here, in case you want to see the views:

def contact_us(request):
    if request.method == 'POST':
        name = request.POST['name']
        email = request.POST['email']
        subject = request.POST['subject']
        message = request.POST['message']

        if request.user.is_authenticated:
            user_id = request.POST['user_id']
            user = User.objects.get(id=user_id)
            contact = Contact.objects.filter(user_id=user.id)
            if contact:
                messages.warning(
                    request, 'You already sent a message, we will get back to you soon.')
                return redirect(request.META.get('HTTP_REFERER'))
        else:
            contact, created = Contact.objects.get_or_create(
                name=name, email=email, subject=subject, message=message, user_id=0)

            if created:
                messages.success(request, 'Message sent successfully!')
            else:
                messages.error(
                    request, 'Please fill all the blanks with required valid data.')

            return redirect(request.META.get('HTTP_REFERER'))

    return render(request, 'contact/contact.html')

Thank you for your time reading, helping and debugging it.

edit:

app_name = 'contacts'
urlpatterns = [
    path('list/', contacts_list, name='contact_list'),
    path('', contact_us, name='contact'),
]

Upvotes: 1

Views: 213

Answers (1)

Ben
Ben

Reputation: 2547

The lines in question from the traceback:

 File "D:\GitHub\Portfolio\contact\views.py", line 34, in contact_us
 return redirect(request.META.get('HTTP_REFERER'))

In your case here, request.META.get('HTTP_REFERER') is returning None when running the tests so you will need to add it manually. Or if you are just trying to redirect to the same page just use return redirect("/") in the view instead.

Upvotes: 1

Related Questions