how to customize the image filed returned by UpdateView - django

i use the UpdateView to update the products informations in my future webstore
in my temblate .
when i open my template i find a that it renders me the image link
edit_product.html
<form method="post">
<div class="form-group">
<label>Name</label>
{{form.name}}
</div>
<div class="form-group">
<label>Description</label>
{{form.description}}
</div>
<div class="form-group">
<label>Price</label>
{{form.nominal_price}}
</div>
<div class="form-group">
<label>Image</label>
<img src="{{form.instance.photo.url}}" width="200"/>
</div>
<div class="form-group">
{{form.photo}}
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
output
<form method="post">
<div class="form-group">
<label>Name</label>
<input type="text" name="name" value="flawless legs" maxlength="255" required="" id="id_name">
</div>
<div class="form-group">
<label>Description</label>
<textarea name="description" cols="40" rows="10" required="" id="id_description">Epilateur de jambes pour femmes</textarea>
</div>
<div class="form-group">
<label>Price</label>
<input type="number" name="nominal_price" value="199" min="0" required="" id="id_nominal_price">
</div>
<div class="form-group">
<label>Image</label>
<img src="/media/products/images/449165_ALTMORE2.jpeg" width="200">
</div>
<div class="form-group">
Currently: products/images/449165_ALTMORE2.jpeg<br>
Change:
<input type="file" name="photo" accept="image/*" id="id_photo">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
what should i do to remove this Currently: products/images/449165_ALTMORE2.jpeg<br>

I found a tricky solution :
i replaced the
<div class="form-group">
{{form.photo}}
</div>
in my html file by an input type file <input type="file" name="photo" accept="image/*" id="id_photo"> and i edited my views
views.py
class ProductUpdateView(RedirectToPreviousMixin, UpdateView):
model = Product
form_class = ProductUpdateForm
template_name = 'admin/product_update.html'
def get_object(self):
return Product.objects.get(name=self.kwargs['product_name'])
def form_valid(self, form):
form = form.save(commit=False)
self.photo = form.photo
form.save()
return HttpResponseRedirect(self.get_success_url())

Related

how to creater a signup register form with my own reqired field form in django?

Im new to django i want create signup form with my own feild ,i dont want to signup form in default that is in user table i want to created own custom sign up forn any can hepl plz
Im new to django i want create signup form with my own feild ,i dont want to signup form in default that is in user table i want to created own custom sign up forn any can hepl plz
here is my example how my form feild look like
[enter link description here][1]
<form id="contact-form" method="post" action="/addyourschool/" role="form">
<input type="hidden" name="csrfmiddlewaretoken" value="vhcAZ5w1HpK2mUXMhdqHR1to9Yv2LeOB85E2kR7Z1ZsPo5fjtWZ5P7o23kj8lDsk">
<div class="messages"></div>
<div class="controls">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="form_name">School Name</label>
<input type="text" name="schoolname" id="product" class="form-control ui-autocomplete-input" placeholder="Type few letter & select from down *" required="required" data-error="Lastname is required." autocomplete="off">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="form_cfschp">Can't find your School *</label>
<input id="form_cfschp" type="text" name="form_cfschpool" class="form-control" placeholder="Can't find your School *" required="required" data-error="Can't find your School">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="Pessonname">Contact person Name *</label>
<input id="Pessonname" type="text" name="Pessonname" class="form-control" placeholder="Contact person Name *" required="required" data-error="Contact person Name ">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="DesignationatSchool">Designation at School(job title at this section) *</label>
<select id="DesignationatSchool" name="DesignationatSchool" class="form-control" required="required" data-error="Designation at School">
<option value=""></option>
<option value="Request principal">Principal</option>
<option value="Request quotation">Founder</option>
<option value="Request order status">Management</option>
<option value="Request copy of an invoice">Teachers</option>
<option value="Other">Others</option>
</select>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="pwd">Password *</label>
<input id="pwd" type="password" name="password" class="form-control" placeholder="Enter your Password *" required="required" data-error="password">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="pwd">Confirm Password *</label>
<input id="pwd" type="password" name="password" class="form-control" placeholder="Confirm Password *" required="required" data-error="Lastname is required.">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="email">Email *</label>
<input id="email" type="email" name="email" class="form-control" placeholder="Please enter your email *" required="required" data-error="Valid email is required.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="tel">Mobile No. *</label>
<input id="tel" type="tel" name="phone" class="form-control" placeholder="Please enter your Mobile No *" required="required" data-error="Valid email is required.">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="col-md-12">
<div class="text-center"> <input type="submit" class="btn btn-success btn-send" value="Register"></div>
<div class="text-center">Aready Register / have an account ? Login here</div>
</div>
</div>
</form>
from django import forms
class RegisterForm(forms.Form):
username = forms.CharField(max_length=50)
email = forms.EmailField(max_length=50)
subject = forms.CharField(max_length=50)
message = forms.CharField(widget=forms.Textarea)
You have to first create the forms.py file in your app as e.g(contact_us)
from django.shortcuts import render
from django.core.mail import send_mail
from .forms import RegisterForm
from django.http import HttpResponse
Create your views here.
def contact_us(request):
#request for POST
if request.method == 'POST':
form = RegisterForm(request.POST)
if form.is_valid():
sender_name = form.cleaned_data['username']
sender_email = form.cleaned_data['email']
message = "{0} has sent you a new message:\n\n{1}".format(sender_name, form.cleaned_data['message'])
send_mail('New Enquiry', message, sender_email, ['example#gmail.com'])
return HttpResponse('Thanks for Contacting US')
else:
form = RegisterForm()
return render(request, 'Contactus/contact.html', {'form': form})
After created the forms you have to insert the forms class name in views.py to display the custom form on browser.
#Create Your Template
<form id="contactform" method="POST">
{% csrf_token %}
<div class="column one-second">
{{ form.username }}
</div>
<div class="column one-second">
{{form.email }}
</div>
<div class="column one">
{{ form.subject }}
</div>
<div class="column one">
{{ form.message }}
</div>
<div class="column one">
<input type="submit" value="submit">
</div>
</form>
After this you have to call the form in template. To display your own custom form.
As i did above.

