views.py
I am trying to upload an image but form.is_valid always return false
def upload(request):
if request.method=="POST":
form=uploadform(request.POST,request.FILES)
if form.is_valid():
cd=cleaned_data
form.save(commit=True)
return render(request,"success.html")
else:
form=uploadform()
return render(request,'pico.html',{'form':form})
here is the form
<form action="" method="post">
{{form.as_p}}
{% csrf_token %}
<input type="submit" value="Submit" />
</form>
forms.py
class uploadform(ModelForm):
class Meta:
model=examplemodel
fields=['pic']
models.py
class examplemodel(models.Model):
pic=models.ImageField()
Did you set enctype="multipart/form-data" in the html form tag?
Related
I don't want to use django form class as they will not give me much flexibility.
I have a form where will random number field in easy request. i am trying to populate the multiple value of forms that appears.
this is my models.py
class Profile(models.Model):
name = models.CharField(max_length=100)
photo = models.FileField()
and this my form.html
<form method="POST" action="{% url 'form' %}">
{% csrf_token %}
{% for i in range %}
<input type="text" id="name" name="name"><br>
<input type="file" id="photo" name="photo"><br><br>
{% endfor %}
<input type="submit" value="Submit">
</form>
You may notice I am rendering field with for loop.
that is means, there will be as much field as possible can be appear based on user request.
So I want to populate these models.
my view looks like
def form_view(request):
if request.method == 'POST':
# Need to puplate the form
return render(request, 'form.html', {'range': range(40)})
Can anyone please help me how can i achieve this? i am just struggling to achieve this.
you can use modelformset_factory for this. this way,
in your views.py
from .models import Profile
from django.forms import modelformset_factory
def form_view(request):
form_range = 40 # set the range here
ProfileFormSet = modelformset_factory(Profile, fields=("name", "photo"), extra=form_range, max_num=form_range)
formset = ProfileFormSet(request.POST or None)
if request.method == "POST":
if formset.is_valid():
formset.save()
return render(request, "form.html", {"profile_formset": formset})
and in your form html
<form method="POST" action="{% url 'form' %}">
{% csrf_token %}
{{ profile_formset.as_p }}
<input type="submit" value="Submit">
</form>
I am trying to upload profile image of user from userprofile.html template but it is not uploading to that model on admin panel. I already configured the static and media settings correctly. I am able to upload from admin panel.But uploading from template isn't working please help..
#forms.py
class ImageUploadForm(forms.ModelForm):
class Meta:
model = accountUser
fields = ['profile_photo',]
#views.py
def upload_pic(request):
if request.method == 'POST':
form = ImageUploadForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('success')
else:
form = ImageUploadForm()
return HttpResponseForbidden('allowed only via POST')
#user.html
<form method = "post" enctype="multipart/form-data">
{% csrf_token %}
<p>
<input id="id_image" type="file" class="" name="image">
</p>
<button type="submit">Choose Picture</button>
</form>
I am trying to use custom HTML to render form field elements. However, now the data is not saving. The data is saving if I use the default form.as_p method.
Related template:
<!--DOES NOT SAVE DATA-->
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.description }}
<input type="submit" value="Update"/>
</form>
<!--SAVES DATA-->
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Update"/>
</form>
Related UpdateView:
class ProfileEditView(UserPassesTestMixin, UpdateView):
model = Profile
form_class = ProfileCreateForm
template_name = 'update_profile_backup.html'
def get_success_url(self):
return reverse('profile', kwargs={'pk': self.object.pk})
def test_func(self):
obj = self.get_object()
print(obj.user == self.request.user)
return obj.user == self.request.user
Related ModelForm:
class ProfileCreateForm(forms.ModelForm):
class Meta:
model = Profile
fields = 'platform', 'content_niche', 'youtube_channel_id', 'description','profile_img', 'v_id_0', 'v_id_0_title', 'v_id_0_desc', \
'v_id_1', 'v_id_1_title', 'v_id_1_desc', 'v_id_2', 'v_id_2_title', 'v_id_2_desc'
Is it because the custom render method is not validating the form data? If so, how would I do that with an updateview?
Here is my form
Class SearchForm(forms.Form):
pub_from = forms.CharField(max_length=20)
pub_to = forms.CharField(max_length=20)
and my SearchView is
def SearchView(request):
if request.method == 'POST':
form = SearchForm(request.POST)
if form.is_valid():
pub_date_from = form.cleaned_data['pub_date_from']
pub_date_to = form.cleaned_data['pub_date_to']
#form.save()
return HttpResponseRedirect("/admin/")
else:
return render_to_response("search_form.html", {"form":form}, context_instance=RequestContext(request))
else:
form = SearchForm()
context = {"form":form}
return render_to_response("search_form.html", context, context_instance=RequestContext(request))
and my search_form.html is
<form action="" method="get">{% csrf_token %}
{{ form }}
<input type="submit" value="submit">
When I render the form singly it shows the form field and now when I inherit it to another template in category.html doing {% include "search_form.html" %} it only displays the submit button not the form field.
I dont know what am I doing wrong.
What is this???? <form action="" method="get">
the form method is a POST!
This was used by our throwing-stones ancestors:
<input type="submit" value="submit">
We now use button instead of input
I have a view and its template that handles and prints a form. The form has a ChoiceField that takes a list of models as choices. Here is my view, template and form:
*views.py*
def index(request):
form = dbForm()
print "form is: ", form
return render(request, 'Directories/index.html', {'form':form})
*index.html*
<div id="content" align="center">
<form action="" method="get"> {% csrf_token %}
{{form.as_p}}
<input type="submit" value="Edit" name="_add" />
</form>
*forms.py*
model_classes = []
class dbForm(forms.Form):
model_classes_field = forms.ChoiceField(choices=models())
def models():
apps = get_app('Directories')
for model in get_models(apps):
model_classes.append( (model._meta.verbose_name, model._meta.db_table), )
return model_classes
The model choice submitted is sent to another view where a ModelForm displays the model's fields and expects data for each of the fields to be submitted. The submitted data are then stored in the database and the user is redirected back to the index to start again from the beginning. Here is the view, template and form:
*views.py*
def modelUpdate(request):
if 'update' in request.POST: # If the form has been submitted...
form_class = get_dynamic_form(request.GET['model_classes_field'])
form = form_class(request.POST)
if form.is_valid(): # All validation rules pass
row = form.save() #saves into database
return render(request, 'Directories/index.html')
else:
print "form errors: ", form.errors
return HttpResponse('ERROR -- Return to form submission')
*create.html*
<form action="" method="post"> {% csrf_token %}
{% for f_name in field_names %}
{% if not forloop.first %}
{{f_name}}: <input id="edit-{{f_name}}" type="text" name={{f_name}} /><br />
{% endif %}
{% endfor %}<br />
<input type="submit" name="update" value="Update" />
<input type="reset" name="Clear" value="Clear" />
</form>
*forms.py*
#create a ModelForm using a dynamic model
def get_dynamic_form(c_model):
model_class = get_model('Directories', c_model)
class ObjForm(forms.ModelForm ):
class Meta:
model = model_class
return ObjForm
The problem occurs when the form is redirected back to the index.html return render(request, 'Directories/index.html') after the data have been saved into the database. What happens is that the index.html does not display the form {{form.as_p}}at all. Although when i check print "form is: ", form in my server (Apache) error.log, my form is there printed as it should be.
I cannot understand why the data are not rendered in my template after the redirection occurs but still they are displayed correctly in my server log.
You should pass the form instance to your template as you do in index view. Your code shall be updated to
def modelUpdate(request):
if 'update' in request.POST: # If the form has been submitted...
form_class = get_dynamic_form(request.GET['model_classes_field'])
form = form_class(request.POST)
if form.is_valid(): # All validation rules pass
row = form.save() #saves into database
#------------------------------------------------v pass it to template
return render(request, 'Directories/index.html', {'form': form})
else:
print "form errors: ", form.errors
return HttpResponse('ERROR -- Return to form submission')