DJANGO: В объекте QueryDict отсутствует атрибут 'status_code'

Я немного застенчив. Это мой первый вопрос здесь, и мой английский не очень хорош.

Поэтому я сделал CreateAdvert CBV(CreateView) и переопределил метод 'post' для него.

Мне нужно обновить QueryDict и добавить к нему поле 'user'. Но когда я пытаюсь вернуть контекст. В заголовке говорится об ошибке.

Просмотров:

class CreateAdvert(CreateView):
    form_class = CreateAdvert
    template_name = 'marketapp/createadvert.html'
    context_object_name = 'advert'


    def post(self, request):
        #Because I don't want to give QueryDict 'user' field right from the form, I override the
        #post method here.
        user = User.objects.filter(email=self.request.user)[0].id
        context = self.request.POST.copy()
        context['user'] = user
        return context

Формы:

class CreateAdvert(forms.ModelForm):
    class Meta:
        model = Advertisment
        fields = ['category', 'title',
                  'description', 'image',
                 ]

Я пытался охватить контекст с помощью HttpRequest(). Это не дало мне большого результата. но я попытался.

См: https://docs.djangoproject.com/en/4.1/topics/http/views/

Вы должны вернуть объект ответа, а не словарь context из CreateView:

Нравится:

from django.http import HttpResponse
import datetime

def current_datetime(request):
    now = datetime.datetime.now()
    html = "<html><body>It is now %s.</body></html>" % now
    return HttpResponse(html)

Из ошибки: obj has no attribute 'status_code' после возврата происходит django пытается найти status_code которое является ожидаемым свойством HttpResponse объекта.

Ор:

    def post(self, request):
        #Because I don't want to give QueryDict 'user' field right from the form, I override the
        #post method here.
        user = User.objects.filter(email=self.request.user)[0].id
        context = self.request.POST.copy()
        service.create_advert(context, user)
        context['user'] = user
        return HttpResponse('ok', status=200)

Что касается того, где/как установить context Я думаю, что это происходит в другом методе обычно.

class CreateAdvert(CreateView):
    form_class = CreateAdvert
    template_name = 'marketapp/createadvert.html'
    context_object_name = 'advert'


    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        user = User.objects.filter(email=self.request.user)[0].id
        context = self.request.POST.copy()
        context['user'] = user
        return context
Вернуться на верх