Ошибка 405 django

I'm trying to develop a REST provider with OAuth. I'm using Django RESTFramework and DjangoOAuthToolkit. I did a GET and it works perfectly but I'm trying to use a POST and the server responds with {"

I’m trying to develop a REST provider with OAuth. I’m using Django RESTFramework and DjangoOAuthToolkit. I did a GET and it works perfectly but I’m trying to use a POST and the server responds with {«detail»: «Method ‘POST’ not allowed.»}
This is my code:

# views.py
@api_view(['POST'])
def pruebapost(request):
    usuario = User()
    access_token = Token.objects.get(
        key=request.POST['oauth_token']
    )
    usuario = access_token.user
    content = {'saludo': usuario.username}
    return Response(content)

# settings.py
OAUTH_AUTHORIZE_VIEW = 'principal.views.oauth_authorize'
SESSION_SERIALIZER = 'django.contrib.sessions.serializers.JSONSerializer'
REST_FRAMEWORK = {
   'DEFAULT_RENDERER_CLASSES': (
        'rest_framework.renderers.JSONRenderer',
    ),
   'DEFAULT_PARSER_CLASSES': (
        'rest_framework.parsers.JSONParser',
    ),
   'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.OAuthAuthentication',
    ),
}

And I’m using this as a «test» client:

import urlparse
import oauth2 as oauth
import requests

consumer_key = "clave"
consumer_secret = "secreto"
consumer = oauth.Consumer(consumer_key, consumer_secret)
client = oauth.Client(consumer)
resource_url = 'http://blablabla.pythonanywhere.com/prueba'
consumer = oauth.Consumer(key='clave', secret='secreto')
token = oauth.Token(key='e7456187a43141af8d2e0d8fa99b95b9',
                    secret='3wRIKoacff16tcew')

oauth_request = oauth.Request.from_consumer_and_token(
    consumer,
    token,
    http_method='POST',
    http_url=resource_url,
    parameters={'hola':'pepe'}
)
oauth_request.sign_request(
    oauth.SignatureMethod_HMAC_SHA1(),
    consumer,
    token
)
url = oauth_request.to_url()
response = requests.post(url, oauth_request.to_postdata())
print response.content

I don’t understand what REST Framework documentation says about 405 Method not allowed

«Raised when an incoming request occurs that does not map to a handler method on the view.»

Thanks

Содержание

  1. Exceptions
  2. Exception handling in REST framework views
  3. Custom exception handling
  4. API Reference
  5. APIException
  6. Inspecting API exceptions
  7. ParseError
  8. AuthenticationFailed
  9. NotAuthenticated
  10. PermissionDenied
  11. NotFound
  12. MethodNotAllowed
  13. NotAcceptable
  14. UnsupportedMediaType
  15. Throttled
  16. ValidationError
  17. Generic Error Views
  18. rest_framework.exceptions.server_error
  19. rest_framework.exceptions.bad_request
  20. Third party packages
  21. DRF Standardized Errors
  22. Исключения¶
  23. Обработка исключений в представлениях фреймворка REST¶
  24. Пользовательская обработка исключений¶
  25. Справочник по API¶
  26. APIException¶
  27. Проверка исключений API¶
  28. ParseError¶
  29. AuthenticationFailed¶
  30. NotAuthenticated¶
  31. PermissionDenied¶
  32. NotFound¶
  33. MethodNotAllowed¶
  34. Неприемлемо¶
  35. UnsupportedMediaType¶
  36. Дросселированный¶
  37. ValidationError¶
  38. Общие представления ошибок¶
  39. rest_framework.exceptions.server_error ¶
  40. rest_framework.exceptions.bad_request ¶

Exceptions

Exceptions… allow error handling to be organized cleanly in a central or high-level place within the program structure.

Exception handling in REST framework views

REST framework’s views handle various exceptions, and deal with returning appropriate error responses.

The handled exceptions are:

  • Subclasses of APIException raised inside REST framework.
  • Django’s Http404 exception.
  • Django’s PermissionDenied exception.

In each case, REST framework will return a response with an appropriate status code and content-type. The body of the response will include any additional details regarding the nature of the error.

Most error responses will include a key detail in the body of the response.

For example, the following request:

Might receive an error response indicating that the DELETE method is not allowed on that resource:

