How is it possible to get data from one form that has multiple textareas in Django - django

I'd like to get data from one form that has multiple textareas inside , In my views: 'compare_ingredients' I've tried requesting data from my form id 'compareform' also the textarea id 'ingredients', but when I enter something into one texture and click on submit it comes back as 'None' when I print. Here is my html and views:
html :
<div class="container-fluid">
<h4>Please enter in your ingredients:</h4>
<h6>(Seperate each item by comma)</h6>
<br>
<button class="add_item">Add Item</button>
<br>
<div class="row row-cols-1 row-cols-md-2 mx-auto">
<form action="{% url 'compare_ingredients' %}" method="POST" name="compareform" id="compare">
{% csrf_token %}
<br>
<button type="submit" class="btn btn-info sub_btn">Submit</button>
<button type="submit" class="btn btn-secondary back_button">
Back
</button>
<br>
<br>
<div class="row form_row">
<div class="col mb-4">
<h5>Item 1</h5>
<div class="card form_card">
<div class="card-body compare_cardbody">
<textarea name="ingredients1" id="ingredients" cols="30" rows="10" form="compareform"></textarea>
</div>
</div>
</div>
<div class="col mb-4">
<h5>Item 2</h5>
<div class="card form_card">
<div class="card-body compare_cardbody">
<textarea name="ingredients2" id="ingredients" cols="30" rows="10" form="compareform"></textarea>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
views.py:
def compare_ingredients(request):
if request.method == "POST":
ingredients = request.POST.get('compareform')
print(ingredients)
return render(request, 'result/compare.html')

ok, I figured it out , the problem was in the html textarea I had the name of the form as 'compareform' when it should have been 'compare' :
<textarea name="ingredients2" id="ingredients" cols="30" rows="10" form="compare"></textarea>
then in my views I did:
ingredients1 = request.POST.get('ingredients1')

Related

Button type "submit" doesn't let bootstrap modal to open but type="button" doesn't fulfill my need. How to use AJAX to solve this?

I have a web page in which there is an input field. And below is an edit button. When I enter some text in the input field and press the edit button, a modal pops up and there is an input field in it also. I want to pass the text from the first input field to the input field in the modal window.
But then a problem arises. The modal window only opens when the edit button has type="button". But this type="button" doesn't submit the text input to the backend when I click the edit button. It submits the text to the backend when I use button type="submit", but then the modal doesn't open because the page reloads.
I don't know how to use AJAX, how can this be done with AJAX?
Here's my HTML code:
<div class="container">
<div class="row manage-groups">
<div class="row g-0 login_form justify-content-center" id="contactForm" novalidate="novalidate">
<form method="POST">
{% csrf_token %}
<div class="col-md-12 form-group">
<input type="text" class="login-inpt" id="name" name="type-groups" placeholder="type in the group name">
</div>
<div class="row g-0 justify-content-center group-action">
<div class="col-sm-4 submit-group">
<div>
<button type="submit" data-bs-toggle="modal" data-bs-target="#ModalAddGroups"
class="button-box">Add</button>
</div>
</div>
<div class="col-sm-4 submit-group">
<button type="button" onclick="form_submit()" data-bs-toggle="modal" data-bs-target="#ModalEditGroups"
class="button-box">Edit</button>
</div>
<div class="col-sm-4 submit-group">
<button type="submit" data-bs-toggle="modal" data-bs-target="#ModalDeleteGroups"
class="button-box">Delete</button>
</div>
</div>
</form>
</div>
</div>
</div>
<!-- Modal window for Edit button -->
<div class="modal fade" id="ModalEditGroups" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle"
aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content edit-modal">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Edit Group</h5>
<button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body grid-container">
<input type="text" value="{{ group.group_name }}">
{{ group.group_name }}
{{ group }}
<table class="edit-groupLinks">
<thead>
<tr class="header">
<th>Links</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" value="www.google.com"></td>
<td><button type="button" class="delete" aria-label="Close">
<span aria-hidden="true">×</span>
</button></td>
</tr>
</tbody>
</table>
<button class="add-linkBTN"><i class="fa fa-plus" aria-hidden="true"></i></button>
</div>
<div class="modal-ftr">
<button type="submit" class="button-box" id="footer-btn">Save</button>
</div>
</div>
</div>
</div>
Views.py file:
def manageGroups(request):
form = GroupSorting()
group = request.POST.get('type-groups', False)
content = Groups.objects.filter(group_name__contains = group)
if request.method == "POST":
form = GroupSorting(request.POST)
if form.is_valid():
form.save()
else:
form = GroupSorting()
context = {'form': form, 'group': content}
return render(request, 'posts/manage-groups.html', context)

