Data not inserting in Django Database using Form DTL - python

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

Related

Django HttpResponseRedirect doesn´t lead to the page

I am working on the CS50 project2 commerce. I try to create a new list but when I click on the submit button, it doesn´t redirect to the index page as I want. Anybody can help please? I get the error message: auctions.models.Category.DoesNotExist: Category matching query does not exist. However I can add list directly from admin page.
views.py
def createlisting(request):
if request.method == "GET":
allCategories = Category.objects.all()
return render(request, "auctions/create.html", {
"categories": allCategories
})
else:
# get the data from the form
title = request.POST["title"]
description = request.POST["description"]
imageurl = request.POST["imageurl"]
price = request.POST["price"]
category = request.POST["category"]
currentuser = request.user
# get the contents
categoryData = Category.objects.get(categoryName=category)
#create new list object
newListing = Listing(
title=title,
description=description,
imageUrl=imageurl,
price=float(price),
category=categoryData,
owner=currentuser
)
newListing.save()
return HttpResponseRedirect(reverse("index"))
create.html
{% extends "auctions/layout.html" %}
{% block body %}
<h2>Create New Listing</h2>
<form action = "{% url 'create' %}" method="POST">
{% csrf_token %}
<div class="form-group">
<label for="title">Title</label>
<input type="text" name="title" class="form-control" id="title" placeholder="Enter title">
</div>
<div class="form-group">
<label for="description">Description</label>
<input type="text" name="description" class="form-control" id="description" placeholder="Enter Description">
</div>
<div class="form-group">
<label for="imageurl">Image URL</label>
<input type="text" name="imageurl" class="form-control" id="imageurl" placeholder="Image Url">
</div>
<div class="form-group">
<label for="price">Price</label>
<input type="number" name="price" class="form-control" id="price" placeholder="Price">
</div>
<div class="form-group">
<label for="category">Choose a Category</label>
<select name="category" id="category">
{% for category in categories %}
<option value="category">{{category}}</option>
{% endfor %}
</select>
</div>
<button type="submit" class="btn btn-success">Create New Listing</button>
</form>
{% endblock %}
Use redirect. And you don't need to use else after returning in the if statement.
from django.shortcuts import redirect
def createlisting(request):
if request.method == "GET":
allCategories = Category.objects.all()
return render(request, "auctions/create.html", {
"categories": allCategories
})
# POST
title = request.POST["title"]
description = request.POST["description"]
imageurl = request.POST["imageurl"]
price = request.POST["price"]
category = request.POST["category"]
currentuser = request.user
# get the contents
categoryData = Category.objects.get(categoryName=category)
#create new list object
newListing = Listing(
title=title,
description=description,
imageUrl=imageurl,
price=float(price),
category=categoryData,
owner=currentuser
)
newListing.save()
return redirect("index")
Try this view:
def createlisting(request):
allCategories=""
if request.method == "GET":
allCategories = Category.objects.all()
else:
# get the data from the form
title = request.POST["title"]
description = request.POST["description"]
imageurl = request.POST["imageurl"]
price = request.POST["price"]
category = request.POST["category"]
currentuser = request.user
# get the contents
categoryData = Category.objects.get(categoryName=category)
#create new list object
newListing = Listing(
title=title,
description=description,
imageUrl=imageurl,
price=float(price),
category=categoryData,
owner=currentuser
)
newListing.save()
return redirect("index")
return render(request, "auctions/create.html", {
"categories": allCategories
})

I am trying to create registration form with django forms.But when i enter data it returns ValueError at /register?

I am trying to create form using django forms.I created registration form when i enter data and click on submit it returns ValueError at /register and if i enter wrong data for example invalid email its not showing corresponding error?
def register(request):
if request.method == "POST":
form = Register(request.POST)
if form.is_valid():
email = form.cleaned_data['Email']
User_name=form.cleaned_data['Username']
Password=form.cleaned_data['Password']
Confirm_Password=form.cleaned_data['Confirm_Password']
User.objects.create_user(username=User_name,
password=Password,email=email)
return redirect("register")
else:
form = Register()
return render(request,'register.html',{'form': form})
<!------register.html--->
{% extends 'layout.html' %}
{% block content %}
<div class="box">
<h2>
<center>Register</center>
</h2><br>
<form action='register' method='POST'>
{% csrf_token %}
<div>
<label>Email:</label>
{{ form.Email }}
{{ form.Email.errors }}
</div>
<div>
<label>Username:</label>
{{ form.Username }}
{{ form.Username.errors }}
</div>
<div>
<label>Password:</label>
{{ form.Password }}
</div>
<div>
<label>Confirm Password:</label>
{{ form.Confirm_Password }}
{{ form.Confirm_Password.errors }}
</div>
<input type="Submit" id="lg"/><br>
<center><a href="login" >Already have an account.Login here.</a>
</center>
</form>
</div>
<div>
{% for message in messages%}
<h1>{{message}}</h1>
{% endfor %}
</div>
{% endblock %}
forms.py
from django import forms
from django.contrib.auth.models import User
from django.core.validators import validate_email
class Register(forms.Form):
Email = forms.EmailField(widget=forms.TextInput(attrs=
{"class":"inputvalues"}))
Username = forms.CharField(widget=forms.TextInput(attrs=
{"class":"inputvalues"}))
Password = forms.CharField(widget=forms.PasswordInput(attrs=
({"class":"inputvalues"})))
Confirm_Password = forms.CharField(widget=forms.PasswordInput(attrs=
({"class":"inputvalues"})))
class Meta():
model = User
fields = ['email','username','password']
def clean_Email(self):
try:
validate_email(self.cleaned_data['Email'])
except:
raise forms.ValidationError("Email is not in correct format!")
return self.cleaned_data['Email']
def clean_Username(self):
try:
User.objects.get(username = self.cleaned_data['Username'])
except:
return self.cleaned_data['Username']
raise forms.ValidationError("Username already exist!")
def clean_Confirm_Password(self):
pas=self.cleaned_data['Password']
cpas = self.cleaned_data['Confirm_Password']
if pas != cpas:
raise forms.ValidationError("Password and Confirm Password are
not matching!")
else:
if len(pas) < 8:
raise forms.ValidationError("Password should have atleast
8 character")
if pas.isdigit():
raise forms.ValidationError("Password should not all
numeric")
Showing Error Message : ValueError at /register
The view blog.views.register didn't return an HttpResponse object. It returned None instead.
In views.py
def register(request):
if request.method == "POST":
form = Register(request.POST)
if form.is_valid():
........
return redirect("register")
else:
return render(request,'register.html',{'form': form})
else:
form = Register()
return render(request,'register.html',{'form': form})
In register.html display errors like this:
{% if form.errors %}
<div class="alert alert-danger">
{{ form.errors }}
</div>
{% endif %}

django modelform how to know input type is checkbook?

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

Django select a valid choice error in form when using custom form template

I've been lurking for an answer for quite some time now, but I haven't found solution for my problems.
I made custom template for my form and now, when I try to submit form I get this under choice field: Select a valid choice. is not one of the available choices.
I believe that problems is because I am not passing instance of organization but id. I tried {{ form.instance.organization }} and then I get None where should be choice field
views.py:
class AddNewView(generic.View):
formClass = AddNewForm
template_name = 'myapp/subscription_form.html'
def get(self, request):
groups = self.request.user.groups.values_list('id', flat=True).first()
form = self.formClass(groups, None)
return render(request, self.template_name, {'form': form})
def post(self, request):
groups = self.request.user.groups.values_list('id', flat=True).first()
form = self.formClass(groups, request.POST)
if form.is_valid():
subscription = form.save(commit=False)
organization = request.user.groups.values_list('id', flat=True).first()
input_user = self.request.user
stuff = form.cleaned_data['stuff']
description = form.cleaned_data['description']
subscription.save()
return render(request, self.template_name, {'form': form})
forms.py:
class AddNewForm(forms.ModelForm):
def __init__(self, groups,*args,**kwargs):
super (AddNewView, self ).__init__(*args,**kwargs)
self.fields['organization'].queryset = Organization.objects.filter(group=groups)
class Meta:
model = Subscription
fields = [
'organization',
'stuff',
'description',
]
models.py:
class Organization(models.Model):
d_number = models.CharField(max_length=25)
city = models.CharField(max_length=100)
group = models.ManyToManyField(Group, help_text="groups")
class Subscription(models.Model):
organization = models.ForeignKey(Group, help_text="which organization")
input_user = models.CharField(max_length=150)
input_date = models.DateTimeField(auto_now_add=True)
description = models.CharField(max_length=1000, null=True, blank=True, help_text='Description')
stuff = models.CharField(max_length=100)
template:
<form action="" method="post">
{% csrf_token %}
<!-- Left Inputs -->
<div class="col-xs-6 wow animated slideInLeft" data-wow-delay=".5s">
<!-- Organization -->
{{ form.non_field_errors }}
<div class="fieldWrapper">
{{ form.organization.errors }}
<label>Organization:</label>
{{ form.organization }}
</div>
<!-- stuff -->
{{ form.non_field_errors }}
<div class="fieldWrapper">
{{ form.stuff.errors }}
<input type="text" name="stuff" id="id_stuff" required placeholder="stuff" class="form"/>
</div>
</div><!-- End Left Inputs -->
<!-- Right Inputs -->
<div class="col-xs-6 wow animated slideInRight" data-wow-delay=".5s">
<!-- description -->
{{ form.non_field_errors }}
<div class="fieldWrapper">
<textarea name="description" id="id_description" class="form textarea" placeholder="description"></textarea>
</div>
</div><!-- End Right Inputs -->
<div class="relative fullwidth col-xs-12">
<!-- Send Button -->
<button type="submit" class="form-btn semibold">Vnesi</button>
</div><!-- End Bottom Submit -->
</form>

form.is_valid always return false

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>

Categories