0

it might be dumb question, but is it okey to use input without calling form.

my form

class st_image(forms.ModelForm):
    pro_img =forms.ImageField(widget=forms.FileInput(attrs={"id" :"upload_image", "class":"form-control image"}))
    
    class Meta:
        model=CustomUser
        fields= [ 'pro_img']

my View

def st_profile_img(request):
    pk = request.user.id
    obj = get_object_or_404(CustomUser, pk=pk)
    form=st_image(request.POST or None,request.FILES or None, instance=obj)
    if request.method == 'POST':
        if(form.is_valid()):       
            form.save()
            messages.success(request, "Амжилттай бүртгэлээ")
            return HttpResponseRedirect(reverse('st_profile'))
        else:
            messages.error(request, "Зөвхөн зураг хийнэ үү")
            return HttpResponseRedirect(reverse('st_profile'))

My template

<form method="POST" action="{% url 'st_profile_img' %}" enctype="multipart/form-data"
                            id="image-form">
                            {% csrf_token %}
                            <label for="upload_image" class="text-center student-profile-img">
                                <img id="uploaded_image" class="image-responsive" src="{{ user.pro_img.url }}" alt="">
                                <div class="overlay">
                                    <div class="text">Засах</div>
                                </div>
                                <input type="file" name="pro_img" class="image" id="upload_image"
                                    oninput="uploadImage()" style="display: none;" accept="image/x-png,image/jpeg" />
                            </label>
                        </form>

as you can see i didn't use {{form}} so is it okay use input like this(with using same name with expected form input)?

Or is there any correct way to call input name using form? (other than request.POST.get and not using attrs)

1 Answers1

0

Yes, you don't need to use {{ form }} in your template in order for the form to work. You will, however, need to supply all the correct <input> tags:

<input type="file" name="pro_img" ...>

This would have been done automatically if you rendered it like this:

{{ form.pro_img }}

But in that case you wouldn't be able to customize the <input> tags, which is probably why you have chosen the first approach.

Another way to customize your input fields is by creating your own custom widget, but this is probably a bit more work and not really needed in your case.

Jaap Joris Vens
  • 3,382
  • 2
  • 26
  • 42