my model is not showing up in admin model data is getting visble in link bar in csrf middle ware token

{% block body %}
{% load static %}
<div class="container my-3">
<h3>Contact Us</h3>
<form action="/contact" method="post"> {% csrf_token %}
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name='name' placeholder="Enter Your Name">
</div>
<div class="form-group">
<label for="name">Email</label>
<input type="email" class="form-control" id="email" name='email' placeholder="Enter Your Email">
</div>
<div class="form-group">
<label for="name">Phone</label>
<input type="tel" class="form-control" id="phone" name='phone' placeholder="Enter Your Phone Number">
</div>
<div class="form-group">
<label for="desc">Your requirements:-</label>
<textarea class="form-control" id="desc" name='desc' rows="3"></textarea>
</div>
<button type="submit" class="btn btn-success">Contact</button>
</form>
</div>
def index(request):
return render(request, 'prop/home.html')
def contact(request):
if request.method=='POST':
name = request.POST['name']
email = request.POST['email']
phone = request.POST['phone']
desc = request.POST['desc']
contact=Contact(name=name,email=email,phone=phone,desc=desc)
contact.save()
return render(request, 'prop/contact.html')
result
"GET /prop/contact/?csrfmiddlewaretoken=npxCzACid026bcA0bYugZdAL1K2Ondqu2EtpzTuoDbnYivut9tsHJnh5Tq7NWOdU&name=yashi&email=hyashkzo%40gmail.com&phone=55645blbb&desc= HTTP/1.1" 200 8758
make following changes and try
<form action="{% url 'contact' %}" method="POST"> {% csrf_token %}
instead of button
<input type="submit" value="Contact" class="btn btn-success">
Provided you have a url with name contact

Django formset with crispy - submit buttons not submitting

