I am new in programming and trying to make a website for Todo by using Python-django.
I am using Django Class Based Update View to make edit in datas.
But while I am click on submit button its not get saved.
models.py
class Task(models.Model):
name=models.CharField(max_length=25)
details=models.CharField(max_length=750)
priority=models.CharField(max_length=500)
date=models.DateField()
user=models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
def __str__(self):
return self.name
views.py
class TaskUpdateView(UpdateView):
model = Task
fields = "__all__"
template_name = 'update.html'
context_object_name = 'task'
success_url = reverse_lazy('cbvhome')
urls.py
path('update/<pk>',views.TaskUpdateView.as_view(),name='cbvupdate')
update.html
<form method="post" class=" justify-content-center align-items-center mb-4 ps" enctype="multipart/form-data">
{% csrf_token %}
<div class="mb-3">
<label for="task-id" class="form-label me-5">Task</label>
<input type="text" name="name" class="form-control" id="task-id" aria-describedby="emailHelp" style="width: 80%;" placeholder="Enter your Task Here" value="{{task.name}}">
</div>
<div class="mb-3">
<label for="exampleFormControlTextarea1" class="form-label me-5">Enter the details</label>
<textarea class="form-control" name="details" id="task-detail"rows="2" placeholder="Enter the task details" style="width: 80%;">{{task.details}}</textarea>
</div>
<div class="mb-3">
<label for="task-date" class="form-label me-5">Date set curerntly: {{task.date}}</label>
<input type="date" name="date" class="form-control" id="task-date" style="width: 80%;" value="{{task.date}}">
</div>
<div class="mb-3 mt-3">
<label for="task-prio" class="form-label me-5">Select the priority</label>
<select class="form-select" name="priority" aria-label="Default select example" style="width: 80%;" id="task-prio" value="{{task.priority}}">
<option selected>{{task.priority}}</option>
<option value="Very Urgent" class="text-danger">Very Urgent</option>
<option value="Urgent" class="text-warning">Urgent</option>
<option value="Important" class="text-primary">Important</option>
</select>
</div>
<div class="submit pe-5" style="padding-left: 100px; padding-top: 10px;" >
<input type="submit" class="btn btn-outline-success me-5" value="Save">
</div>
</form>
By default if nothing is given in url params, so it is considered as str type, so define it as int:
path('update/<int:pk>/',views.TaskUpdateView.as_view(),name='cbvupdate')
It will be better if you give action="{% url 'cbvupdate' %}" in form tag of HTML although not necessary as Django always takes current page route.
Note: Always add / at the end of every route.
Related
Basically I am filling in the details in my form in Django and clicking on submit but the error is appearing. What should I do?
My Error-
TypeError at /contact
Contact() got unexpected keyword arguments: 'name', 'email',
'phone','desc', 'date'
My models.py
from django.db import models
# Create your models here.
class Contact(models.Model):
name = models.CharField(max_length=122)
phone = models.CharField(max_length=122)
email = models.CharField(max_length=122)
desc = models.TextField()
My contacts.html
<h1 class="text-center">
Contact Us
</h1>
<form method="post" action="/contact">
{% csrf_token %}
<div class="form-group my-3">
<label for="Name" class="form-label">Name</label>
<input type="Name" class="form-control" id="Name">
</div>
<div class="form-group my-3">
<label for="phone" class="form-label">PhoneNumber</label>
<input type="phone" class="form-control" id="phone" name="phone" placeholder="Enter your Phone Number">
</div>
<div class="form-group my-3">
<label for="email" class="form-label">Email address</label>
<input type="email" class="form-control" id="email" name="email" aria-describedby="emailHelp">
<div id="emailHelp" class="form-text">We'll never share your email with anyone else.</div>
</div>
<div class="form-group my-4">
<label for="desc" class="form-label">Tell us about Yourself</label>
<input type="desc" class="form-control" name="desc" id="exampleDecription1">
</div>
<button class="btn btn-primary" type="submit">Submit</button>
</form>
</div>
{% endblock body %}
I made a customer feedback form with rating stars. But problem is, not getting stored data in database. Where the actual problem occured? What is the relevent solution? I tried many time.
forms.py:
class FeedBackForm(forms.Form):
feedBACK = forms.CharField(widget=forms.Textarea, required=True)
rating = forms.CharField(widget=forms.NumberInput)
models.py:
class ProductREVIEWS(models.Model):
rating = models.IntegerField(blank=True, null=True)
feedBACK = models.TextField(blank=True, null=True)
views.py:
def quick_view(request, quick_view_id):
form = FeedBackForm()
if request.method == "POST" and request.user.is_authenticated:
form = FeedBackForm(request.POST)
if form.is_valid():
ProductREVIEWS.objects.create(
feedBACK=form.cleaned_data.get('feedBACK'),
rating=form.cleaned_data.get('product_rating'),
)
template:
<form action="#!" method="POST" class="needs-validation mt-3" style="font-size: 13px;" novalidate="" autocomplete="off">
{% csrf_token %}
<div class="radio-toolbar d-flex">
<input type="radio" id="one_star" name="product_rating" value="1" checked>
<label for="one_star" class="mx-1">1 <i class="fas fa-star"></i></label>
<input type="radio" id="two_star" name="product_rating" value="2">
<label for="two_star" class="mx-1">2 <i class="fas fa-star"></i></label>
<input type="radio" id="three_star" name="product_rating" value="3">
<label for="three_star" class="mx-1">3 <i class="fas fa-star"></i></label>
<input type="radio" id="four_star" name="product_rating" value="4">
<label for="four_star" class="mx-1">4 <i class="fas fa-star"></i></label>
<input type="radio" id="five_star" name="product_rating" value="5">
<label for="five_star" class="mx-1">5 <i class="fas fa-star"></i></label>
</div>
<div class="mb-3 mt-2">
<textarea id="email" placeholder="Share your experiencs..." rows="10" style="font-size: 13px; text-transform: lowercase;" type="email" class="form-control" name="feedBACK" value="" required></textarea>
</div>
Since, you are not doing anything with FeedBackForm, so you can simply get the names of fields through POST request in view as:
from django.shortcuts import redirect
def quick_view(request, quick_view_id):
if request.method == "POST" and request.user.is_authenticated:
ProductREVIEWS.objects.create(
feedBACK=request.POST.get('feedBACK'),
rating=request.POST.get('product_rating')
)
return redirect('success')
return render(request, 'some_folder_name/index.html')
def success(request):
return render(request, 'some_folder_name/success.html')
Note: Its a good practice to redirect after dealing with POST data.
Template file:
<form method="POST" class="needs-validation mt-3" style="font-size: 13px;" autocomplete="off">
{% csrf_token %}
<div class="radio-toolbar d-flex">
<input type="radio" id="one_star" name="product_rating" value="1" checked>
<label for="one_star" class="mx-1">1 <i class="fas fa-star"></i></label>
<input type="radio" id="two_star" name="product_rating" value="2">
<label for="two_star" class="mx-1">2 <i class="fas fa-star"></i></label>
<input type="radio" id="three_star" name="product_rating" value="3">
<label for="three_star" class="mx-1">3 <i class="fas fa-star"></i></label>
<input type="radio" id="four_star" name="product_rating" value="4">
<label for="four_star" class="mx-1">4 <i class="fas fa-star"></i></label>
<input type="radio" id="five_star" name="product_rating" value="5">
<label for="five_star" class="mx-1">5 <i class="fas fa-star"></i></label>
</div>
<div class="mb-3 mt-2">
<textarea id="email" placeholder="Share your experiencs..." rows="10" style="font-size: 13px; text-transform: lowercase;" type="email" class="form-control" name="feedBACK" value="" required></textarea>
</div>
<input type="submit" value="save">
</form>
urls.py
urlpatterns = [
...
path('success/',views.success,name='success')
]
success.html
<body>
<h2>Form successfully submitted.</h2>
</body>
Your code isn't actually utilising the functionality of Django forms. Firstly, I would suggest using a model form rather than just a normal form - it will automatically do some of the lifting to connect the form with your model.
https://docs.djangoproject.com/en/4.0/topics/forms/modelforms/#modelform
Secondly, you are validating the form using is_valid() but you are then manually creating the object - you can instead using save() to create the model.
I have a modal popup that allows users to input data. I want to pass that data to Flask so that I can put it in my database. For some reason, no data is being passed. I am printing out request.form and it logs "ImmutableMultiDict([])", when it should contain my form's inputs. I have been trying to use POST, but I'm open to other ideas. This is happening on Heroku, I haven't tested it locally.
HTML
<!-- Modal -->
<div class="modal fade" id="newProjectModal" tabindex="-1" aria-labelledby="newProjectModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="newProjectModalLabel">Create Project</h5>
<button type="button" class="btn-close" aria-label="Close"></button>
</div>
<form action="/createproject/" name="createProjectForm" id="createProjectForm" method="POST">
<div class="modal-body">
<div class="mb-3">
<label for="projectNameInput" class="form-label">Project Name</label>
<input type="text" class="form-control" id="projectNameInput" name="projectName" placeholder="New Project">
</div>
<div class="mb-3">
<label for="projectDescriptionInput" class="form-label">Project Description</label>
<textarea class="form-control" id="projectDescriptionInput" name="projectDescription" rows="3"></textarea>
</div>
<label for="selectUsersInput" class="form-label">Assign Personnel</label>
<select class="form-select" id="selectUsersInput" name="selectUsers" multiple aria-label="multiple select example">
{% for user in users %}
<option value="{{ user }}">{{ user }}</option>
{% endfor %}
</select>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary">Close</button>
<button class="btn btn-primary" type="submit" name="submit" value="Submit">Create Project</button>
</div>
</tr>
</form>
</div>
</div>
</div>
Python
#app.route('/createproject/', methods=['POST'])
def createproject():
if request.method == 'POST':
print(request.form)
project_name = request.form.get('projectName')
project_description = request.form.get('projectDescription')
return '''
<h1>The name value is: {}</h1>
<h1>The description value is: {}</h1>'''.format(project_name, project_description)
project_name and project_description are always "None" instead of the entered value
I have created a form in Flask, and want to submit certain values which need to be processed.But the method used is getting defaulted to GET even though I have specified the method as post in my form
These are the the relevant code files:
app.py
#app.route('/test',methods=["GET","POST"])
def test():
print(request.method)
error = None
try:
if request.method == "POST":
first_name = request.form['firstname']
last_name = request.form['lastname']
flash(first_name)
flash(last_name)
return render_template("test.html")
else:
return "Wrong"
except Exception as e:
return str(e)
test.html
<form method="post" class="text-center" style="color: #757575;" action="">
<div class="form-row">
<div class="col">
<!-- First name -->
<div class="md-form">
<input type="text" name="firstname" value="{{request.form.firstname}}" class="form-control">
<label for="materialRegisterFormFirstName">First name</label>
</div>
</div>
<div class="col">
<!-- Last name -->
<div class="md-form">
<input type="text" name="lastname" value="{{request.form.lastname}}" class="form-control">
<label for="materialRegisterFormLastName">Last name</label>
</div>
</div>
</div>
<!-- File Upload -->
<div class="md-form">
<input type="file" id="fileupload" class="form-control">
</div>
<input class="btn btn-info btn-block" type="submit" value="Submit">
</form>
The method is getting defaulted to post and the response "Wrong" on loading 127.0.0.1:5000/test. The method is always GET
<form method="post" class="text-center" style="color: #757575;" action="/test" method="post">
<div class="form-row">
<div class="col">
<!-- First name -->
<div class="md-form">
<input type="text" name="firstname" value="{{request.form.firstname}}" class="form-control">
<label for="materialRegisterFormFirstName">First name</label>
</div>
</div>
<div class="col">
<!-- Last name -->
<div class="md-form">
<input type="text" name="lastname" value="{{request.form.lastname}}" class="form-control">
<label for="materialRegisterFormLastName">Last name</label>
</div>
</div>
</div>
<!-- File Upload -->
<div class="md-form">
<input type="file" id="fileupload" class="form-control">
</div>
<input class="btn btn-info btn-block" type="submit" value="Submit">
</form>
By adding the "route" to the action attribute and defining the method of submission of form, you can perform the desired objective.
I'm a bit confused with all the django stuff and forms, I hope you can help me.
I'm migrating a cmd line app to django, and I think I don't need to mess with models (db) atm. I just would like to pass the parameters filled in a form to a python script that use these fields as parameters. I would like to keep my html code and skip render the form with a python form class since it has a lot of css code inside each one.
At the moment I have this form:
<form class="nobottommargin" id="template-contactform" name="template-contactform" action="{% url 'get_data' %}" method="post">
{% csrf_token %}
<div class="col_half">
<label for="name">Project Name <small>*</small></label>
<input type="text" id="name" name="name" value="{{ current_name }}" class="sm-form-control required" />
</div>
<div class="col_half col_last">
<label for="group">Project Group <small>*</small></label>
<input type="text" id="group" name="group" value="{{ current_group }}" class="required sm-form-control" />
</div>
<div class="clear"></div>
<div class="col_half">
<label for="version">Project Version<small>*</small></label>
<input type="text" id="version" name="version" value="{{ current_version }}" class="required sm-form-control" />
</div>
<div class="col_half col_last">
<label for="pType">Project Type<small>*</small></label>
<select id="pType" name="pType" class="required sm-form-control">
<option value="">-- Select One --</option>
<option value="bundle">Bundle</option>
<option value="multiple">Multiple</option>
<option value="git">Git</option>
</select>
</div>
<div class="col_half">
<label for="pPath">Project path<small>*</small></label>
<input type="text" id="pPath" name="pPath" value="{{ current_path }}" class="required sm-form-control" />
</div>
<div class="clear"></div>
<div class="col_full hidden">
<input type="text" id="template-contactform-botcheck" name="template-contactform-botcheck" value="" class="sm-form-control" />
</div>
<div class="col_full" style="margin: 50px 0 0 0 ">
<button class="button button-3d nomargin" type="submit" id="template-contactform-submit" name="template-contactform-submit" value="submit">Create Project</button>
</div>
</form>
So, I want to figure out what's the best way to write the get_data function. I also need some sort of custom validation about some fields that involves other checks that exceeds the basic checks, such as max_chars on each field. That means I need to create some sort of my own form.is_valid() function.
Hope you can help me!
Regards