Validation errors are handled slightly differently, and will include the field names as the keys in the response. If the validation error was not specific to a particular field then it will use the «non_field_errors» key, or whatever string value has been set for the NON_FIELD_ERRORS_KEY setting.

An example validation error might look like this:

Custom exception handling

You can implement custom exception handling by creating a handler function that converts exceptions raised in your API views into response objects. This allows you to control the style of error responses used by your API.

The function must take a pair of arguments, the first is the exception to be handled, and the second is a dictionary containing any extra context such as the view currently being handled. The exception handler function should either return a Response object, or return None if the exception cannot be handled. If the handler returns None then the exception will be re-raised and Django will return a standard HTTP 500 ‘server error’ response.

For example, you might want to ensure that all error responses include the HTTP status code in the body of the response, like so:

In order to alter the style of the response, you could write the following custom exception handler:

The context argument is not used by the default handler, but can be useful if the exception handler needs further information such as the view currently being handled, which can be accessed as context[‘view’] .

The exception handler must also be configured in your settings, using the EXCEPTION_HANDLER setting key. For example:

If not specified, the ‘EXCEPTION_HANDLER’ setting defaults to the standard exception handler provided by REST framework:

Note that the exception handler will only be called for responses generated by raised exceptions. It will not be used for any responses returned directly by the view, such as the HTTP_400_BAD_REQUEST responses that are returned by the generic views when serializer validation fails.

API Reference

APIException

Signature: APIException()

The base class for all exceptions raised inside an APIView class or @api_view .

To provide a custom exception, subclass APIException and set the .status_code , .default_detail , and default_code attributes on the class.

For example, if your API relies on a third party service that may sometimes be unreachable, you might want to implement an exception for the «503 Service Unavailable» HTTP response code. You could do this like so:

Inspecting API exceptions

There are a number of different properties available for inspecting the status of an API exception. You can use these to build custom exception handling for your project.

The available attributes and methods are:

  • .detail — Return the textual description of the error.
  • .get_codes() — Return the code identifier of the error.
  • .get_full_details() — Return both the textual description and the code identifier.

In most cases the error detail will be a simple item:

In the case of validation errors the error detail will be either a list or dictionary of items:

ParseError

Signature: ParseError(detail=None, code=None)

Raised if the request contains malformed data when accessing request.data .

By default this exception results in a response with the HTTP status code «400 Bad Request».

AuthenticationFailed

Signature: AuthenticationFailed(detail=None, code=None)

Raised when an incoming request includes incorrect authentication.

By default this exception results in a response with the HTTP status code «401 Unauthenticated», but it may also result in a «403 Forbidden» response, depending on the authentication scheme in use. See the authentication documentation for more details.

NotAuthenticated

Signature: NotAuthenticated(detail=None, code=None)

Raised when an unauthenticated request fails the permission checks.

By default this exception results in a response with the HTTP status code «401 Unauthenticated», but it may also result in a «403 Forbidden» response, depending on the authentication scheme in use. See the authentication documentation for more details.

PermissionDenied

Signature: PermissionDenied(detail=None, code=None)

Raised when an authenticated request fails the permission checks.

By default this exception results in a response with the HTTP status code «403 Forbidden».

NotFound

Signature: NotFound(detail=None, code=None)

Raised when a resource does not exists at the given URL. This exception is equivalent to the standard Http404 Django exception.

By default this exception results in a response with the HTTP status code «404 Not Found».

MethodNotAllowed

Signature: MethodNotAllowed(method, detail=None, code=None)

Raised when an incoming request occurs that does not map to a handler method on the view.

By default this exception results in a response with the HTTP status code «405 Method Not Allowed».

NotAcceptable

Signature: NotAcceptable(detail=None, code=None)

Raised when an incoming request occurs with an Accept header that cannot be satisfied by any of the available renderers.

By default this exception results in a response with the HTTP status code «406 Not Acceptable».

Signature: UnsupportedMediaType(media_type, detail=None, code=None)

Raised if there are no parsers that can handle the content type of the request data when accessing request.data .

By default this exception results in a response with the HTTP status code «415 Unsupported Media Type».

Throttled

Signature: Throttled(wait=None, detail=None, code=None)

Raised when an incoming request fails the throttling checks.

By default this exception results in a response with the HTTP status code «429 Too Many Requests».

ValidationError

Signature: ValidationError(detail, code=None)

