form.is_valid in views.py always return false. I have used Django forms to create a form and html to implement it.
I will upload this photo to imgur using imgurpython later, but first this should work.
views.py
def upload_view(request):
usr = check_validation(request)
if usr:
if request.method == "GET":
form = PostForm()
return render(request, 'upload.html', {'form': form})
elif request.method == "POST":
form = PostForm(request.POST, request.FILES)
if form.is_valid():
pic = form.cleaned_data.get('image')
title = form.cleaned_data.get('caption')
post = PostForm()
post.user = usr
post.caption = title
post.image = pic
post.save()
return redirect('feed/')
else:
return render(request, 'upload.html', {'error_msg' : "Invalid Inputs"})
else:
return redirect('/login/')
models.py
class Post(models.Model):
user = models.ForeignKey(User)
image = models.FileField(upload_to='user_images')
caption = models.CharField(max_length=240)
image_url = models.CharField(max_length=255)
created_on = models.DateTimeField(auto_now_add=True)
forms.py
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ['user', 'image', 'caption']
template - upload.html
<form method="post" enctype="multipart/form-data" class="loginbox" style="margin-top:200px;">
{% csrf_token %}
<p class="text-16">Upload to aperture.</p>
{{ form }}
<p class="text-16">{{ error_msg }}</p>
<input class="login-btn" type="submit" value="Upload"/>
</form>
Try this,
<form method="post" enctype="multipart/form-data" class="loginbox" style="margin-top:200px;">
{% csrf_token %}
{{ form }}
<input class="login-btn" type="submit" value="Upload"/>
</form>
If this doesn't work, print the request.POST and request.FILES then update the answer with the contents.
Your context has only one variable named form so you have to use that only to make your form work.
<form method="post" enctype="multipart/form-data" class="loginbox" style="margin-top:200px;">
{% csrf_token %}
<p class="text-16">Upload to aperture.</p>
<input type="file" accept="image/*" value="{{ form.image }}" name="image" class="login-btn"/><br/>
<input placeholder="Caption" class="input-default all-curve" rows="3" value="{{ form.caption }}" name="caption" />
<p class="text-16">{{ form.error_msg }}</p>
<input class="login-btn" type="submit" value="Upload"/>
</form>
Related
Here is my model.py file
class TestData(models.Model):
test_date = models.DateField(blank=True)
test_name = models.CharField(max_length=255)
result = models.IntegerField()
And here is my forms.py file
class TestDataForm(forms.ModelForm):
class Meta:
model = TestData
fields = ['test_date','test_name','result']
And here is my views.py file
def photo_single(request):
if request.POST:
form = TestDataForm(request.POST)
if form.is_valid():
if form.save():
return redirect('/', messages.success(request, 'Order was successfully created.', 'alert-success'))
else:
return redirect('/', messages.error(request, 'Data is not saved', 'alert-danger'))
else:
return redirect('/', messages.error(request, 'Form is not valid', 'alert-danger'))
else:
form = TestDataForm()
return render(request, 'photo_single.html', {'form':form})
and here is my photo_single.html file
<form>{% csrf_token %}
<div class="form-row">
<div class="form-group col-md-6">
<label for="date">Date</label>
{{ form.test_date | add_class:'form-control' | attr:'type:date' }}
</div>
<div class="form-group col-md-6">
<label for="test_name">Test Name</label>
{{ form.test_name | add_class:'form-control' }}
</div>
<div class="form-group col-md-6">
<label for="result">Result</label>
{{ form.result | add_class:'form-control' }}
</div>
</div>
<button type="submit" class="btn btn-primary" name="data">Submit</button>
</form>
When I'm submitting value from form to databasw, I'm getting this in url
http://127.0.0.1:8000/photo/?test_date=2020-03-13&test_name=SUGAR&result=23&data=
and data is not saving in database.
Can anyone help me out why ? I'm messed in this. Am I missed something here ?
Thanks
try this
def photo_single(request):
if request.POST:
form = TestDataForm(request.POST)
if form.is_valid():
base_form = form.save(commit=False)
base_form.save()
if form.save():
return redirect('/', messages.success(request, 'Order was successfully created.', 'alert-success'))
else:
return redirect('/', messages.error(request, 'Data is not saved', 'alert-danger'))
else:
return redirect('/', messages.error(request, 'Form is not valid', 'alert-danger'))
else:
form = TestDataForm()
return render(request, 'photo_single.html', {'form':form})
in template:
<form method="post" action="/your-url/">
{% csrf_token %}
---------
refer this
hope it helps
Picture gets uploaded on the django admin panel but when i click on the image on the panel it shows the page not found error.
forms.py
class ApproveImgForm(forms.ModelForm):
class Meta:
model = ApprovImg
fields = ['photo']
urls.py
path('w_p.html', views.WProduct_list, name='WProduct_list'),
views.py
def WProduct_list(request, category_slug=None):
category = None
categories = Category.objects.all()
wproducts = Product.objects.filter()
if category_slug:
category = get_object_or_404(Category, slug=category_slug)
wproducts = Product.objects.filter()
if(request.method=='POST'):
form = ApproveImgForm(request.POST, request.FILES)
form.save()
context = {
'category': category,
'categories': categories,
'wproducts': wproducts,
}
return render(request, 'shop/w_p.html', context)
models.py
class ApprovImg(models.Model):
photo=models.ImageField(upload_to='products/%Y/%m/%d')
def __str__(self):
return str(self.photo)
w_p.html
<tr>
<td>{{ product.name }}</td>
<td> {{ product.price }}</td>
<td><form action="w_p.html" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit">
</form>
</td>
</tr
Can someone please help?
You should inherit from ModelForm.
class ApproveImgForm(forms.ModelForm):
class Meta:
model = ApprovImg
fields = "__all__" # not recommended, you should specify the fields.
# views.py
def upload_file(request):
if request.method == 'POST':
form = ApproveImgForm(request.POST, request.FILES)
if form.is_valid():
# file is saved
form.save()
return HttpResponseRedirect('/home/')
else:
form = ApproveImgForm
return render(request, 'upload_image.html', {'form': form})
# urls.py
urlpatterns = [path('upload', upload_file, name='upload')]
# upload_image.html
<form action="{% url 'upload' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<p>{{ form.non_field_errors }}</p>
<p>{{ form.photo.label_tag }} {{ form.photo.help_text }}</p>
<p>
{{ form.photo.errors }}
{{ form.photo }}
</p>
<p><input type="submit" value="Upload" /></p>
</form>
I am new to django, my question is simple. How can I add two form in the same page? I tried many things as making a class in views or add a second urls path but didn't find how. Thanks you for helping
this is my code:
forms.py
class scrap_info(forms.Form):
url = forms.CharField(label="Urls")
website = forms.ChoiceField(label="Website", choices=ask_website)
class sms_info(forms.Form):
data = forms.ChoiceField(label="Data list", choices=ask_data)
number = forms.CharField(label="Sms number")
views.py
def scrap_app(request):
form1 = scrap_info(request.POST or None)
return render(request, "sms/scrap_app.html", {'form1': form1})
def sms_app(request):
form2 = sms_info(request.POST or None)
return render(request, "sms/sms_app.html", {"form2": form2})
scrap_app.html
<body>
<div>
<form method="POST">
{% csrf_token %}
{{ form|crispy }}
<button class="btn btn-outline-info" type="submit" value="Save">SCRAP</button>
</form>
</div>
</body>
urls.py
urlpatterns = [
path("/scrap_app", views.scrap_app, name="scrap_app"),
]
I have encountered this problem just recently and I solved it by adding a hidden field on every form and getting that hidden value to determine what form was submitted by using an if condition in views
Here's how I did it using CBV.
views.py
class ContactUsView(TemplateView):
template_name = 'yourtemplate.html'
def get(self, request, *args, **kwargs):
inquiry_form = InquiryForm(self.request.GET or None, prefix='inquiry_form')
complaint_form = ComplaintForm(self.request.GET or None, prefix='complaint_form')
context = self.get_context_data(**kwargs)
context['complaint_form'] = complaint_form
context['inquiry_form'] = inquiry_form
return self.render_to_response(context)
def post(self, request):
# instantiate all unique forms (using prefix) as unbound
inquiry_form = InquiryForm(prefix='inquiry_form')
complaint_form = ComplaintForm(prefix='complaint_form')
# determine which form is submitting (based on hidden input called 'action')
action = self.request.POST['action']
# bind to POST and process the correct form
if action == 'inquiry':
inquiry_form = InquiryForm(data=request.POST, prefix='inquiry_form')
if inquiry_form.is_valid():
# Your logic here
return self.render_to_response(
self.get_context_data(
inquiry_form=inquiry_form,
complaint_form=complaint_form,
)
)
messages.error(self.request,
'Inquiry form is invalid.')
elif action == 'complaint':
complaint_form = ComplaintForm(data=request.POST, prefix='complaint_form')
if complaint_form.is_valid():
# Your logic here
return self.render_to_response(
self.get_context_data(
inquiry_form=inquiry_form,
complaint_form=complaint_form,
)
)
messages.error(self.request,
'Complaint form is invalid.')
# prep context
context = {
'inquiry_form': inquiry_form,
'complaint_form': complaint_form,
}
return render(request, self.template_name, context)
yourtemplate.html
<!-- First Form -->
<form action="" method="post" role="form">
{% csrf_token %}
<input type='hidden' name='action' value='inquiry'>
{{ form1 }}
<button type="submit" title="Send Inquiry">Send Inquiry</button>
</form>
<!-- Second Form -->
<form action="" method="post" role="form">
{% csrf_token %}
<input type='hidden' name='action' value='complaint'>
{{ form2 }}
<button type="submit" title="Send Complaint">Send Complaint</button>
</form>
As you can see there's a hidden value in every form named 'action', that will be the one to determine which form was submitted.
My modelform is a dynamically generated modelform,I want to know the type of is_true in the modelForm. The type of the input tag is the checkbook type.
If I know the type=‘checkbox’ of the is_true field, add a class attr to him separately.
The default type='checkbox’ interface is too ugly
models
class Employee(AbstractBaseUser):
"""
用户表
"""
username = models.CharField(max_length=30, verbose_name='姓名')
email = models.EmailField(verbose_name='邮箱', unique=True)
is_true = models.BooleanField(default=False, verbose_name='是否超级用户')
views
class ModelFormDemo(ModelForm):
class Meta:
model = self.model
if self.list_editable:
fields = self.list_editable
else:
fields = '__all__'
excluded = self.excluded
def __init__(self, *args, **kwargs):
super(ModelFormDemo, self).__init__(*args, **kwargs)
def add_view(self, request):
form = ModelFormDemo()
if request.method == "POST":
res_dict = {'status': 1, 'msg': 'success'}
form = ModelFormDemo(request.POST)
if form.is_valid():
obj = form.save()
else:
res_dict['msg'] = form.errors
res_dict['status'] = 2
return JsonResponse(res_dict)
return render(request, "xadmin/add_view.html", locals())
html
<form class="layui-form" method="post">
{% csrf_token %}
{% for field in form %}
{% if field.name == 'employee' %}
<input type="hidden" name="employee" value="{{ user.id }}">
{% else %}
<div class="layui-form-item">
<label class="layui-form-label">{{ field.label }}</label>
<div class="layui-input-inline">
{{ field }}
</div>
</div>
{% endif %}
{% endfor %}
<div class="layui-form-item">
<div class="layui-input-block">
<input type="button" class="layui-btn" lay-filter="add" lay-submit="" value="add">
</input>
<button type="reset" class="layui-btn layui-btn-primary">reset</button>
</div>
</div>
</form>
You can use the Widget.attrs arg in your form __init__ method.
https://docs.djangoproject.com/en/dev/ref/forms/widgets/#django.forms.Widget.attrs
I have a template form and trying to save some data. Upon clicking on the submit button the page just refreshes and nothing gets saved to the database. I don't get any errors on anything.
template
<form action="" method="post" id="salesform">
{% csrf_token %}
<input type="name" class="form-control" id="name" placeholder="Name">
<input type="clinic" class="form-control" id="clinic_name" placeholder="Clinic">
<input type="phone" class="form-control" id="phone" placeholder="Phone">
<input type="email" class="form-control" id="email" placeholder="Email">
<button id="sub" type="submit" class="btn btn-default">Submit</button>
</form>
forms.py
class LeadForm(forms.ModelForm):
name = forms.CharField(max_length=250, required= True,widget=forms.TextInput())
clinic_name = forms.CharField(max_length=250, required= True,widget=forms.TextInput())
phone = forms.CharField(max_length=8, required= True,widget=forms.TextInput(attrs={'type':'number'}))
email = forms.CharField(max_length=250, required= False, widget=forms.TextInput())
class Meta:
model = Lead
fields = ("clinic_name","phone")
views.py
def add_doc_info(request):
d = getVariables(request,dictionary={'page_name': "Doctors",
'meta_desc' : "Sign up "})
if request.method == "POST":
SalesForm = LeadForm(request.POST)
if SalesForm.is_valid():
name = SalesForm.cleaned_data['name']
clinic_name = SalesForm.cleaned_data['clinic_name']
phone = SalesForm.cleaned_data['phone']
email = SalesForm.cleaned_data['email']
#Saving to database
lead = Lead(name=name, clinic_name=clinic_name, phone=phone, email=email)
lead.save()
else:
SalesForm = LeadForm()
return render(request, 'm1/add_doc_info.html', d, context_instance=RequestContext(request))
models.py
class Lead(models.Model):
name = models.CharField(max_length=1300)
clinic_name = models.CharField(max_length=1300)
phone = models.IntegerField()
email = models.EmailField(blank = True)
submitted_on = models.DateField(auto_now_add=True)
def __unicode__(self):
return u"%s %s" % (self.clinic_name, self.phone)
Almost certainly the form is not valid, but you're not using it in your template so there is no way for it to display errors, or redisplay itself with partially-filled fields.
The Django documentation is fairly explicit on this, so I don't know why you have done something different. Pass the form into your context:
d['form'] = SalesForm
return render(request, 'm1/add_doc_info.html', d)
and use it in the template:
{{ form.errors }}
<form action="" method="post" id="salesform">
{% csrf_token %}
{{ form.name }}
{{ form.clinic_name }}
{{ form.phone }}
{{ form.email }}
<button id="sub" type="submit" class="btn btn-default">Submit</button>
</form>
(Note also you've unnecessarily defined all the fields explicitly in the form, but also stated you are only using two of them in the meta class; also your is_valid block is mostly unnecessary as you can just call form.save() directly. Again, all this is shown fully in the documentation.)