I am using an automatically generated Bootstrap form to allow the user to upload files to the database. The form is generated inside a modal like this:
<div class="modal fade" id="uploadModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Dateien hinzufügen</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form method="post" enctype="multipart/form-data">
<div class="modal-body">
{% csrf_token %}
{% bootstrap_form form %}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Abbrechen</button>
<button type="submit" class="btn btn-primary">OK</button>
</div>
</form>
</div>
</div>
</div>
using a Django form and file structure that look like this:
import django.forms as forms
from .models import StandaloneFile
# Create the form class.
class StandaloneFileForm(forms.ModelForm):
file = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))
class Meta:
model = StandaloneFile
fields = ['file', 'profile', 'description']
and
from django.db import models
# Create your models here.
def file_directory_path(instance, filename):
# file will be uploaded to MEDIA_ROOT/<profile.abbr>/<filename>
return '{0}/{1}'.format(instance.profile.abbr, filename)
class StandaloneFile(models.Model):
file = models.FileField(upload_to=file_directory_path)
profile = models.ForeignKey('MeasurementProfile',on_delete=models.SET_NULL,null=True)
description = models.TextField()
date_uploaded = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.file.name.split("/")[-1]
Now if I click the submit button the fields file, profile and description should be send via POST however if I look at request.POST only the fields file and profile are send and the variable file does not exist.
What did I do wrong here?
# This text is here to fill the answer to get to 30 characters minimum
request.FILES
Related
I am using django 3.2 along with datatables and bootstrap 5. it shows pagination correctly using datatables. I want to show Links/buttons like First, previous,Next and Last on edit productstatus form using datatables pagination or django pagination django.core.paginator whose details as shown below
class ProductStatus(models.Model):
ProductID = models.CharField(max_length=512, verbose_name="ProductID", null=False, blank=False)
Description = models.CharField(max_length=512, verbose_name="Description", null=True, blank=True)
CreateDate = models.DateTimeField(verbose_name=_("CreateDate"), blank=True)
modificationtime = models.DateTimeField(verbose_name="modificationtime", null=True, blank=True, )
...
def __str__(self):
return self.ProductID
def get_absolute_url(self):
return reverse('productdetail', args=[str(self.id)])
urls.py has entry as shown below
path('editproduct/int:pk/edit/', EditProductView.as_view(), name='editproduct'),
views.py contains following code
class EditProductView(LoginRequiredMixin, UpdateView):
model = ProductStatus
template_name = 'editproduct.html'
form_class = EditProductStatusForm
login_url = 'login'
def form_valid(self, form):
editedproduct = form.save(commit=False)
editedproduct.modificationtime = timezone.now()
editedproduct.save()
# self.object = editedproduct
return super().form_valid(form)
Forms.py contains
class EditProductStatusForm(forms.ModelForm):
class Meta:
model = ProductStatus
editproduct.html looks as shown below
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<br>
<!-- show 4 links in bootstrap navigation bar -->
<nav class="navbar navbar-expand-lg navbar-light">
<div class="container-fluid ">
<div class="nav navbar-left">
<ul class="nav navbar-nav">
<li><a class="btn btn-info btn-sm" style="padding-left:0px;margin-left:10px" href="#" role="button">« First</a></li>
<li><a class="btn btn-info btn-sm" style="padding-left:0px;margin-left:10px" href="#" role="button">‹ Previous</a></li>
</ul>
</div>
<div class="nav navbar-right">
<ul class="nav navbar-nav">
<li> <a class="btn btn-info btn-sm" style="padding-left:0px;margin-left:10px" href="#" role="button">Next ›</a></li>
<li> <a class="btn btn-info btn-sm" style="padding-left:0px;margin-left:10px" href="#" role="button">Last »</a></li>
</ul>
</div>
</div>
</nav>
<h3 class="text-center">Change Product Status </h3>
<form class="form-inline" role="form">
<div class="row">
<div class="col">
<div class="input-group mb-3">
<span class="input-group-text" style="background-color: #ffffff" id="labelFor-Product ID">Product ID </span>
<input type="text" style="background-color: #ffffff" class="form-control" value="{{ object.ProductID }}" readonly>
</div>
</div>
</form>
<form method="post">
{% csrf_token %}
<div class="row">
<div class="col-6">
{{ form.Description| as_crispy_field }}
</div>
</div>
<br>
<button type="submit" class="btn btn-success">Save</button>
</form>
{% endblock content %}
editproduct url is invoked from other datatables using list page as . this page allows sorting by click on table header
I need to show pagination on editproduct page with 4 links/buttons First,Previous,Next and Last or datatables like pagination so that user dont have go back to product list page and then click on edit icon to open editproduct status page and user can go to first product, Previous product, next product or last product from edit product status page itself.
I am aware of datatables pagination that requires passing productstatus_list and using table but not sure how to use datatables pagination or django.core.paginator on this editproduct status page or on product details page that uses DetailView where only product id is passed and available as shown above. what change/update is needed in above code to show desired pagination on the edit productstatus page.
I’m really new in Django.
I’m trying to implement Modal dialog using forms. The problem is that even when I make some changes in my form, this changes are not shown in database… I have no idea why. When I test form outside Modal dialog, form is working…
Here is my form.py:
class anomalie_location_form(ModelForm):
class Meta:
model = Anomalie
fields = ['localization', ]
here is my view.py
#login_required(login_url='login')
def fix_anomalie_stock(request, pk, type_anomalie):
anomalie_pk = Anomalie.objects.get(id=pk)
# form to change anomalie position
form_location = anomalie_location_form(instance=anomalie_pk)
if request.method == 'POST':
print('printinng anomalie_location_form POST ', request.POST)
form_location = anomalie_location_form(
request.POST, instance=anomalie_pk)
if form_location.is_valid():
form_location.save()
return redirect('/')
context = {'anomalie_pk': anomalie_pk,
'form_location': form_location}
return render(request, "anomalie/fix_anomalie_stock.html", context)
and my html:
<div class="modal fade" id="myModal2" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h4>{{product.product_name }}</h4>
</div>
<form action="" method="POST">
{% csrf_token %}
<div class="modal-body">
{{form_location}}
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-primary" value="Treter" data-dismiss="modal">
</div>
</form>
</div>
</div>
</div>
this is the model.py
class Anomalie (models.Model):
ANOMALIE = (
("Etiquette absente", "Etiquette absente"),
("Etiquette decalee", "Etiquette decalee"),
("Etiquette inconnue", "Etiquette inconnue"),
)
ANOMALIE_STATE = (
("traité", "traité"),
("mise à jour", "mise à jour"),
("signalé", "signalé"),
)
type = models.CharField(
max_length=200, choices=ANOMALIE, null=False)
date_report = models.DateTimeField(null=False, blank=False)
localization = models.TextField(max_length=30, null=False, blank=False)
state = models.CharField(
max_length=200, choices=ANOMALIE_STATE, null=False)
aisle = models.ForeignKey(Aisle, null=True, on_delete=models.SET_NULL)
product = models.ForeignKey(
Product, null=True, on_delete=models.SET_NULL)
def datepublished(self):
return self.date_report.strftime('%B %d %Y')
def __str__(self):
return self.type
and this is the url.py
urlpatterns = [
path('admin/', admin.site.urls),
path('', home_screen_view, name="home"),
path('consult/<str:pk>/', consult_anomalie, name="consult_anomalie"),
path('fix_anomalie_stock/<str:pk>/<str:type_anomalie>',
fix_anomalie_stock, name="fix_anomalie_stock"),
]
So the question is why form is working outside of Dialog Modal ?
The mistake is simple.
That is, the form in the modal have a submit button. This button has the bootstrap modal data-dismiss attribute which makes the modal to dismiss and not the form to submit.
<input type="submit" class="btn btn-primary" value="Treter" data-dismiss="modal">
Remove the bootstrap data-dismiss attribute from submit button.
<input type="submit" class="btn btn-primary" value="Treter">
Code snippet in action
Run the code snippet to see it in action. I've added the modal code from the question. Form submit() to alert the form data and 'hidden.bs.modal' to alert when modal closes. For demo purpose, form has two submit buttons. One with the data-dismiss attribute and the other without. You can see that the button (2) alerts the data while the other closes the modal
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal2">
Launch modal
</button>
<div class="modal fade" id="myModal2" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h4>Product Name</h4>
</div>
<form action="" method="POST">
<div class="modal-body">
<input type="text" name="product" class="form-control">
(1) submit button with data-dismiss attribute<br>
(2) submit button without data-dismiss attribute
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-primary" value="(1) Treter" data-dismiss="modal"> | <input type="submit" class="btn btn-primary" value="(2) Treter">
</div>
</form>
</div>
</div>
</div>
<script>
$(document).ready(function() {
console.log('start');
$('form').submit(function() {
alert($(this).serialize());
})
$('#myModal2').on('hidden.bs.modal', function (e) {
alert('modal closes');
})
});
</script>
I'm missing some details but forms often don't submit properly when inputs are not named. Even your select elements need name and value pair parameters. Have you double checked this?
What can happen with bootstrap is that the modal can confuse the form action. You have it now set to = "". Try removing the action parameter and give your form a unique id.
if request.method == 'POST':
Also try checking if submit button was posted rather than just the request method.
Modal should be inside the form tag and not the other way around.
<form action="" method="POST">{% csrf_token %}
<div class="modal fade" id="myModal2" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h4>{{product.product_name }}</h4>
</div>
<div class="modal-body">
{{form_location}}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
</form>
I am learning Django 2.2 and using a little bit of Bootstrap 4 to help with the front end. I have a Model created which stores some user information like first name and last name. I have created a DeleteView class which is supposed to delete entries from the database using the ID. Everything works fine as is. But if I try to implement the DeleteView class using a Bootstrap modal window, nothing seems to happen even if I click the submit button. I am not sure what I am doing wrong. I read in another thread here in Stackoverflow that we need to include the button inside a form which I have done too. But it still doesn't delete the entry. Below is all the code required.
Note - I have placed the Delete button inside the contacts_view.html file. The contacts_delete.html file is exactly the same. My idea is to provide the user to not just view the details but also update or even delete the specific entry. When I click on the Delete button, the modal pop up window appears. But when I click on the 'Confirm' button, the entry does not get deleted as required.
Please let me know how to proceed with this.
contacts_view.html / contacts_delete.html
{% extends 'base.html' %}
{% block content %}
<div class="container" style="width: 500px">
<div>
<div class="list-group" style="color: black">
<a class="list-group-item list-group-item-action my-1" style="background-color: wheat">
<div class="row">
<div class="col-4">
First Name
</div>
<div class="col-8">
{{ object.first_name }}
</div>
</div>
</a>
<a class="list-group-item list-group-item-action my-1" style="background-color: wheat">
<div class="row">
<div class="col-4">
last Name
</div>
<div class="col-8">
{{ object.last_name }}
</div>
</div>
</a>
</div>
</div>
<div class="border-top text-center my-4 pt-3">
<a class="btn btn-outline-danger ml-2" href="{% url 'contacts-delete' object.id %}" type="submit" data-toggle="modal" data-target="#myModal">Delete</a>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content" style="background-color: whitesmoke; color: dimgray">
<div class="modal-header">
<h4 class="modal-title">Delete Contact</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body text-left">
form
<p>Do you really want to delete {{ object.first_name }} {{ object.last_name }}?</p>
</div>
<div class="modal-footer">
<form method="POST" action="{% url 'contacts-delete' object.id %}">
{% csrf_token %}
<button class="btn btn-outline-warning ml-2" type="submit">Update</button>
<button type="button" class="btn btn-outline-danger" href="{% url 'contacts-delete' object.id %}" data-dismiss="modal">Delete</button>
</form>
<a type="button" class="btn btn-outline-secondary" href="{% url 'contacts-view' object.id %}" data-dismiss="modal">Cancel</a>
</div>
</div>
</div>
</div>
</div>
</div>
{% endblock content %}
views.py
from .models import Contact
from django.urls import reverse_lazy
from django.shortcuts import reverse
from django.views.generic import DetailView, DeleteView
class ContactDetailView(DetailView):
model = Contact
template_name = 'contacts/contacts_view.html'
class ContactDeleteView(DeleteView):
model = Contact
template_name = 'contacts_update.html'
success_url = reverse_lazy('contacts-browse')
models.py
from django.db import models
from django.contrib.auth.models import User
class Contact(models.Model):
added_by = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
first_name = models.CharField(max_length=35)
last_name = models.CharField(max_length=35, blank=True, default='')
def __str__(self):
return f"{self.first_name} {self.last_name}"
urls.py
from django.urls import path
from .views import ContactDetailView, ContactDeleteView
urlpatterns = [
path('view/<int:pk>/', ContactDetailView.as_view(), name='contacts-view'),
path('view/<int:pk>/delete/', ContactDeleteView.as_view(), name='contacts-delete'),
]
Very, very quick question. I'm rendering my own custom forms within my html template...how would I go about submitting the hidden input when the user submits that form?
template.html
<form class="contact-form" name="contact-form" method="post" action=".">
{% csrf_token %}
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<label for="four">Your Text</label>
<textarea class="form-control" type="text" name="{{ comment_form.content.name }}" {% if comment_form.content.value %}value="{{ comment_form.content.value }}"{% endif %} placeholder="" required="required" id="four"></textarea>
</div>
</div>
</div>
<div class="form-group text-center">
<button type="submit" class="btn btn-primary pull-right">Submit Comment</button>
</div>
</form>
form.py
from django import forms
from .models import Comment
class CommentForm(forms.ModelForm):
content_type = forms.CharField(widget=forms.HiddenInput)
object_id = forms.IntegerField(widget=forms.HiddenInput)
#parent_id = forms.IntegerField(widget=forms.HiddenInput, required=False)
content = forms.CharField(widget=forms.Textarea)
class Meta:
model = Comment
fields = ('content',)
You can add this part to you forms.py file (in CommentForm class) :
hidden_field=forms.CharField(widget=forms.HiddenInput())
I hope it will work.let me know
I am strating to learn Django and I want to display some forms in bootstrap modal view.
I have a template with a HTML table, this table have a column with a drop down button with several options.
the table is rendered with django-tables2 and the forms are rendered with django-crispy-forms
My form definition for the modal form:
class RecepcionForm(forms.ModelForm):
fecha_recepcion = forms.DateField(widget=DateInput())
def __init__(self,*args,**kwargs):
super(RecepcionForm,self).__init__(*args,**kwargs)
self.helper = FormHelper(self)
self.helper.layout = Layout(
Field('id_proveedor',
'anio',
'mes',
'usuario',
readonly = True
),
Fieldset('',
'fecha_recepcion',
'num_archivos',
Submit('save','Grabar'),
HTML('<a class="btn btn-danger" href={% url "monitor" %}>Cancelar</a>')
)
)
class Meta:
model = DetalleRecepcion
My view for the modal form:
#login_required(login_url='/login/')
def RecepModalView(request):
idp = request.GET.get('i')
anio = request.GET.get('a')
mes = request.GET.get('m')
if request.method == 'POST':
r = DetalleRecepcion.objects.get(id_proveedor=idp,anio=anio,mes=mes)
form = RecepcionForm(request.POST, instance=r)
if form.is_valid():
form.save()
return HttpResponseRedirect('/monitor/')
else:
r = DetalleRecepcion.objects.get(id_proveedor=idp,anio=anio,mes=mes)
r.usuario = request.user
form = RecepcionForm(instance=r)
return render_to_response('recepmodal.html',
{'form':form},
context_instance=RequestContext(request))
My template for the modal form
{% load crispy_forms_tags %}
<div class="modal fade" id="recmodal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Register </h4>
</div>
<div class="modal-body">
<form action="" method=post">
<div class="tab-content">
<div class="tab-pane active" id="tab1">
{% crispy form %}
</div>
</form>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary">Submit</button>
</div>
</div>
</div>
</div>
I don't know how to open and pass arguments to the modal form.
I try using the django tag include
Example snippet:
<body>
<table>
.
.
.
</table>
{% include 'recmodal.html' %}
</body>
but I get this error
Exception Value: Failed lookup for key [form] in
In simple word how can I pass values and open a bootstrap modal form in django using django-crispy-forms.
Any advice
Thansk in advance
I know it's too late to answer, but I render my forms in a modal using this into a "modal-body" tag:
<form method="post">
{% csrf_token %}
{% form.as_p %}
</form>
I hope this work for all people like me that we came here finding an answer.
Regards.