L
L
liss666-netizen2019-11-10 18:58:34
Django
liss666-netizen, 2019-11-10 18:58:34

Django how to upload image via form?

view.py

class TagCreate(View):
    def get(self, request):
        form = TagForm()
        return render(request, 'blog/tag_create.html', context ={'form' : form})

    def post(self , request):
        bound_form = TagForm(request.POST)
        if bound_form.is_valid():
            new_tag = bound_form.save()
            return redirect(new_tag)
        return render(request, 'blog/tag_create.html', context ={'form' : bound_form})

model.py
class Tag(models.Model):
    title = models.CharField(max_length=50)
    slug = models.SlugField(max_length=50, unique=True)
    image = models.ImageField(upload_to='cat/', blank=True, null=True,)

    def get_absolute_url(self):
        return reverse('tag_detail_url', kwargs={'slug':self.slug})

    def __str__(self):
        return '{}'.format(self.title)

form.py
from django.core.exceptions import ValidationError

class TagForm(forms.Form):
    title = forms.CharField(max_length=50)
    slug = forms.CharField(max_length=50)
    #image = forms.ImageField()

    title.widget.attrs.update({'class' : 'form-control'})
    slug.widget.attrs.update({'class' : 'form-control'})
    #image.widget.attrs.update({'class' : 'form-input'})

    def clean_slug(self):
        new_slug = self.cleaned_data['slug']

        if new_slug == 'create':
            raise ValidationError([ValidationError(_('Error 1'), code='error1'),])
        return new_slug

    def save(self):
        new_tag = Tag.objects.create(
            title = self.cleaned_data['title'],
            slug = self.cleaned_data['slug'],
            #image = self.cleaned_data['image']
                )
        return new_tag

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dr. Bacon, 2019-11-10
@bacon

https://docs.djangoproject.com/en/2.2/topics/http/...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question