The ValidationError exception is slightly different from the other APIException classes:

  • The detail argument is mandatory, not optional.
  • The detail argument may be a list or dictionary of error details, and may also be a nested data structure. By using a dictionary, you can specify field-level errors while performing object-level validation in the validate() method of a serializer. For example. raise serializers.ValidationError(<‘name’: ‘Please enter a valid name.’>)
  • By convention you should import the serializers module and use a fully qualified ValidationError style, in order to differentiate it from Django’s built-in validation error. For example. raise serializers.ValidationError(‘This field must be an integer value.’)

The ValidationError class should be used for serializer and field validation, and by validator classes. It is also raised when calling serializer.is_valid with the raise_exception keyword argument:

The generic views use the raise_exception=True flag, which means that you can override the style of validation error responses globally in your API. To do so, use a custom exception handler, as described above.

By default this exception results in a response with the HTTP status code «400 Bad Request».

Generic Error Views

Django REST Framework provides two error views suitable for providing generic JSON 500 Server Error and 400 Bad Request responses. (Django’s default error views provide HTML responses, which may not be appropriate for an API-only application.)

rest_framework.exceptions.server_error

Returns a response with status code 500 and application/json content type.

Set as handler500 :

rest_framework.exceptions.bad_request

Returns a response with status code 400 and application/json content type.

Set as handler400 :

Third party packages

The following third-party packages are also available.

DRF Standardized Errors

The drf-standardized-errors package provides an exception handler that generates the same format for all 4xx and 5xx responses. It is a drop-in replacement for the default exception handler and allows customizing the error response format without rewriting the whole exception handler. The standardized error response format is easier to document and easier to handle by API consumers.

Источник

Исключения¶

Исключения… позволяют чисто организовать обработку ошибок в центральном или высокоуровневом месте в структуре программы.

‒ Doug Hellmann, Python Exception Handling Techniques

Обработка исключений в представлениях фреймворка REST¶

Представления фреймворка REST обрабатывают различные исключения и возвращают соответствующие ответы на ошибки.

Обрабатываемыми исключениями являются:

Подклассы APIException , поднятые внутри фреймворка REST.

Исключение Django Http404 .

Исключение Django PermissionDenied .

В каждом случае фреймворк REST возвращает ответ с соответствующим кодом состояния и типом содержимого. В теле ответа будут содержаться любые дополнительные сведения о характере ошибки.

Большинство ответов на ошибки будут содержать ключ detail в теле ответа.

Например, следующий запрос:

Может быть получен ответ об ошибке, указывающий на то, что метод DELETE не разрешен на данном ресурсе:

Ошибки валидации обрабатываются несколько иначе, и в качестве ключей в ответе будут указаны имена полей. Если ошибка валидации не относится к конкретному полю, то будет использован ключ «non_field_errors» или любое строковое значение, установленное для параметра NON_FIELD_ERRORS_KEY .

Пример ошибки валидации может выглядеть следующим образом:

Пользовательская обработка исключений¶

Вы можете реализовать пользовательскую обработку исключений, создав функцию-обработчик, которая преобразует исключения, возникающие в представлениях вашего API, в объекты ответа. Это позволит вам контролировать стиль ответов на ошибки, используемый вашим API.

Функция должна принимать пару аргументов, первый из которых — обрабатываемое исключение, а второй — словарь, содержащий любой дополнительный контекст, например, обрабатываемое в данный момент представление. Функция обработчика исключения должна либо вернуть объект Response , либо вернуть None , если исключение не может быть обработано. Если обработчик возвращает None , то исключение будет повторно поднято и Django вернет стандартный ответ HTTP 500 „server error“.

Например, вы можете захотеть убедиться, что все ответы на ошибки включают код состояния HTTP в теле ответа, например, так:

Чтобы изменить стиль ответа, вы можете написать следующий пользовательский обработчик исключений:

Аргумент context не используется обработчиком по умолчанию, но может быть полезен, если обработчику исключения нужна дополнительная информация, например, обрабатываемое в данный момент представление, доступ к которому можно получить в виде context[‘view’] .

Обработчик исключений также должен быть настроен в ваших настройках, используя клавишу настройки EXCEPTION_HANDLER . Например:

Если параметр ‘EXCEPTION_HANDLER’ не указан, то по умолчанию используется стандартный обработчик исключений, предоставляемый фреймворком REST:

