I'm using a Django form to load an image and I'm using Bootstap-fileinput.
When the form has already been initialised with an image I want the image displayed immediately but it simple shows no image currently. How do I get the template to automatically show the file-input-exists version of the Bootstap HTML rather than the file-input-new version?
Forms.py :
class MyModelForm(forms.ModelForm):
class Meta:
model = MyModel
fields = ['image',]
widget = {
'image' : forms.FileInput(attrs={'class': 'form-control',
'id' : 'input-file'}),
}
My template has:
{{form.image}}
{{form.image.errors}}
This generates the following HTML whether the form contains an image or not
<div class="file-input file-input-new"><div class="file-preview ">
<div class="close fileinput-remove">×</div>
<div class="">
<div class="file-preview-thumbnails"></div>
<div class="clearfix"></div>
<div class="file-preview-status text-center text-success"></div>
<div class="kv-fileinput-error file-error-message" style="display: none;"></div>
</div>
</div>
<div class="kv-upload-progress hide"></div>
<div class="input-group ">
<div tabindex="500" class="form-control file-caption kv-fileinput-caption">
<div class="file-caption-name"></div>
</div>
<div class="input-group-btn">
<button type="button" tabindex="500" title="Clear selected files" class="btn btn-default fileinput-remove fileinput-remove-button"><i class="glyphicon glyphicon-trash"></i> Remove</button>
<button type="button" tabindex="500" title="Abort ongoing upload" class="btn btn-default hide fileinput-cancel fileinput-cancel-button"><i class="glyphicon glyphicon-ban-circle"></i> Cancel</button>
<div tabindex="500" class="btn btn-primary btn-file"><i class="glyphicon glyphicon-folder-open"></i> Browse …<input class="form-control" id="input-file" name="image" type="file" required=""></div>
</div>
</div>
** EDIT **
Thanks to help so far I now have the images showing, but if I try and resubmit the form I get a message that no file has been chosen. I need to pick this up as well.
I've added this JavaScript in order to display the image on loading.
<script>
$("#input-file").fileinput({
showUpload: false,
initialPreviewShowDelete: false,
{% if form.instance.image %}
initialPreview: [
"<img src='{{ form.instance.image.url }}' class='file-preview-frame'>",
],
initialPreviewConfig: [
{caption: "{{ form.instance.image.name}}",},
],
{% endif %}
});
</script>
I am getting the preview of saved database file by using this script
<script>
$(document).ready(function(){
$("#id_album_logo").fileinput({
showUpload: false,
showCaption: false,
browseClass: "btn btn-primary btn-lg",
fileType: "any",
previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",
overwriteInitial: false,
initialPreviewAsData: true,
{% if form.instance.album_logo %}
initialPreview: [
"{{ form.instance.album_logo.url }}",
],
initialPreviewConfig: [
{caption: "{{ form.instance.album_logo.name}}", width: "120px", url: "{$url}", key: 1},
],
{% endif %}
});
})
where id_album_logo is the id assigned to form input ,
initialPreview: [
"{{ form.instance.album_logo.url }}",
],
is the url of the image already saved in database
my models.py
class Album(models.Model):
user = models.ForeignKey(User)
album_logo=models.FileField(upload_to=upload_location)
my forms.html is
<div class="container-fluid">
<div class="row">
<div class="col-sm-6 col-md-6 col-lg-6 col-sm-offset-3 col-md-offset-3 col-lg-offset-3">
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{% include 'form-template.html' %}
<div class="form-group">
<br>
<button type="submit" class="btn btn-success">Submit</button>
</div>
</form>
</div>
</div>
and form-template.html is
{% for field in form %}
<div class="form-group djfr">
<label class="control-label">{{ field.label_tag }}</label>
{{ field }}
<span class="text-danger small">{{ field.errors }}</span>
</div>
{% endfor %}
Related
I'm currently building a website that makes use of django-allauth and I've come across a problem regarding error messages while using a custom User model.
My custom User model is called CustomUser, I've noticed that when django-allauth handles errors regarding the username, it uses the name of the user model as the starting word to the error message's sentence. Example image is linked below.
Image of the error message
How can I change this error message? I'd like to stay away from overriding any django-allauth views if possible, though I'd be happy with any solution!
This is my Django form code that makes use of django-crispy-forms:
<form class="signup" id="signup_form" method="post" action="{% url 'account_signup' %}">
{% csrf_token %}
<div class="row">
<div class="col-12 col-lg-7">
{{ form.email|attr:"autofocus"|as_crispy_field }}
</div>
<div class="col-12 col-lg-5">
{{ form.username|as_crispy_field }}
</div>
<div class="col-6 col-lg-4">
{{ form.first_name|as_crispy_field }}
</div>
<div class="col-6 col-lg-4">
{{ form.last_name|as_crispy_field }}
</div>
<div class="col-12 col-lg-4">
{{ form.birthday|as_crispy_field }}
</div>
<div class="col-12 col-sm-6">
{{ form.password1|as_crispy_field }}
</div>
<div class="col-12 col-sm-6">
{{ form.password2|as_crispy_field }}
</div>
<div class="col-12 text-center">
{{ form.captcha|as_crispy_field }}
{% for error in form.captcha.errors %}
{% if error %}
<style>
#div_id_captcha {
margin-bottom: 0px !important;
}
</style>
<span class="invalid-feedback d-block mb-3">
<strong>
You must complete the captcha to register
</strong>
</span>
{% endif %}
{% endfor %}
</div>
</div>
{% if redirect_field_value %}
<input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" />
{% endif %}
<button type="submit" class="btn btn-primary btn-light mb-3">Register <i class="fa fa-user-plus fa-fw"></i></button>
<p>Already have an account?<br /><small>Login here</small></p>
</form>
I have two different forms of a model in a template
I change the user's photo with one form and edit the user's text profile with another form
The model (profile) is a one-to-one relationship with the main Django user
But I have a problem with the user photo change form
When clicking on the user profile edit form which is the profile model (for text changes)
The photo change form is also called and is always valid
My forms are from the Django form model
Definitely the main problem is the image change form, but I do not know which part of the code has a problem. I send the values to the server with Ajax.
Below I will display the codes and output to convey the concept easier
If you do not understand my problem, I can explain more to you, just give me your email address so that I can contact you. Thank you.
Output
View
def edit_user_view(request, pk):
user = get_object_or_404(User, pk=pk)
c_default_user_edit_form = default_user_edit_form(
request.POST or None,
initial=vars(user),
instance=user
)
c_user_image_editing_form = user_image_editing_form(
request.POST or None,
request.FILES or None,
instance=user.profile
)
c_user_information_editing_form = user_information_editing_form(
request.POST or None,
initial=vars(user.profile),
instance=user.profile,
)
if c_default_user_edit_form.is_valid():
print("default user")
c_default_user_edit_form.save()
return JsonResponse({'s': 's'})
if c_user_information_editing_form.is_valid():
c_user_information_editing_form.save()
if c_user_image_editing_form.is_valid():
print("image user")
user.profile.save()
return JsonResponse({'src': user.profile.user_profile.url})
context = {
'default_user_edit_form': c_default_user_edit_form,
'user_image_editing_form': c_user_image_editing_form,
'user_information_editing_form': c_user_information_editing_form,
'editing_user': user,
}
return render(request, 'AdminPanel/Users/user-edit.html', context)
Model
class Profile(models.Model):
gender_selection_choices = [
('MS', 'زن'),
('MR', 'مرد'),
('TG', 'دیگر'),
]
user = models.OneToOneField(
User,
on_delete=models.CASCADE
)
user_profile = models.ImageField(
verbose_name="پروفایل",
upload_to=RenameUserPhoto,
validators=[ImageSizaValidators],
default='images/User/UserProfile/icon-avatar-default.png',
blank=True
)
gender_selection = models.CharField(
verbose_name='انتخاب جنسیت',
max_length=2,
blank=True,
default="NS",
choices=gender_selection_choices,
)
postal_code = models.CharField(
verbose_name='کد پستی',
max_length=20,
validators=[postal_code_validator],
blank=True,
help_text='کد پستی 10 رقمی میتواند شامل خط تیره (-) یا نباشد',
)
phone_number = models.CharField(
max_length=11,
verbose_name='شماره تماس',
help_text='شماره تماس باید 11 رقمی باشد و میتواند شامل صفر در ابتدای شماره نباشد',
blank=True,
validators=[phone_number_validator],
)
location_first = models.CharField(
max_length=250,
blank=True,
verbose_name="آدرس (1)"
)
NumberOfEmailsSentActivationLink = models.IntegerField(
blank=True,
default=0,
verbose_name="تعداد ایمیل ارسالی فعالسازی حساب کاربری"
)
NumberOfEmailsSentToTheUser = models.IntegerField(
blank=True,
default=0,
verbose_name="تعداد ایمیل های ارسال شده برای کاربر"
)
objects = CustomModelManagerProfile()
def get_absolute_url(self):
return reverse_lazy('AdminSite__Ak:edit_user_view', kwargs={
'pk': self.user.pk
})
Form
class user_information_editing_form(forms.ModelForm):
class Meta:
model = Profile
fields = (
'phone_number',
'postal_code',
'location_first',
'gender_selection',
)
widgets = {
'phone_number': forms.NumberInput(
attrs={
'class': 'form-control',
'placeholder': 'تلفن همراه را وارد نمایید...',
}),
'postal_code': forms.TextInput(attrs={
'class': 'form-control',
'placeholder': 'کد پستی را وارد نمایید...'
}),
'location_first': forms.Textarea(attrs={
'rows': 1,
'style': 'resize:none;height:2.7125rem',
'class': 'form-control',
'placeholder': 'آدرس خود را وارد نمایید...'
}),
'gender_selection': forms.Select(attrs={
'class': 'form-control'
})
}
class user_image_editing_form(forms.ModelForm):
class Meta:
model = Profile
fields = ('user_profile',)
widgets = {
'user_profile': forms.FileInput()
}
Ajax
// Change User Photo
$('button.user-photo-change-btn').click(function () {
const image_input = $('input[name="user_profile"]').click()
let formData = new FormData();
image_input.change(function () {
let formData = new FormData();
formData.append('user_profile', $('form#form-change-photo input[name="user_profile"]').prop('files')[0])
formData.append('csrfmiddlewaretoken', $('form#form-change-photo input[name="csrfmiddlewaretoken"]').val())
jQuery.ajax({
url: location.href,
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function (Data) {
$('img.users-avatar-shadow').attr('src', Data.src)
}
});
})
})
//Account change information form
$('form#account_change_information_form button[type="button"]').click(function () {
$.ajax({
url: location.href,
data: $('form#account_change_information_form').serialize(),
type: 'POST',
cache:false,
success: function () {
}
})
})
Html
{% extends 'AdminPanel/__Main__/base.html' %}
{% load static %}
<!--Title-->
{% block title_edit_user %}
ویرایش کاربر
{% endblock %}
<!-- BEGIN: Vendor CSS-->
{% block vendor_css_edit_user %}
<link rel="stylesheet" type="text/css"
href="{% static 'AdminPanel/app-assets/css-rtl/plugins/forms/validation/form-validation.css' %}">
<link rel="stylesheet" type="text/css"
href="{% static 'AdminPanel/app-assets/vendors/css/forms/select/select2.min.css' %}">
<link rel="stylesheet" type="text/css"
href="{% static 'AdminPanel/app-assets/vendors/css/pickers/pickadate/pickadate.css' %}">
{% endblock %}
<!-- END: Vendor CSS-->
<!-- BEGIN: Page CSS-->
{% block page_css_edit_user %}
<link rel="stylesheet" type="text/css" href="{% static 'AdminPanel/app-assets/css-rtl/pages/app-user.min.css' %}">
{% endblock %}
<!-- END: Page CSS-->
<!-- BEGIN: Content-->
{% block edit_user %}
<div class="app-content content">
<div class="content-overlay"></div>
<div class="header-navbar-shadow"></div>
<div class="content-wrapper">
<div class="content-header row">
</div>
<div class="content-body"><!-- users edit start -->
<section class="users-edit">
<div class="card">
<div class="card-content">
<div class="card-body">
<ul class="nav nav-tabs mb-3" role="tablist">
<li class="nav-item">
<a class="nav-link d-flex align-items-center active" id="account-tab"
data-toggle="tab" href="#account"
aria-controls="account" role="tab" aria-selected="true">
<i class="feather icon-user mr-25"></i><span
class="d-none d-sm-block">حساب</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link d-flex align-items-center" id="information-tab"
data-toggle="tab" href="#information"
aria-controls="information" role="tab" aria-selected="false">
<i class="feather icon-info mr-25"></i><span class="d-none d-sm-block">اطلاعات</span>
</a>
</li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="account" aria-labelledby="account-tab"
role="tabpanel">
<!-- users edit media object start -->
<div class="media mb-2">
<a class="mr-2 my-25" href="#">
<img src="{{ editing_user.profile.user_profile.url }}" alt="users avatar"
class="users-avatar-shadow rounded" height="90" width="90">
</a>
<div class="media-body mt-50">
<h4 class="media-heading">{{ user.get_full_name }}</h4>
<div class="col-12 d-flex mt-1 px-0">
<form action="" method="post" id="form-change-photo"
class="form-inline" enctype="multipart/form-data">
{% csrf_token %}
{{ user_image_editing_form.user_profile }}
<button type="button"
class="btn btn-primary d-none d-sm-block mr-75 user-photo-change-btn">
تغییر دادن
</button>
<button type="button"
class="btn btn-outline-danger d-none d-sm-block user-photo-delete-btn">
پاک کردن
</button>
</form>
</div>
</div>
</div>
<!-- users edit media object ends -->
<!-- users edit account form start -->
<form novalidate method="post" id="form_default_user">
{% csrf_token %}
<div class="row">
<div class="col-12 col-sm-6">
<div class="form-group">
<div class="controls">
<label>پست الکترونیک</label>
{{ default_user_edit_form.username }}
</div>
</div>
<div class="form-group">
<div class="controls">
<label>نام</label>
{{ default_user_edit_form.first_name }}
</div>
</div>
<div class="form-group">
<div class="controls">
<label>نام خانوادگی</label>
{{ default_user_edit_form.last_name }}
</div>
</div>
</div>
{# User Permission #}
<div class="col-12 mt-2">
<div class="table-responsive border rounded px-1 ">
<h6 class="border-bottom py-1 mx-1 mb-0 font-medium-2"><i
class="feather icon-lock mr-50 "></i>وضعیت حساب کاربری
</h6>
<table class="table table-borderless">
<thead>
<tr>
<th>دسترسی های کاربر</th>
<th>فعال / غیرفعال</th>
<th>کاربر ویژه</th>
<th>کارمند</th>
</tr>
</thead>
<tbody>
<tr>
<td>کاربران</td>
<td>
<div class="custom-control custom-checkbox">
{{ default_user_edit_form.is_active }}
<label class="custom-control-label"
for="user-active"></label>
</div>
</td>
<td>
<div class="custom-control custom-checkbox">
{{ default_user_edit_form.is_superuser }}
<label class="custom-control-label"
for="user-superuser"></label>
</div>
</td>
<td>
<div class="custom-control custom-checkbox">
{{ default_user_edit_form.is_staff }}
<label class="custom-control-label"
for="user-personnel"></label>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="col-12 d-flex flex-sm-row flex-column justify-content-end mt-1">
<button type="button"
class="btn btn-primary glow mb-1 mb-sm-0 mr-0 mr-sm-1"
id="btn-apply-default-user-changes">
ذخیره تغییرات
</button>
<button type="reset" class="btn btn-outline-warning">تنظیم مجدد
</button>
</div>
</div>
</form>
<!-- users edit account form ends -->
</div>
<div class="tab-pane" id="information" aria-labelledby="information-tab"
role="tabpanel">
<!-- users edit Info form start -->
<form method="post" novalidate id="account_change_information_form">
{% csrf_token %}
<div class="row mt-1">
<div class="col-12 col-sm-6">
<h5 class="mb-1"><i class="feather icon-user mr-25"></i>اطلاعات شخصی
</h5>
<div class="form-group">
<div class="controls">
<label for="">تلفن همراه</label>
{{ user_information_editing_form.phone_number }}
</div>
</div>
<div class="form-group">
<label>انتخاب جنسیت</label>
{{ user_information_editing_form.gender_selection }}
</div>
</div>
<div class="col-12 col-sm-6">
<h5 class="mb-1 mt-2 mt-sm-0"><i
class="feather icon-map-pin mr-25"></i>نشانی</h5>
<div class="form-group">
<div class="controls">
<label>آدرس</label>
{{ user_information_editing_form.location_first }}
</div>
</div>
<div class="form-group">
<div class="controls">
<label>کد پستی</label>
{{ user_information_editing_form.postal_code }}
</div>
</div>
</div>
<div class="col-12 d-flex flex-sm-row flex-column justify-content-end mt-1">
<button type="button"
class="btn btn-primary glow mb-1 mb-sm-0 mr-0 mr-sm-1"
id="Test">
ذخیره تغییرات
</button>
<button type="reset" class="btn btn-outline-warning">تنظیم مجدد
</button>
</div>
</div>
</form>
<!-- users edit Info form ends -->
</div>
</div>
</div>
</div>
</div>
</section>
<!-- users edit ends -->
</div>
</div>
</div>
{% endblock %}
<!-- END: Content-->
<!-- BEGIN: Page Vendor JS-->
{% block page_vendor_js_edit_user %}
<script src="{% static 'AdminPanel/app-assets/vendors/js/forms/select/select2.full.min.js' %}"></script>
<script src="{% static 'AdminPanel/app-assets/vendors/js/forms/validation/jqBootstrapValidation.js' %}"></script>
<script src="{% static 'AdminPanel/app-assets/vendors/js/pickers/pickadate/picker.js' %}"></script>
<script src="{% static 'AdminPanel/app-assets/vendors/js/pickers/pickadate/picker.date.js' %}"></script>
{% endblock %}
<!-- END: Page Vendor JS-->
<!-- BEGIN: Page JS-->
{% block page_js_edit_user %}
<script src="{% static 'AdminPanel/app-assets/js/scripts/pages/app-user.min.js' %}"></script>
<script src="{% static 'AdminPanel/app-assets/js/scripts/navs/navs.min.js' %}"></script>
{% endblock %}
<!-- END: Page JS-->
there is some approaches to your question, first I suggest ModelFormSet. you could add a modelformset to another form so reduce the confliction. another way is have only one submit button for all forms in the same page. or control the submission of each form using JS, there is a submit() function available and it could be mixed with serialize() function too. e.g:
$("#form1_sub_btn").on('click', function(e){
e.preventDefault();
$.ajax({
url: url,
type: 'GET',
data: form1.serialize
success: function (res) {
console.log(res);
},
});
I have a class based Update view "ManifestUpdate", which is a modal pop up, and is launched from within another function based view "Manifest". I need to be able to take the field = 'reference' from my ManifestUpdate view and make it available to the "Manifest" view as 'Reference_Nos'. As you can see ManifestUpdate should direct the user to Manifest, but it does not, just nothing happens (it works if I change this to direct to any other view). I believe this is because I am not passing that parameter. Can anyone tell me how to capture that 'reference' parameter within ManifestUpdate and pass it to Manifest from the class based view?
views.py
class ManifestUpdate(BSModalUpdateView):
model = Manifests
template_name = 'manifest_update.html'
form_class = UpdateManifestForm
success_message = 'Success: Manifest was updated.'
success_url = reverse_lazy('manifest')
def manifest(request):
form = CreateManifestForm(request.POST)
if request.method == "POST":
if form.is_valid():
form.save()
reference_id = form.cleaned_data.get('reference')
data = Manifests.objects.all().filter(reference__reference=reference_id)
form = CreateManifestForm(initial={
'reference': Orders.objects.get(reference=reference_id),
})
total_cases = Manifests.objects.filter(reference__reference=reference_id).aggregate(Sum('cases'))
context = {
'reference_id': reference_id,
'form': form,
'data': data,
'total_cases': total_cases['cases__sum'],
}
return render(request, 'manifest_readonly.html', context)
else:
reference_id = request.POST.get('Reference_Nos')
data = Manifests.objects.all().filter(reference__reference=reference_id)
form = CreateManifestForm(initial={
'reference': Orders.objects.get(reference=reference_id),
})
total_cases = Manifests.objects.filter(reference__reference=reference_id).aggregate(Sum('cases'))
context = {
'reference_id': reference_id,
'form': form,
'data': data,
'total_cases': total_cases['cases__sum'],
}
return render(request, 'manifest_readonly.html', context)
forms.py
class UpdateManifestForm(BSModalForm):
class Meta:
model = Manifests
fields = ('reference', 'cases', 'product_name', 'count', 'CNF', 'FOB')
update_manifest.html
#showing the modal window body
<form method="post" action="">
{% csrf_token %}
<div class="modal-header">
<h3 class="modal-title">Update Manifest</h3>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="{% if form.non_field_errors %}invalid{% endif %} mb-2">
{% for error in form.non_field_errors %}
{{ error }}
{% endfor %}
</div>
<div class="container">
<form id="create_mani_form" method="POST">
<br>
{% csrf_token %}
<div class="column">
<label for="form.reference" class="formlabels">Reference ID: </label><br>
<!-- <input type="text" value="{{ reference_id }}">-->
{{ form.reference }}
<br>
<br>
<label for="form.count" class="formlabels">CNF: </label>
<br>
{{ form.CNF }}
<br>
</div>
<div class="description">
<div class="column">
<label for="form.product_name" class="formlabels">Description: </label>
<br>
{{ form.product_name}}
<br><br>
<label for="form.count" class="formlabels">FOB: </label>
<br>
{{ form.FOB }}
<br>
</div>
</div>
<div class="column">
<label for="form.cases" class="formlabels">Cases: </label>
<br>
{{ form.cases }}
<br>
</div>
<div class="column">
<label for="form.count" class="formlabels">Count: </label>
<br>
{{ form.count }}
<br>
</div>
</div>
<div class="modal-footer">
<button type="button" class="submit-btn btn btn-primary">Update</button>
</div>
</form>
manifest_readonly.html
#showing the html rendered by the manifest view
{% extends 'base.html' %}
{% load humanize %}
{% block body %}
{% load staticfiles %}
<div class="container">
<div class="col-xs-12">
{% if messages %}
{% for message in messages %}
<div class="alert alert-success" role="alert">
<center>{{ message }}</center>
</div>
{% endfor %}
{% endif %}
</div>
</div>
<div class="container">
<form id="create_mani_form" method="POST">
<br>
<br>
<br>
{% csrf_token %}
<div class="column">
<label for="form.reference" class="formlabels">Reference ID: </label><br>
<!-- <input type="text" value="{{ reference_id }}">-->
{{ form.reference }}
<br>
<br>
<label for="form.count" class="formlabels">CNF: </label>
<br>
{{ form.CNF }}
<br>
</div>
<div class="description">
<div class="column">
<label for="form.description" class="formlabels">Description: </label>
<br>
{{ form.product_name}}
<br><br>
<label for="form.count" class="formlabels">FOB: </label>
<br>
{{ form.FOB }}
<br>
</div>
</div>
<div class="column">
<label for="form.cases" class="formlabels">Cases: </label>
<br>
{{ form.cases }}
<br>
</div>
<div class="column">
<label for="form.count" class="formlabels">Count: </label>
<br>
{{ form.count }}
<br>
<label for="form.reference" class="formlabels">Case Total: </label><br>
<input type="text" value="{{ total_cases|intcomma }}" readonly>
<br>
<label for="form.reference" class="formlabels">Total CNF: </label><br>
<input type="text" value="{{ totalCNF|intcomma }}" readonly>
<br>
<label for="form.reference" class="formlabels">Total FOB: </label><br>
<input type="text" value="{{ totalFOB|intcomma }}" readonly>
</div>
<br>
<br>
<button type="submit" name="add_mani" style="border-color: #7395AE;">Add Line</button>
</form>
<br>
<h4>Manifest</h4>
<div class="table-responsive">
<!--<table id="manifest_table" class="table table-striped table-bordered table-sm " cellspacing="0"-->
<table class="table table-striped table-bordered manifest_table" cellspacing="0" style="width="100%">
<thead>
<tr>
<th style="width:2%;"</th>
<th style="width:10%;">Cases</th>
<th style="width:60%;">Description</th>
<th style="width:10%;">Count</th>
<th style="width:10%">FOB</th>
<th style="width:10%">CNF</th>
</tr>
</thead>
<tbody>
{% for manifests in data %}
<tr>
<td>
<!-- Update book buttons -->
<button type="button" class="update-manifest btn btn-sm btn-primary" style="color: #FFCF8B; border-color: #FFCF8B; background-color: #FFF;" data-id="{% url 'manifest_update' manifests.pk %}">
<span class="fa fa-pencil"></span>
</button>
</td>
<td>{{ manifests.cases }}</td>
<td>{{ manifests.product_name}}</td>
<td>{{ manifests.count}}</td>
<td>{{ manifests.FOB}}</td>
<td>{{ manifests.CNF}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<div class="text-center">
Subit Manifest
</div>
<div class="modal fade" tabindex="-1" role="dialog" id="modal">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content"></div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js"></script>
<script src="jquery.min.js"></script>
<script src="jquery.fulltable.js"></script>
<script src="script.js"></script>
<script src="{% static 'js/jquery.bootstrap.modal.forms.js' %}"></script>
<script>
$(function () {
$(".update-manifest").each(function () {
$(this).modalForm({formURL: $(this).data('id')});
});
});
</script>
{% endblock %}
jquery.bootstrap.modal.forms.js
(function ($) {
// Place the form at formURL to modalContent element of modal with id=modalID
var newForm = function (modalID, modalContent, modalForm, formURL, successURL, errorClass) {
$(modalContent).load(formURL, function () {
$(modalID).modal('toggle');
ajaxSubmit(modalID, modalContent, modalForm, successURL, errorClass);
});
};
// Add AJAX validation to the modalForm
var ajaxSubmit = function (modalID, modalContent, modalForm, successURL, errorClass) {
$(modalForm).submit(function (event) {
// Prevent submit and POST form to url using AJAX
event.preventDefault();
$.ajax({
type: $(this).attr("method"),
url: $(this).attr("action"),
// Serialize form data
data: $(this).serialize(),
success: function (response) {
// Update form with errors after unsuccessful POST request
// Django form.is_valid() = False
if ($(response).find(errorClass).length > 0) {
$(modalID).find(modalContent).html(response);
ajaxSubmit(modalID, modalContent, modalForm, successURL, errorClass);
}
// Hide modal after successful POST request when & redirect to successURL
else {
$(modalID).modal("hide");
window.location.href = successURL;
}
}
});
});
};
$.fn.modalForm = function (options) {
// Default settings
var defaults = {
modalID: "#modal",
modalContent: ".modal-content",
modalForm: ".modal-content form",
formURL: null,
successURL: "/",
errorClass: ".invalid"
};
// Extend default settings with provided options
var settings = $.extend(defaults, options);
return this.each(function () {
$(this).click(function (event) {
newForm(settings.modalID,
settings.modalContent,
settings.modalForm,
settings.formURL,
settings.successURL,
settings.errorClass);
event.preventDefault();
});
});
};
}(jQuery));
I've a register form and a function to post the values to django via ajax, but for some reasons, the post request says 403 forbidden but the get request does the job.
I want to use post request in this functionality but it doesn't seem to work, tried putting {% csrf_form %} too within the template, but still it says 403 Forbidden. Any sugestion?
Views.py
from django.http import HttpResponse
from django.shortcuts import render
from django.views import View
class signUp(View):
def post(self, request):
return HttpResponse(" POST method successfull !!")
Urls.py
path('insert/', views.signUp.as_view()),
HTML Form:
{% extends 'base.html' %}
{% block title %}
<title> Register </title>
{% endblock %}
{% block content %}
<div class="row breadcrumb_nav">
<div class="col-md-1" ></div>
<div class="col-md-10" style="margin-bottom: 35px;">
<!-- START col-md-12 Section -->
<ol class="breadcrumb nm" >
<li> Home </li>
<li class="active"> Register </li>
</ol>
<div id="quickViewPage_error_container">
<div id="animated_image"></div>
<div id="results_container"></div>
</div>
</div>
<!--end of col-md-12 -->
<div class="col-md-1" ></div>
</div> <!-- end of row -->
<!--start of row -->
<div class="row">
<div class="col-md-1" ></div>
<div class="col-md-12"> <!-- START Right Section -->
<div class="main_shadow panel panel-default"> <!-- START OF panel panel-default-->
<div class="panel-body panel-body-padding"> <!-- -START OF PANE -->
<div class="modal-header">
<h4 class="modal-title" id="exampleModalLabel"> Register </h4>
</div>
<div class="modal-body">
<div class="panel-body"> <!-- -START OF PANE -->
<form id="signup_form" name="signup_form" method="post">
{% csrf_token %}
<div class="form-group">
<div class="row">
<div class="col-sm-6">
<label class="control-label"> eMail <span class="text-danger">*</span></label>
<input name="email" type="text" class="form-control" autocomplete="off" required>
</div>
<div class="col-sm-6">
<label class="control-label">Password <span class="text-danger">*</span></label>
<input name="password" type="password" class="form-control" autocomplete="off" data-parsley-trigger="change" required>
</div>
</div>
</div>
<input type="hidden" name="register_new_user" id="register_new_user" value="register_new_user">
<input type="submit" name="register_btn" id="register_btn" class="btn btn-primary" value="Register" style="float:left;padding-left:25px;padding-right:25px;margin-right: 25px;">
<a href="/register">
<input type="button" class="btn btn-primary" value="Register Now" style="float:left;padding-left:25px;padding-right:25px;">
</a>
</form> <!--end of Login_Management -->
</div> <!-- END OF panel-body -->
</div>
</div> <!-- END OF panel-body -->
</div> <!--/ End of Form layout -->
</div> <!-- END OF Right Section -->
<div class="col-md-1" ></div>
</div>
<!-- end of row -->
enter code here
{% endblock %}
{% block javascript %}
<script>
$('#register_btn').click(function(e) {
e.preventDefault();
$.post('/insert/', '®ister_new_user=register_new_user' +
'&csrftoken={{ csrf_token }}' , function(response) {
$('#results_container').html(response);
});
});
</script>
{% endblock %}
You are sending the data in the path like this:
$.post('/insert/', '®ister_new_user=register_new_user' +
'&csrftoken={{ csrf_token }}' , function(response) {
$('#results_container').html(response);
});
Try sending the data in the body:
$.post( '/insert/', { register_new_user: "register_new_user", csrftoken: "your_token_here" } );
I have redefined form for contact us page, It's standard django-form stuff, but I'm struggling to understand how can I write description inside <inpout> field.
To be precise I want to write Name inside <input> field, so how can I do this. I define <input> field like {{ form.name }}, so how can I define it more like <input type="name" class="form-control" id="id_name" placeholder="Your Name">.
<div class="col-xs-12 col-sm-12 col-md-4 col-md-offset-2 col-lg-4">
{% if form.errors %}
<p style="color: red">
Please correct the error{{ form.errors|pluralize }} below.
</p>
{% endif %}
<form class="form-horizontal" action="." method="POST">
{% csrf_token %}
<div class="field form-group">
{{ form.name.errors }}
<label for="id_name" class="control-label"></label>
<div class="col-sm-10">
{{form.name}}
</div>
</div>
<div class="field form-group">
{{ form.email.errors }}
<label for="id_email" class="control-label"></label>
<div class="col-sm-10">
{{ form.email }}
</div>
</div>
<div class="field form-group">
{{ form.phone_number.errors }}
<label for="id_phone_number" class="control-label"></label>
<div class="col-sm-10">
{{ form.phone_number }}
</div>
</div>
<div class="field form-group">
{{ form.message.errors }}
<label for="id_message" class="control-label"></label>
<div class="col-sm-10">
{{ form.message }}
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="submit" class="btn btn-primary btn-block" value="Submit"></button>
</div>
</div>
</form>
</div><!--/end form colon -->
If you want to modify the placeholder text, or other values of the field Django creates, it can be done in the form code using the widget's attrs:
class MyForm(forms.Form):
name = forms.CharField(
widget=forms.TextInput(
attrs={
'class': 'my-class',
'placeholder': 'Name goes here',
}))
If your intention is to keep all of the code in the template you will have to manually create each input field instead of using the ones Django renders. You can still access the values of the generated field in the template to help you do that though.
<input name="{{ form.name.name }}" type="text" placeholder="Name field">