G
G
guit242022-02-03 01:17:26
Django
guit24, 2022-02-03 01:17:26

What is the error in trying to test the file upload?

Models.py

class News(models.Model):
    title = models.CharField(max_length=40, verbose_name='Название')
    description = models.CharField(max_length=200, verbose_name='Описание')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True, verbose_name='Дата изменения', editable=True)
    is_active = models.BooleanField(default=True, verbose_name='Активное')
    user = models.ForeignKey(User, default=None, null=True, on_delete=models.PROTECT, verbose_name='Пользователь',
                             related_name='users_news', blank=True)


<b>forms.py</b>
class NewsForm(forms.ModelForm):
    images = forms.ImageField(widget=forms.ClearableFileInput(attrs={'multiple': True}),
                                  label='Выберите изображения, не больше 4', required=False)

    class Meta:
        model = News
        fields = ['title', 'description']
        widgets = {
            'description': forms.Textarea(attrs={'cols': 30, 'rows': 10}),
        }

<b>views.py</b>
class CreateNews(LoginRequiredMixin, FormView):

    login_url = reverse_lazy('login')
    redirect_field_name = 'redirect_to'

    form_class = NewsForm
    template_name = 'news/add_news.html'
    success_url = reverse_lazy('news')

    def form_valid(self, form):
        messages.success(self.request, 'Новость успешно добавлена')
        # return HttpResponseRedirect(self.get_success_url())
        return super().form_valid(form)

    def form_invalid(self, form, text=None):
        messages.error(self.request, text)
        return self.render_to_response(self.get_context_data(form=form))

    @transaction.atomic
    def post(self, request, *args, **kwargs):
        form_class = self.get_form_class()
        form = self.get_form(form_class)

        if form.is_valid():

            files = request.FILES.getlist('images')

            if len(files) > 4:
                text = 'Вы можете прикрепить не больше 4х изображений'
                return self.form_invalid(form, text)

            news = form.save(commit=False)
            news.user = self.request.user
            news.save()

            for f in files:
                instance = Image(photo=f, item=news)
                instance.save()
            return self.form_valid(form)
        else:
            return self.form_invalid(form)
<b>
Сам тест:</b>
        img = os.path.join(settings.TEST_FILES, 'test1.jpeg')
        photo = SimpleUploadedFile(name='test1.jpeg',
                                   content=b'Test test text|2021-11-05 12:25',
                                   content_type='image/jpeg')

        response_post = self.client.post(url, {'title': 'Title for news to add', 'description': 'ОПИСАНИЕ',
                                               'user': self.client, 'images': photo})


Why isn't redirecting to the page using the successful url when uploading a file? why is this test self.assertEquals(response_post.status_code, 302) giving an AssertionError: 200 != 302
Why is the form not valid? how to properly organize file test?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question