Обратите внимание, что обработчик исключений будет вызываться только для ответов, сгенерированных поднятыми исключениями. Он не будет использоваться для любых ответов, возвращаемых непосредственно представлением, например, ответов HTTP_400_BAD_REQUEST , которые возвращаются общими представлениями при неудачной проверке сериализатора.

Справочник по API¶

APIException¶

Подпись: APIException()

базовый класс для всех исключений, возникающих внутри класса APIView или @api_view .

Чтобы обеспечить пользовательское исключение, подкласс APIException и установите атрибуты .status_code , .default_detail , и default_code на класс.

Например, если ваш API полагается на сторонний сервис, который иногда может быть недоступен, вы можете захотеть реализовать исключение для кода ответа HTTP «503 Service Unavailable». Это можно сделать следующим образом:

Проверка исключений API¶

Существует ряд различных свойств, доступных для проверки состояния исключения API. Вы можете использовать их для создания пользовательской обработки исключений в вашем проекте.

Доступными атрибутами и методами являются:

.detail — Возвращает текстовое описание ошибки.

.get_codes() — Возвращает идентификатор кода ошибки.

.get_full_details() — Возвращает как текстовое описание, так и идентификатор кода.

В большинстве случаев деталь ошибки будет простым элементом:

В случае ошибок валидации деталь ошибки будет представлять собой список или словарь элементов:

ParseError¶

Подпись: ParseError(detail=None, code=None)

Возникает, если запрос содержит неправильно сформированные данные при доступе к request.data .

По умолчанию это исключение приводит к ответу с кодом состояния HTTP «400 Bad Request».

AuthenticationFailed¶

Подпись: AuthenticationFailed(detail=None, code=None)

Возникает, когда входящий запрос содержит неправильную аутентификацию.

По умолчанию это исключение приводит к ответу с кодом состояния HTTP «401 Unauthenticated», но оно также может привести к ответу «403 Forbidden», в зависимости от используемой схемы аутентификации. Более подробную информацию см. в authentication documentation .

NotAuthenticated¶

Подпись: NotAuthenticated(detail=None, code=None)

Возникает, когда неаутентифицированный запрос не прошел проверку на разрешение.

По умолчанию это исключение приводит к ответу с кодом состояния HTTP «401 Unauthenticated», но оно также может привести к ответу «403 Forbidden», в зависимости от используемой схемы аутентификации. Более подробную информацию см. в authentication documentation .

PermissionDenied¶

Подпись: PermissionDenied(detail=None, code=None)

Возникает, когда аутентифицированный запрос не прошел проверку на разрешение.

По умолчанию это исключение приводит к ответу с кодом состояния HTTP «403 Forbidden».

NotFound¶

Подпись: NotFound(detail=None, code=None)

Возникает, когда ресурс не существует по заданному URL. Это исключение эквивалентно стандартному исключению Django Http404 .

По умолчанию это исключение приводит к ответу с кодом состояния HTTP «404 Not Found».

MethodNotAllowed¶

Подпись: MethodNotAllowed(method, detail=None, code=None)

Возникает, когда происходит входящий запрос, который не сопоставлен с методом-обработчиком на представлении.

По умолчанию это исключение приводит к ответу с кодом состояния HTTP «405 Method Not Allowed».

Неприемлемо¶

Подпись: NotAcceptable(detail=None, code=None)

Возникает, когда поступает запрос с заголовком Accept , который не может быть удовлетворен ни одним из доступных рендереров.

По умолчанию это исключение приводит к ответу с кодом состояния HTTP «406 Not Acceptable».

Подпись: UnsupportedMediaType(media_type, detail=None, code=None)

Возникает, если при обращении к request.data нет парсеров, способных обработать тип содержимого данных запроса.

По умолчанию это исключение приводит к ответу с кодом состояния HTTP «415 Unsupported Media Type».

Дросселированный¶

Подпись: Throttled(wait=None, detail=None, code=None)

Возникает, когда входящий запрос не проходит проверку на дросселирование.

По умолчанию это исключение приводит к ответу с кодом состояния HTTP «429 Too Many Requests».

ValidationError¶

Подпись: ValidationError(detail, code=None)

Исключение ValidationError несколько отличается от других классов APIException :

Аргумент detail является обязательным, а не опциональным.