I'm using a FormSet with crispy, and have but a submit button on each row, however hitting submit does not update records currently.
I've searched and found some similar answers which suggest the submit isn't inside the form, but mine are. Also that a form action is missing, but none of my other crispy forms have actions and they work without issue.
Are there any other reasons seen from the code below that would cause the records to not save?
forms.py
class ChangeGroupForm(FormHelper):
def __init__(self, *args, **kwargs):
super(ChangeGroupForm, self).__init__(*args, **kwargs)
self.form_method = 'post'
self.css_class = 'form-inline'
self.form_id = 'changegroup_form'
self.form_show_labels = False
self.layout = Layout(
Div(
Div(
Div(
Field('group', placeholder='Group', css_class="form-control mb-2 mr-sm-2"),
css_class='col-lg-3'
),
Div(
Field('gps', placeholder='gps coords', css_class="form-control mb-2 mr-sm-2"),
css_class='col-lg-8'
),
Div(
HTML("""<input type="submit" name="submit" value="Save" class="btn btn-primary mt-1"/>"""),
css_class='col-lg-1'
),
css_class='row'
),
)
)
self.render_required_fields = True
views.py
#login_required
def db_change_groups(request):
change_form = modelformset_factory(ChangeGroup, fields=('group','gps'))
change_form_helper = ChangeGroupForm()
return render(request, 'home/db_change_groups.html', {
"change_form": change_form,
"change_form_helper": change_form_helper,
})
template.html
{% crispy change_form change_form_helper %}
rendered html
<form id="changegroup_form" method="post"> <input type="hidden" name="csrfmiddlewaretoken"
value="7v0000CPl3G70M6HLfF2FAiwefdfsdgdfwewdf7Gp4nay1hFqZ1Y34SBUA000mHBZQ54">
<div> <input type="hidden" name="form-TOTAL_FORMS" value="10" id="id_form-TOTAL_FORMS"> <input type="hidden"
name="form-INITIAL_FORMS" value="9" id="id_form-INITIAL_FORMS"> <input type="hidden"
name="form-MIN_NUM_FORMS" value="0" id="id_form-MIN_NUM_FORMS"> <input type="hidden"
name="form-MAX_NUM_FORMS" value="1000" id="id_form-MAX_NUM_FORMS"> </div>
<div>
<div class="row">
<div class="col-lg-3">
<div id="div_id_form-0-group" class="form-group">
<div class="controls "> <input type="text" name="form-0-group" value="A" maxlength="50"
class="form-control mb-2 mr-sm-2 textinput textInput form-control" placeholder="Group"
id="id_form-0-group"> </div>
</div>
</div>
<div class="col-lg-8">
<div id="div_id_form-0-gps" class="form-group">
<div class="controls "> <input type="text" name="form-0-gps" maxlength="255"
class="form-control mb-2 mr-sm-2 textinput textInput form-control" placeholder="gps coords"
id="id_form-0-gps"> </div>
</div>
</div>
<div class="col-lg-1"> <input type="submit" name="submit" value="Save" class="btn btn-primary mt-1" />
</div>
</div>
</div> <input type="hidden" name="form-0-id" value="1" id="id_form-0-id">
<div>
<div class="row">
<div class="col-lg-3">
<div id="div_id_form-1-group" class="form-group">
<div class="controls "> <input type="text" name="form-1-group" value="B" maxlength="50"
class="form-control mb-2 mr-sm-2 textinput textInput form-control" placeholder="Group"
id="id_form-1-group"> </div>
</div>
</div>
<div class="col-lg-8">
<div id="div_id_form-1-gps" class="form-group">
<div class="controls "> <input type="text" name="form-1-gps" maxlength="255"
class="form-control mb-2 mr-sm-2 textinput textInput form-control" placeholder="gps coords"
id="id_form-1-gps"> </div>
</div>
</div>
<div class="col-lg-1"> <input type="submit" name="submit" value="Save" class="btn btn-primary mt-1" />
</div>
</div>
</div>
</div> <input type="hidden" name="form-9-id" id="id_form-9-id">
</form>
You need to attach somthing like this to your view
def db_change_groups(request):
....
if request.method == "POST":
form = ChangeGroupForm(request.POST)
if form.is_valid():
# Access cleaned data with
group = form.cleaned_data['group']
# Then you can save this to a model.
# return success template or something
else:
# Check for errors.
If you created the form with ModelForm instead of FormHelper you could use form.save() which you automatically save it to the model.

Django image upload with js plugin issue