Distinguish which link-button clicked in django

I have that html code:
<form id="my-form" method="POST" action="{% url 'my_view' %}">
{% csrf_token %}
<div class="row">
<div class="col-md-6">
<div class="md-form mb-1">
<textarea id="message" name="message" rows="2" class="form-control md-textarea"></textarea>
</div>
</div>
<div class="col-md-6">
<div class="md-form mb-1">
<textarea id="message_then" name="message_then" rows="2" class="form-control md-textarea"></textarea>
</div>
</div>
</div>
<div class="text-center text-md-left">
<a class="btn btn-primary" onclick="document.getElementById('my-form').submit();" style="width: 78px;" name="name1">Click1</a>
</div>
<div class="text-center text-md-left">
<a class="btn btn-primary" onclick="document.getElementById('my-form').submit();" style="width: 78px;" name="name2">Click2</a>
</div>
</form>
Now I would like to get to know which "button" was clicked. Unfortunately request.POST doesn't have that information.
You should add another field to specify which button has been clicked.
Exp:
Add this to your form
then update your "a" elements onclick event code like this:
<a class="btn btn-primary" onclick="update_form(this)" style="width: 78px;">Click1</a>
And finally some js code to update the form
<script>
function update_form(button){
document.getElementById("id_button").value = document.getElementById(button).innerText;
document.getElementById('my-form').submit();
}
</script>
In your django view use this to get the selected button:
request.POST['id_button']

How can I remove a particular item using a popup?

I have many items and I want to delete one of them but when I delete one item it turns out that it deletes the last item which exists based on ordering so, if I have 10 records of id which start from 1 to 10 record so, it will remove the item number 10 til if I remove item number 5 will remove the number 10. this case occurs because of popup but if I remove popup and delete the items directly it will remove with no mistake so, How can I remove a particular item using popup?
profile.html
{% if request.user == profile.user %}
<div class="col-lg-7 offset-lg-1 col-12">
{% if profile.user.user_history.all.count != 0 %}
<form method="post">
{% csrf_token %}
<div class="clear_all fl-left">
<input class="global_checkbox" type="checkbox" name="remove_all_history" id="remove_all_history">
<label for="remove_all_history" class="ml">Remove All</label>
</div>
<div class="fl-right">
<input type="submit" value="Remove" class="clear_button btn btn-danger invisible"/>
</div>
</form>
{% else %}
<p class="text-center">you have no history yet!</p>
{% endif %}
<div class="clearfix"></div>
<div class="mt-6"></div>
{% for history in history_pages %}
{% if history.deleted_history == False %}
<div class="history">
<div class="row">
<div class="col-4">
<form method="post">
{% csrf_token %}
<input class="global_checkbox" type="checkbox" name="remove_one_history" id="remove_all_history">
<span class="ml-2">{{ history.history_time|time }}</span>
<div class="ml ml-4">{{ history.history_time|date:'d M Y' }}</div>
</form>
</div>
<div class="history-content col-7">
<p><strong>text:</strong> {{ history.history }}</p>
<p><strong>action:</strong> {{ history.action_option }}</p>
<p><strong>position:</strong>
{% if history.verb_option == "" %}
POS
{% else %}
{{ history.verb_option }}
{% endif %}
</p>
</div>
<form method="post" action="{% url 'accounts:remove_history' history.id %}">
{% csrf_token %}
<div class="history-list col-1">
<span class="fa fa-ellipsis-v" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"></span>
<div class="dropdown-menu">
<a type="button" class="dropdown-item" data-toggle="modal" data-target="#exampleModal">Remove this item</a>
</div>
</div>
{% include 'accounts/popup.html' %}
</form>
</div>
</div>
{% endif %}
{% endfor %}
</div>
{% endif %}
popup.html
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Warning!!</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Do you want to remove this history item?
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-outline-danger">Remove</button>
</div>
</div>
</div>
</div>
views.py
#login_required
def userProfile(request, slug=None):
profile = None
try:
profile = Profile.objects.get(user__slug=slug)
paginator = Paginator(profile.user.user_history.all(), 100)
page_number = request.GET.get('page_number')
history_pages = paginator.get_page(page_number)
except:
return redirect('accounts:index_404')
return render(request, 'accounts/profile.html', {'profile': profile, 'history_pages': history_pages})
def remove_history(request, id=None):
if id and id is not None:
# History.objects.get(id=id)
print(id)
return redirect("accounts:profile", request.user.username)
Note: I tested the delete using print(id)
In your current code you have included popup.html mutliple times so when you click on a tag its not confirm which modal will get open has all are triggering exampleModal i.e :data-target="#exampleModal" .
So , to overcome this one way would be including only one modal and adding form tags around submit button . Then , whenever user click on a tag you can get action value from form where a tag has been clicked and then add this action value inside modal form tag .
Demo Code :
//on click of `a` tag
$(".dropdown-item").on("click", function() {
//get closest form from `a` tag then get action from it
var action_ = $(this).closest("form").attr("action");
$("#exampleModal form").attr("action", action_) //add that action inside modal form tag
console.log(action_)
})
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<div class="history">
<div class="">
<div class="">
<form method="post">
{% csrf_token %}
<input class="global_checkbox" type="checkbox" name="remove_one_history" id="remove_all_history">
<span class="">12:30</span>
<div class="">12-04-21</div>
</form>
</div>
<div class="history-content">
<p><strong>text:</strong> Somethigs</p>
<p><strong>action:</strong>Ok</p>
<p><strong>position:</strong> POS
</p>
</div>
<form method="post" action="{% url 'accounts:remove_history' 1 %}">
<div class="history-list">
<span class="fa fa-ellipsis-v" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"></span>
<div class="dropdown-menu">
<a type="button" class="dropdown-item" data-toggle="modal" data-target="#exampleModal">Remove this item</a>
</div>
</div>
<!--remove this line {% include 'accounts/popup.html' %}-->
</form>
</div>
</div>
<div class="history">
<div class="">
<div class="">
<form method="post">
{% csrf_token %}
<input class="global_checkbox" type="checkbox" name="remove_one_history" id="remove_all_history">
<span class="">12:32</span>
<div class="">22-04-21</div>
</form>
</div>
<div class="history-content">
<p><strong>text:</strong> Somethigs2</p>
<p><strong>action:</strong>Ok2</p>
<p><strong>position:</strong> POS
</p>
</div>
<form method="post" action="{% url 'accounts:remove_history' 2 %}">
<div class="history-list">
<span class="fa fa-ellipsis-v" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"></span>
<div class="dropdown-menu">
<a type="button" class="dropdown-item" data-toggle="modal" data-target="#exampleModal">Remove this item</a>
</div>
</div>
<!--remove this line {% include 'accounts/popup.html' %}-->
</form>
</div>
</div>
<!--just use only one modal no need to include it every time on your page-->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Warning!!</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<!--added form tag-->
<form method="post" action="">
<!--added csrf token-->
{% csrf_token %}
<div class="modal-body">
Do you want to remove this history item?
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-outline-danger">Remove</button>
</div>
</form>
</div>
</div>
</div>

Django - handle two form elements for the same model in one template

I am using the following UpdateView in order to alter some values in the database:
class MyUpdateView(UpdateView):
model = MyModel
fields = ['VideoURL', 'MainDescription']
template_name = 'myapp/edit.html'
This is my template:
<div class="row">
<div class="col-12 col-lg-7">
<form method='post' class="card shadow-soft border p-4 mb-4">
{% csrf_token %}
<h5 class="mb-4">General</h5>
<div class="form-group">
<label for="MainDescription">Title</label>
{{form.MainDescription|add_class:"form-control shadow-soft"}}
</div>
<div class="row">
<div class="col">
<button class="btn btn-primary btn-dark mt-2 animate-up-2"
type="submit">Update</button>
</div>
</div>
</form>
</div>
<div class="col-12 col-lg-5">
<form method='post' class="card shadow-soft border p-4 mb-4">
{% csrf_token %}
<div class="form-group">
<label for="VideoURL">Video URL:</label>
{{form.VideoURL|add_class:"form-control shadow-soft"}}
</div>
<div class="row">
<div class="col">
<button class="btn btn-primary btn-dark mt-2 animate-up-2 text-right"
type="submit">Update</button>
</div>
</div>
</form>
</div>
</div>
However, I am facing some difficulties doing so because although both fields belongs to the same model, I cannot update any of the information. What I have noticed though is that if I place the both fields under the same HTML form, it works:
<div class="col-12 col-lg-5">
<form method='post' class="card shadow-soft border p-4 mb-4">
{% csrf_token %}
<div class="form-group">
<label for="VideoURL">Video URL:</label>
{{form.VideoURL|add_class:"form-control shadow-soft"}}
</div>
<div class="form-group">
<label for="MainDescription">Main Description:</label>
{{form.MainDescription|add_class:"form-control shadow-soft"}}
</div>
<div class="row">
<div class="col">
<button class="btn btn-primary btn-dark mt-2 animate-up-2 text-right"
type="submit">Update</button>
</div>
</div>
</form>
</div>
What am I missing here? Can anyone give me a hint? Thanks
Edit
It's due to how the forms are being displayed in the HTML form. They should be independent:

How to Upload any kind of file in django 2

I'm New in Django 2. I was trying to upload a file in Django here is my code
View.py
def addBook(request):
checkName = AddBook.objects.filter(title=request.POST.get('title'))
if not checkName:
bookAdd = AddBook(
title=request.POST.get('title'),
slug=slugify(request.POST.get('title')),
description=request.POST.get('description'),
cover_image=request.FILES.get('cover_image'),
file=request.FILES.get('file'),
category=request.POST.get('category'),
created_by=request.user.id,
)
bookAdd.save()
messages.add_message(request, messages.INFO, 'Book Saved Successfully')
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
else:
messages.add_message(request, messages.INFO, 'Book Title Already Exists')
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
Update As per Comment
Here is my template code
bookSave.html
<form action="{% url 'addBook' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="modal-body">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs 12">
<div class="form-group ic-cmp-int">
<div class="form-ic-cmp">
<i class="notika-icon notika-edit"></i>
</div>
<div class="nk-int-st">
<input type="text" class="form-control input-sm" required="required" name="title"
Placeholder="Title">
</div>
</div>
</div>
</div>
<div class="modal-body">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="form-group ic-cmp-int">
<div class="form-ic-cmp">
<i class="notika-icon notika-mail"></i>
</div>
<div class="nk-int-st">
<textarea class="form-control input-sm" required="required" name="description"
placeholder="Description"></textarea>
</div>
</div>
</div>
</div>
<div class="modal-body">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="form-group ic-cmp-int">
<div class="form-ic-cmp">
<i class="notika-icon notika-dollar"></i>
</div>
<div class="nk-int-st">
<input type="file" name="cover_image" required="required" class="form-control input-sm">
</div>
</div>
</div>
</div>
<div class="modal-body">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="form-group ic-cmp-int">
<div class="form-ic-cmp">
<i class="notika-icon notika-house"></i>
</div>
<div class="nk-int-st">
<input type="file" name="file" required="required" class="form-control input-sm">
</div>
</div>
</div>
</div>
<div class="modal-body">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="form-group ic-cmp-int">
<div class="form-ic-cmp">
<i class="notika-icon notika-next"></i>
</div>
<div class="nk-int-st">
<input type="text" name="category" required="required" class="form-control input-sm"
Placeholder="Category">
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-default">Save changes</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form>
I can save everything but I need to save the file path and save the file locally. I read their documentation but cannot help me out. Please help me to solve this problem
The FileField in your Model, besides the other fields, should look like this:
class AddBook(models.Model):
# file will be uploaded to MEDIA_ROOT/uploads
file = models.FileField(upload_to='uploads/')
# or...
# file will be saved to MEDIA_ROOT/uploads/2015/01/30
file = models.FileField(upload_to='uploads/%Y/%m/%d/')
In your settings file, you’ll need to define MEDIA_ROOT as the full path to a directory where you’d like Django to store uploaded files. (For performance, these files are not stored in the database.) Define MEDIA_URL as the base public URL of that directory. Make sure that this directory is writable by the Web server’s user account.
in settings.py you should set for example:
MEDIA_ROOT = '/home/foo/bar/yourproject/assets'
Also you might want to study and set static files storage in Django (besides the ‘static’ folder).
https://docs.djangoproject.com/en/2.0/howto/static-files/#configuring-static-files
In Django you can get any file with the File Object like:
from django.core.files import File
# Open an existing file using Python's built-in open()
f = open('/path/to/mybookfile.pdf')
myfile = File(f)