Аргумент detail может представлять собой список или словарь сведений об ошибках, а также может быть вложенной структурой данных. Используя словарь, вы можете указать ошибки на уровне полей при выполнении проверки на уровне объектов в методе validate() сериализатора. Например. raise serializers.ValidationError(<‘name’: ‘Please enter a valid name.’>)

По соглашению вы должны импортировать модуль serializers и использовать полностью квалифицированный стиль ValidationError , чтобы отличить его от встроенной ошибки валидации Django. Например. raise serializers.ValidationError(‘This field must be an integer value.’)

Класс ValidationError следует использовать для сериализатора и валидации полей, а также классами валидаторов. Он также возникает при вызове serializer.is_valid с аргументом ключевого слова raise_exception :

Общие представления используют флаг raise_exception=True , что означает, что вы можете переопределить стиль ответов на ошибки валидации глобально в вашем API. Для этого используйте пользовательский обработчик исключений, как описано выше.

По умолчанию это исключение приводит к ответу с кодом состояния HTTP «400 Bad Request».

Общие представления ошибок¶

Django REST Framework предоставляет два представления ошибок, подходящих для предоставления общих JSON 500 Server Error и 400 Bad Request ответов. (Стандартные представления ошибок Django предоставляют ответы в формате HTML, что может не подойти для приложения, использующего только API).

rest_framework.exceptions.server_error ¶

Возвращает ответ с кодом состояния 500 и типом содержимого application/json .

Установить как handler500 :

rest_framework.exceptions.bad_request ¶

Возвращает ответ с кодом состояния 400 и типом содержимого application/json .

Источник

This problem has gotten me mad and it’s the only question regarding this topics that shows up when searching that problem. I can’t say I have a proper fix but I’ve solved it for me, and I thought I might share the result of a few hours of debugging.

I had just the exact same problem as you, that is a POST request that doesn’t work in a unit test while it works perfectly fine when the full application is running. What was even crazier in my case is that the test worked on my laptop but not on my desktop machine, with no environment difference (same virtual environment, and just the minor difference of having python3.5.3 VS python3.5.1)

The messages I got were :

  • «Method Not Allowed (POST): url/where/i/wanted/to/post» interlaced with the test method names (when run with ./manage.py test -v2)
  • An assertion error in the «test sum-up» : «AssertionError: False is not true : Response didn’t redirect as expected: Response code was 405 (expected 302)»

With the following piece of code :

r = self.client.post(url, follow=True)
self.assertRedirects(r, expected_url)

(The URL I was posting to was handled by a class derived from a CreateView)

The first message was firing from this piece of code which was triggered by going through this line

handler = getattr(self, request.method.lower(), self.http_method_not_allowed)

… with request.method set to ‘POST’ … and it turned out my CreateView didn’t have any ‘post’ method when in test mode (which is very weird … and obviously when run on my laptop the view had that function !), so Django was falling back on that ‘http_method_not_allowed’ instead.

Now, why didn’t my CreateView have a ‘POST’ method ? I have not taken the time to go through the whole init process (which seems rather complicated), so I have no precise idea, but it turned out in my case that some URLs were simply not ‘initialized’ in my tests (which I could figure out by printing stuff in this function in urls/resolvers.py). And for instance, the URL that was supposed to handle the POST request I was indeed non-existent while running my tests … so I guess that explains why my CreateView was not initialized properly

I finally found out that my problem came from using django-crudbuilder app for building my CRUD views, and it doesn’t initialize properly when the database is empty (which is the case while running a test on a non-persistent database)

Not sure where that problem might come from in other cases, but if you run into this you might like to check whether all your URLs are properly «seen» by Django while running your tests (and if they aren’t, try and figure out why).

(the Django source code I’ve linked is from the current master but it’s just the same as the one I’ve been going through in the version I use which is the 1.11.7)

This problem has gotten me mad and it’s the only question regarding this topics that shows up when searching that problem. I can’t say I have a proper fix but I’ve solved it for me, and I thought I might share the result of a few hours of debugging.

I had just the exact same problem as you, that is a POST request that doesn’t work in a unit test while it works perfectly fine when the full application is running. What was even crazier in my case is that the test worked on my laptop but not on my desktop machine, with no environment difference (same virtual environment, and just the minor difference of having python3.5.3 VS python3.5.1)