I am using js plugin to upload image, first time when i select image from the plugin the form gets submitted. The issue is that i select the image first time but then i don't want that image and i click on it again to upload another image, the form does not get validated and fails to submit.
views.py
class SelectObituaryView(LoginRequiredMixin, TemplateView):
template_name = "website/obituary_select.html"
def get_context_data(self, **kwargs):
context = super(SelectObituaryView, self).get_context_data(**kwargs)
church_id = self.request.session.get('church_id', None)
if church_id:
samples = ObituarySample.objects.filter(organization__id=church_id)
context['obituary_samples'] = samples
context['church_cover'] = self.request.session.get('church_cover', None)
return context
#transaction.atomic
def post(self, request):
print("Entered function")
try:
data = request.POST.copy()
data['organization'] = request.session.get('church_id', None)
data['slug'] = data['name'].replace(' ', '-')
data['funeral_time'] = data['funeral_time'].replace(" ", "")
data['viewing_time'] = data['viewing_time'].replace(" ", "")
if len(request.FILES.getlist('gallery')) > 10:
messages.error(request, "Max gallery images limit exceeded.")
return HttpResponseRedirect(
reverse('obituary:create', kwargs={'sample_obituary_id': request.POST.get('obituary_sample')}))
obituary_form = ObituaryForm(data=data, files=request.FILES)
# print("obituary form data",data)
print("before is valid")
if obituary_form.is_valid():
print("Inside is_valid")
obituary_instance = obituary_form.save(commit=False)
obituary_instance.image = obituary_instance.obituary_sample.background
obituary_instance.user = request.user
obituary_instance.save()
obituary_instance.update_slug_with_id()
#override profile_image
#imageName = os.path.basename(obituary_instance.profile_image.path)
imgArr = os.path.split(obituary_instance.profile_image.path)
image_data = request.POST['profile_image1']
b = json.loads(image_data)
head, data = b["output"]["image"].split(',')
binary_data = a2b_base64(data)
print(binary_data)
with open(obituary_instance.profile_image.path, 'wb+') as fh:
myfile = File(fh)
myfile.write(binary_data)
imprinted_image_path = apps.obituary.utils.imprint(obituary_instance, obituary_instance.obituary_sample)
# Save imprinted image in db
with open(imprinted_image_path, 'rb') as f:
data = f.read()
file_postfix = datetime.now().strftime("%Y%m%d-%H%M%S")
obituary_instance.image.save("%s%s.jpg" % ('obituary', file_postfix), ContentFile(data))
for gallery_image in request.FILES.getlist('gallery'):
GalleryImage.objects.create(obituary=obituary_instance, image=gallery_image)
return HttpResponseRedirect(reverse('obituary:preview', kwargs={'obituary_id': obituary_instance.id}))
else:
print("else")
messages.error(request, constants.OPERATION_UNSUCCESSFUL)
return HttpResponseRedirect(
reverse('obituary:create', kwargs={'sample_obituary_id': request.POST.get('obituary_sample')}))
except Exception as e:
print(e)
print("except")
messages.error(request, "Unable to create, Please try again.")
return HttpResponseRedirect(
reverse('obituary:create', kwargs={'sample_obituary_id': request.POST.get('obituary_sample')}))
html
{% extends "website/base.html" %}
{% load static %}
{% block javascript %}
<script>
// Submit post on submit
{# $('#create_obit').on('submit', function(event){#}
{# event.preventDefault();#}
{# alert("Aamixsh");#}
{# });#}
$("#create_obit").submit(function(evt){
//evt.preventDefault();
if($(this).find('input[name="profile_image"]').val() != "") {
$(this).find('input[name="profile_image"]').attr('name','profile_image1');
$(this).find(".slim").find('input[type="file"]').attr('name','profile_image');
return true;
}
});
$(document).ready(function(){
$('input[type="text"]').attr( 'autocomplete', 'off' );
$('.dateReadonly').attr( 'readonly', 'true' );
});
</script>
{% endblock %}
{% block body_block %}
<!-- Banner Area Start -->
<div class="banner-area">
<div class="overlay"></div>
<div class="img-holder">
<div class="holder"><img src="{{ church_cover }}" alt=""></div>
</div>
<div class="caption">
<div class="holder">
<div class="container">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="banner">
<h2>Fill in Loved Ones Details</h2>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="section-space">
<div class="container">
<div class="row">
<div class="col-xs-12">
<div class="row">
<h3 class="heading-title">Create an Obituary</h3>
<form class="setting-form" id="create_obit" action="{% url 'obituary:select' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<fieldset>
<div class="col-xs-12">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
Name: <input type="text" maxlength="50" name="name" placeholder="Name*" class="form-control input-field" required>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
Funeral Address: <input type="text" maxlength="50" name="address" placeholder="Funeral Address*" class="form-control input-field" required>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
Date of Birth: <input type="text" id="datepicker1" name="date_of_birth" placeholder="Date of Birth*" class="dateReadonly form-control input-field" required>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
Date of Death: <input type="text" id="datepicker2" name="date_of_death" placeholder="Date of Death*" class="dateReadonly form-control input-field" required>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
Funeral Date: <input type="text" name="funeral_date" id="datepicker3" placeholder="Funeral Date*" class="dateReadonly form-control input-field" required>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
Funeral Time: <input type="text" name="funeral_time" id="timepicker" placeholder="Funeral Time*" class="form-control input-field" required>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
Surviving Family: <input type="text" maxlength="100" name="family_info" placeholder="spouse Mary Louise, and sons Joe, Ed, and Tim, etc. (Max Limit: 100 Characters)" class="form-control input-field" required>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
Ways To Contribute: <input type="text" maxlength="40" name="memorial_donation_info" placeholder="e.g. Donation url or other Information* (Max Limit: 40 Characters)" class="form-control input-field" >
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
Viewing Date: <input type="text" name="viewing_date" id="datepicker4" placeholder="Viewing Date*" class="dateReadonly form-control input-field" required>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
Viewing Time: <input type="text" name="viewing_time" id="timepicker2" placeholder="Viewing Time*" class="form-control input-field" required>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
Viewing Address: <input type="text" maxlength="50" name="viewing_address" placeholder="Viewing Address*" class="form-control input-field" required>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
Message: <textarea maxlength="500" name="message" id="" cols="30" rows="10" class="form-control input-field" placeholder="Message* (Max Limit: 500 Characters)" required></textarea>
</div>
</div>
</div>
<input type="hidden" name="obituary_sample" value="{{ obituary_form.obituary_sample.value }}" />
</div>
<div class="col-sm-12">
<h3>Upload Obituary Photo</h3>
<div class = "form-group">
Maximum image size is 8 MB. You can rotate and crop the uploaded image by using the control buttons at the bottom of the image.
<!-- original <input type="file" name="profile_image" placeholder="Obituary Image*" class="form-control input-field" required> -->
<input type="file" name="profile_image" placeholder="Obituary Image*" class="slim" required>
</div>
</div>
<div class="col-xs-12">
<h3>Upload Gallery Photos</h3>
<div class="dropzone" id="my-awesome-dropzone">
<div class="fallback">
(Maximum image size should be 8 MB)
<input type="file" name="gallery" multiple class="form-control input-field"/>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<input type="checkbox" onchange="document.getElementById('create').disabled = !this.checked;" /> I understand, that the obituary cannot be edited once paid for!
</div>
</div>
</div>
<div class="col-xs-12">
<div class="form-group">
<button type="submit" id="create" class="btn send-btn" disabled>Create</button>
</div>
</div>
</fieldset>
</form>
</div>
</div>
</div>
</div>
</div>
{% endblock %}

How to show error messages in a custom signup template in Django

I'm trying to show error message in my custom signup template. Just to verify my below codes work, I used the {{ form.as_table }} and it shows error message properly. However, when I use my custom signup template, it doesn't show any error message when I cause an error on purpose on the signup form.
HTML
<form class="form-signin" method="POST">
{% csrf_token %}
<div class="container">
<div class="jumbotron">
<a class="navbar-brand js-scroll-trigger" href="{% url 'boutique:index' %}"><img width="165" height="30" src="{% static 'boutique/img/modvisor_logo_black.png' %}"></a>
<br><br>
<div class="text-center mb-4">
<h1 class="h3 mb-3 font-weight-normal">Join Modvisor</h1>
<p class="error-message">
{% if form.non_field_errors %}
{% for error in form.non_field_errors %}
{{ error }}
{% endfor %}
{% endif %}
</p>
</div>
<div class="form-label-group">
<input type="text" id="inputEmail" class="form-control" name="username" placeholder="Email address" required autofocus>
<label for="inputEmail">Email</label>
</div>
<div class="form-label-group">
<input type="password" id="inputPassword1" class="form-control" name="password1" placeholder="Password" required>
<label for="inputPassword">Password</label>
</div>
<div class="form-label-group">
<input type="password" id="inputPassword2" class="form-control" name="password2" placeholder="Password" required>
<label for="inputPassword">Confirm Password</label>
</div>
<!--
<div class="form-label-group">
<input type="password" id="inputPassword" class="form-control" name="password2" placeholder="Password" required>
<label for="inputPassword">Confirm Password</label>
</div>
<div class="checkbox mb-3">
<label>
<input type="checkbox" value="remember-me"> Remember me
</label>
</div>
-->
<button class="btn btn-success btn-block" type="submit">Sign Up</button>
<br>
<button class="btn btn-secondary btn-block" type="button">Back</button>
<p class="mt-5 mb-3 text-muted text-center">© 2018 Modvisor All Rights Reserved.</p></p>
</div>
</div>
</form>
forms.py
class SignupForm(UserCreationForm):
class Meta(UserCreationForm.Meta):
fields = UserCreationForm.Meta.fields
views.py
def signup(request):
if request.method == 'POST':
form = SignupForm(request.POST)
if form.is_valid():
form.save()
return redirect(settings.LOGIN_URL)
else:
form = SignupForm()
return render(request, 'accounts/register.html', {'form': form})
You should use form.errors.field_name for errors related to specific field. Like for error on username field, it will be form.errors.username
You HTML will look like
<div class='error'>{{form.errors.username}}</div>
<div class="form-label-group">
<input type="text" id="inputEmail" class="form-control" name="username" placeholder="Email address" required autofocus>
<label for="inputEmail">Email</label>
</div>