The messages I got were :

  • «Method Not Allowed (POST): url/where/i/wanted/to/post» interlaced with the test method names (when run with ./manage.py test -v2)
  • An assertion error in the «test sum-up» : «AssertionError: False is not true : Response didn’t redirect as expected: Response code was 405 (expected 302)»

With the following piece of code :

r = self.client.post(url, follow=True)
self.assertRedirects(r, expected_url)

(The URL I was posting to was handled by a class derived from a CreateView)

The first message was firing from this piece of code which was triggered by going through this line

handler = getattr(self, request.method.lower(), self.http_method_not_allowed)

… with request.method set to ‘POST’ … and it turned out my CreateView didn’t have any ‘post’ method when in test mode (which is very weird … and obviously when run on my laptop the view had that function !), so Django was falling back on that ‘http_method_not_allowed’ instead.

Now, why didn’t my CreateView have a ‘POST’ method ? I have not taken the time to go through the whole init process (which seems rather complicated), so I have no precise idea, but it turned out in my case that some URLs were simply not ‘initialized’ in my tests (which I could figure out by printing stuff in this function in urls/resolvers.py). And for instance, the URL that was supposed to handle the POST request I was indeed non-existent while running my tests … so I guess that explains why my CreateView was not initialized properly

I finally found out that my problem came from using django-crudbuilder app for building my CRUD views, and it doesn’t initialize properly when the database is empty (which is the case while running a test on a non-persistent database)

Not sure where that problem might come from in other cases, but if you run into this you might like to check whether all your URLs are properly «seen» by Django while running your tests (and if they aren’t, try and figure out why).

(the Django source code I’ve linked is from the current master but it’s just the same as the one I’ve been going through in the version I use which is the 1.11.7)

  • #1

Тестирую вьюху в django но выбивает ошибку 405!=201 где именно совершил ошибку подскажите

Python:

сlass AddStarRating(View):
    """Добавление рейтинга фильму"""

    def get_client_ip(self, request):
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]
        else:
            ip = request.META.get('REMOTE_ADDR')
        return ip

    def post(self, request):
        form = RatingForm(request.POST)
        if form.is_valid():
            Rating.objects.update_or_create(
                ip=self.get_client_ip(request),
                movie_id=int(request.POST.get("movie")),
                defaults={'star_id': int(request.POST.get("star"))}
            )
            return HttpResponse(status=201)
        else:
            return HttpResponse(status=400)

вот сам тест:

Python:

def test_rating_views(self):
    factory = RequestFactory()
    request = factory.get("")
    request.user = self.user
    response = AddStarRating.as_view()(request)
    self.assertEqual(response.status_code, 201))

  • #19

получается что тест некорректен?
нужно для данной view переписывать его?

Смотря что вы тестите, если к примеру вы тестите что нельзя изменить рейтинг get-запросом, то можно поменять в ассерте код на такой:

Python:

self.assertEqual(response.status_code, 405)

и тест будет корректным.
Если вы хотите протестить именно работу формы, то надо переделывать тест на post-запрос и передавать тестовые данные для формы.

  • #2

Судя по ошибке у вас не проходит тест в этой строке (не выполняется условие):

Python:

self.assertEqual(response.status_code, 201))

То есть ожидает код 201 CREATED, а получается 405 METHOD NOT ALLOWED
Видимо вьюха не принимает метод GET.
Попробуйте обратится к вьюхе через браузер (для проверки).

  • #3

Судя по ошибке у вас не проходит тест в этой строке (не выполняется условие):

Python:

self.assertEqual(response.status_code, 201))

То есть ожидает код 201 CREATED, а получается 405 METHOD NOT ALLOWED
Видимо вьюха не принимает метод GET.
Попробуйте обратится к вьюхе через браузер (для проверки).

Если вы про работоспособность вьхи, то она рабочая

  • #4

Если вы про работоспособность вьхи, то она рабочая

То есть в браузере по get-запросу она не выдает ошибку 405.

  • #5

То есть в браузере по get-запросу она не выдает ошибку 405.

нет

  • #6

Значит тест не корректный если в тесте получается 405, а в браузере 200.
Полный код теста покажите и еще файл urls.py чтобы посмотреть к какому роуту вьюха подключена.

  • #7

Значит тест не корректный если в тесте получается 405, а в браузере 200.
Полный код теста покажите и еще файл urls.py чтобы посмотреть к какому роуту вьюха подключена.

Код:

path("add-rating/", views.AddStarRating.as_view(), name='add_rating')

это урлка
это и есть полный тест

Код:

class RatingForm(forms.ModelForm):
    """Форма добавления рейтинга"""
    star = forms.ModelChoiceField(
        queryset=RatingStar.objects.all(), widget=forms.RadioSelect(), empty_label=None
    )

    class Meta:
        model = Rating
        fields = ("star",)

это формы

  • #8

вы тесты пишите же файле test.py покажите этот файл полностью (чтобы понять что импортируйте и как тесты структурированы).
Просто по такому коду теста не очень понятно.

  • #9

Код:

path("add-rating/", views.AddStarRating.as_view(), name='add_rating')

Попробуйте при создании реквеста через RequestFactory() передать правильный урл:

Python:

request = factory.get("add-rating/")

  • #10

Код:

path("add-rating/", views.AddStarRating.as_view(), name='add_rating')

Попробуйте при создании реквеста через RequestFactory() передать правильный урл:

Python:

request = factory.get("add-rating/")

Код:

from django.contrib.auth import get_user_model
from django.test import TestCase, RequestFactory


from movies.models import Reviews, Movie
from movies.views import AddStarRating, MovieDetailView


class CreateNewReviewTest(TestCase):
    def setUp(self):
        self.user = get_user_model().objects.create_user(username='test', password='12test12', email='test@example.com')
        self.movie = Movie.objects.create(
            url="5"
        )

        self.review = Reviews.objects.create(
            name='user1',
            email="test1@example.com",
            text='This is a test to check if a post is correctly created',
            movie=self.movie
        )

    def test_create_review_db(self):
        self.assertEqual(Reviews.objects.count(), 1)

    def test_rating_views(self):
        factory = RequestFactory()
        request = factory.get("add-rating/")
        request.user = self.user
        response = AddStarRating.as_view()(request)
        self.assertEqual(response.status_code, 201)

  • #11

Эту строку можно вынести в метод setUp():

Код:

factory = RequestFactory()

и вызывать как request = self.factory.get(...) чтобы не создавать экземпляр на каждый тест.

Что выдает после смены урла в реквесте?

  • #12

Эту строку можно вынести в метод setUp():

Код:

factory = RequestFactory()

и вызывать как request = self.factory.get(...) чтобы не создавать экземпляр на каждый тест.

Что выдает после смены урла в реквесте?

такая же ошибка

  • #13

Попробуйте сделать:

Python:

print(response)
print(response.status_code)

перед ассертом
Чтобы посмотреть что приходит в респонс.

  • #14

Попробуйте сделать:

Python:

print(response)
print(response.status_code)

перед ассертом
Чтобы посмотреть что приходит в респонс.

<HttpResponseNotAllowed [POST, OPTIONS] status_code=405, «text/html; charset=utf-8»>
405

  • #15

<HttpResponseNotAllowed [POST, OPTIONS] status_code=405, «text/html; charset=utf-8»>

Странно что при переходе по этому урлу в браузере вы не получайте ошибку 405.

  • #16

Странно что при переходе по этому урлу в браузере вы не получайте ошибку 405.

Код:

class RatingForm(forms.ModelForm):
    """Форма добавления рейтинга"""
    star = forms.ModelChoiceField(
        queryset=RatingStar.objects.all(), widget=forms.RadioSelect(), empty_label=None
    )

    class Meta:
        model = Rating
        fields = ("star",)
[/ICODE]
вот моя forms, тут как бы не переход на страницу, а мы устанавливаем рейтинг фильму, после того как установим, оно не переходит никуда, ip
передается в админку.

  • #17

Попробовал запустить код вашей вьюхи в браузере — выдает ошибку 405, так как метод get(self, request): не определен.
Так что с тестом все нормально.
Просто чтобы тестить форму нужно делать post-запрос.

  • #18

Попробовал запустить код вашей вьюхи в браузере — выдает ошибку 405, так как метод get(self, request): не определен.
Так что с тестом все нормально.
Просто чтобы тестить форму нужно делать post-запрос.

получается что тест некорректен?
нужно для данной view переписывать его?

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Ошибка 404b что значит
  • Ошибка 4047 itunes
  • Ошибка 4045 при обновлении iphone
  • Ошибка 4045 при восстановлении iphone
  • Ошибка 4045 itunes

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии