Django and Bootstrap Modal - django

Please help me to progress with my project. I'm new to Django and bootstrap and i'm currently working on a project. For the Registration of the user i'm using a popup modal.
I've set up the following:
Html file with modal
{% load static %}
<!-- Register Modal Starts -->
<div class="row mt25 tab-pane fade" id="profile" role="tabpanel" aria-labelledby="profile-tab">
<div class="col-lg-6 col-xl-6">
<div class="regstr_thumb">
<img class="img-fluid w100" src="{% static 'images/resource/regstr.jpg' %}" alt="regstr.jpg">
</div>
</div>
<div class="col-lg-6 col-xl-6">
<div class="sign_up_form">
<form action="{% url 'register' %}" method="POST" id="register-form">
{% csrf_token %}
<div class="heading">
<h4>Register</h4>
</div>
<div class="row">
<div class="col-lg-12">
<button type="submit" class="btn btn-block btn-fb"><i class="fa fa-facebook float-left mt5"></i> Login with Facebook</button>
</div>
<div class="col-lg-12">
<button type="submit" class="btn btn-block btn-googl"><i class="fa fa-google float-left mt5"></i> Login with Google</button>
</div>
</div>
<hr>
<div class="form-group ui_kit_select_search mb0">
<select class="selectpicker" data-live-search="true" data-width="100%">
<option data-tokens="SelectRole">Landlord</option>
<option data-tokens="Agent/Agency">Property Manager</option>
<option data-tokens="SingleUser">Homeowner</option>
</select>
</div>
<div class="form-group input-group">
<p>{{ form.errors.email}}</p>
{{form.email}}
<input type="email" class="form-control" id="exampleInputEmai" placeholder="Email">
<div class="input-group-prepend">
<div class="input-group-text"><i class="fa fa-envelope-o"></i></div>
</div>
</div>
<div class="form-group input-group">
<p>{{ form.errors.password1 }}</p>
{{ form.password1 }}
<input type="password" name="password1" class="form-control" id="exampleInputPassword2" placeholder="Password">
<div class="input-group-prepend">
<div class="input-group-text"><i class="flaticon-password"></i></div>
</div>
</div>
<div class="form-group input-group">
<p>{{ form.errors.password2 }}</p>
{{ form.password2 }}
<input type="password" name="password2" class="form-control" id="exampleInputPassword3" placeholder="Re-enter password">
<div class="input-group-prepend">
<div class="input-group-text"><i class="flaticon-password"></i></div>
</div>
</div>
<div class="form-group input-group">
<p>{{ form.errors.country }}</p>
{{ form.country }}
<input type="country" name="country" class="form-control" id="exampleInputCountry" placeholder="Country">
<div class="input-group-prepend">
<div class="input-group-text"><i class="flaticon-country"></i></div>
</div>
</div>
<div class="form-group input-group">
<p>{{ form.errors.city }}</p>
{{ form.city }}
<input type="city" name="city" class="form-control" id="exampleInputCity" placeholder="City">
<div class="input-group-prepend">
<div class="input-group-text"><i class="flaticon-city"></i></div>
</div>
</div>
<div class="form-group input-group">
<p>{{ form.errors.phone_number }}</p>
{{ form.phone_number }}
<input type="phone" name="phone_number" class="form-control" id="exampleInputPhone" placeholder="Phone Number">
<div class="input-group-prepend">
<div class="input-group-text"><i class="flaticon-phone"></i></div>
</div>
</div>
<div class="form-group custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" id="exampleCheck2">
<label class="custom-control-label" for="exampleCheck2">I have read and accept the Terms and Privacy Policy?</label>
</div>
<button type="submit" class="btn btn-log btn-block btn-thm">Sign Up</button>
<p class="text-center">Already have an account? <a class="text-thm" href="#">Log In</a></p>
</form>
</div>
</div>
</div>
The views.py file:
from django.shortcuts import render, redirect
from .forms import UserAdminCreationForm
from django.contrib import messages
def login(request):
return render(request, 'login.html')
def register(request):
form = UserAdminCreationForm()
if request.method == 'POST':
form = UserAdminCreationForm(request.POST)
if form.is_valid():
form.save()
user = form.cleaned_data.get('email')
messages.success(request, 'Account was created for ' + user)
return redirect('index')
return render(request, 'accounts/register.html', {'form': form})
The urls.py file
from django.urls import path, include
from . import views
urlpatterns = [
path('accounts/', include('django.contrib.auth.urls')),
path('register', views.register, name='register'),
path('logout', views.logout, name='logout'),
path('dashboard', views.dashboard, name='dashboard'),
]
The forms.py file:
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm
from django import forms
class UserAdminCreationForm(UserCreationForm):
"""A Custom form for creating new users."""
email = forms.EmailField(label="", widget=forms.EmailInput(attrs={'class': 'form-control', 'placeholder': 'Email Address'}), )
password1 = forms.CharField(label="", widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Password'}))
password2 = forms.CharField(label="", widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Repeat Password'}))
country = forms.CharField(label="", max_length=50, widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Country'}))
city = forms.CharField(label="", max_length=50, widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'City'}))
phone_number = forms.CharField(label="", max_length=20, widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Phone Number'}))
class Meta:
model = get_user_model()
fields = ['user_types', 'email', 'password1', 'password2', 'country', 'city', 'phone_number']
When the popup modal with the registration form is opened and click SignUp i have setup a new page accounts/register page just for testing. But i do not want this page, i want to complete the form above and add user in the database. How can i configure that?
My problems that i cannot solve are:
how when i fill in the popup registration (inside the modal) and press SignUp to add user in the database without the accounts/register page?
Please help! Thank you for your time!

change input fields with form.{field name} and add {{ form.errors.{fieldname} }}
here your code:
<!-- Login/Register Starts -->
<!-- Modal -->
<div class="sign_up_modal modal fade" tabindex="-1" role="dialog" aria-hidden="true" id=bd-example-modal-lg>
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<div class="modal-body container pb20">
<div class="row">
<div class="col-lg-12">
<ul class="sign_up_tab nav nav-tabs" id="myTab" role="tablist">
<li class="nav-item">
<a class="nav-link active" id="home-tab" data-toggle="tab" href="#home" role="tab" aria-controls="home" aria-selected="true">Login</a>
</li>
<li class="nav-item">
<a class="nav-link" id="profile-tab" data-toggle="tab" href="#profile" role="tab" aria-controls="profile" aria-selected="false">Register</a>
</li>
</ul>
</div>
</div>
<!-- Register Modal Starts -->
<div class="row mt25 tab-pane fade" id="profile" role="tabpanel" aria-labelledby="profile-tab">
<div class="col-lg-6 col-xl-6">
<div class="regstr_thumb">
<img class="img-fluid w100" src="{% static 'images/resource/regstr.jpg' %}" alt="regstr.jpg">
</div>
</div>
<div class="col-lg-6 col-xl-6">
<div class="sign_up_form">
<form action="{% url 'register' %}" method="POST" id="register-form">
{% csrf_token %}
{{form.as_p}}
<div class="heading">
<h4>Register</h4>
</div>
<div class="row">
<div class="col-lg-12">
<button type="submit" class="btn btn-block btn-fb"><i class="fa fa-facebook float-left mt5"></i> Login with Facebook</button>
</div>
<div class="col-lg-12">
<button type="submit" class="btn btn-block btn-googl"><i class="fa fa-google float-left mt5"></i> Login with Google</button>
</div>
</div>
<hr>
<div class="form-group ui_kit_select_search mb0">
<select class="selectpicker" data-live-search="true" data-width="100%">
<option data-tokens="SelectRole">Landlord</option>
<option data-tokens="Agent/Agency">Property Manager</option>
<option data-tokens="SingleUser">Homeowner</option>
</select>
</div>
<div class="form-group input-group">
<p>{{ form.errors.email}}</p>
{{ form.email }}
<div class="input-group-prepend">
<div class="input-group-text"><i class="fa fa-envelope-o"></i></div>
</div>
</div>
<div class="form-group input-group">
<p>{{ form.errors.password1 }}</p>
{{ form.password1 }}
<div class="input-group-prepend">
<div class="input-group-text"><i class="flaticon-password"></i></div>
</div>
</div>
<div class="form-group input-group">
{{ form.password2 }}
<div class="input-group-prepend">
<div class="input-group-text"><i class="flaticon-password"></i></div>
</div>
</div>
<div class="form-group input-group">
<p>{{ form.errors.country }}</p>
{{ form.country }}
<div class="input-group-prepend">
<div class="input-group-text"><i class="flaticon-country"></i></div>
</div>
</div>
<div class="form-group input-group">
<p>{{ form.errors.city }}</p>
{{ form.city }}
<div class="input-group-prepend">
<div class="input-group-text"><i class="flaticon-city"></i></div>
</div>
</div>
<div class="form-group input-group">
<p>{{ form.phone_number }}</p>
{{ form.phone_number }}
<div class="input-group-prepend">
<div class="input-group-text"><i class="flaticon-phone"></i></div>
</div>
</div>
<div class="form-group custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" id="exampleCheck2">
<label class="custom-control-label" for="exampleCheck2">I have read and accept the Terms and Privacy Policy?</label>
</div>
<button type="submit" class="btn btn-log btn-block btn-thm">Sign Up</button>
<p class="text-center">Already have an account? <a class="text-thm" href="#">Log In</a></p>
</form>
</div>
</div>
</div>

Related

How to assign HTML Form fields to DJANGO Model Forms without using ModelForm

I am trying to make pretty looking HTML form where each fields are formatted with some validation and icons. Once these fields are submitted I want to save to Model instance using either using Model form or some other approach which allows to make this operation smooth.
Here is my code snippet:
model.py:
class Client(Model):
client_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
first_name = models.CharField(max_length=256)
last_name = models.CharField(max_length=256)
date_of_birth = models.DateField(blank=True, null=True)
email = models.EmailField(null=True)
form.py:
class ClientNewForm(forms.ModelForm):
class Meta:
model = Client
fields = "__all__"
view.py (I know this is wrong but need help to figure out what's the best way to do this):
class ClientCreateView(CreateView):
model=Client
form_class = ClientNewForm
template_name = 'Client/client_new.html'
context_object_name = 'client' # refer the object as patient in template
success_url = reverse_lazy('WebApp:clients')
def form_valid(self, form):
model = form.save(commit=False)
#model.submitted_by = self.request.user
model.save()
messages.success(self.request, "The Client is created successfully.")
return super(ClientCreateView, self).form_valid(form)
Template:
<div class='row'>
<div class="col-md-8 col-sm-8 col-xs-12">
<div class="x_panel">
<div class="x_title">
<h2>NEW REGISTRATION</h2>
</div>
<div class="x_content">
<form class="form-horizontal form-label-left input_mask" action="" method="post">
{% csrf_token %}
<div class="col-md-6 col-sm-6 col-xs-12 form-group has-feedback">
<input type="text" class="form-control has-feedback-left" id="in-fn" placeholder="First Name" name="first_name">
<span class="fa fa-user form-control-feedback left" aria-hidden="true"></span>
</div>
<div class="col-md-6 col-sm-6 col-xs-12 form-group has-feedback">
<input type="text" class="form-control has-feedback-left" id="in-ln" placeholder="Last Name" name="last_name">
<span class="fa fa-user form-control-feedback left" aria-hidden="true"></span>
</div>
<div class="col-md-6 col-sm-6 col-xs-12 form-group has-feedback">
<input type="text" class="form-control has-feedback-left" id="in-dob" name="date_of_birth" placeholder="Date of Birth (mm/dd/yyyy)" >
<span class="fa fa-calendar form-control-feedback left" aria-hidden="true"></span>
</div>
<div class="col-md-6 col-sm-6 col-xs-12 form-group has-feedback">
<input type="text" class="form-control has-feedback-left" id="in-email" placeholder="Email" name="email">
<span class="fa fa-envelope form-control-feedback left" aria-hidden="true"></span>
</div>
<div class="form-buttons">
<div class="col-md-9 col-sm-9 col-xs-12 col-md-offset-9">
Cancel
Reset
<input type="submit" value="Save" class="btn btn-round btn-success"/>
</div>
</div>
</form>
</div>
</div>
</div>
So I need help from Django Experts to make this work properly. If possible can you please help me to figure out following:
Can I make each Django Field as individual formatting filed (I like to format each fields better than crispy forms)? (I am using gentelella templates).
What would be best way to get each fields assign back to model fields and save in database? Current approach I am taking is Django Model form but I am not sure if this right approach for me to achieve what I am trying to do.
Really appreciate your help and consideration.
Thank You.
I used django-wiget-tweaks library to get me through this problem.
Its super Easy and it works like charm to help me customize the form look and feel.
Here are steps I followed:
step 1: install: pip install django-widget-tweaks on my virtual environment
Step 2: update settings.py for INSTALLED_APPS = [ 'widget_tweaks']
Step 3: on my template I had to put following at the top of the Template:
{% load widget_tweaks %}
Step 4: Now I can use the renderfields to do this all stuff as follow:
<div class='row'>
<div class="col-md-8 col-sm-8 col-xs-12">
<div class="x_panel">
<div class="x_title">
<h2>NEW REGISTRATION</h2>
</div>
<div class="x_content">
<form class="form-horizontal form-label-left input_mask" action="" method="post">
{% csrf_token %}
<div class="col-md-6 col-sm-6 col-xs-12 form-group has-feedback">
{% render_field form.first_name class="form-control" placeholder="First Name"|append_attr:"required" %}
<span class="fa fa-user form-control-feedback left" aria-hidden="true"></span>
</div>
<div class="col-md-6 col-sm-6 col-xs-12 form-group has-feedback">
{% render_field form.last_name class="form-control" placeholder="Last Name" %}
<span class="fa fa-user form-control-feedback left" aria-hidden="true"></span>
</div>
<div class="col-md-6 col-sm-6 col-xs-12 form-group has-feedback">
{% render_field form.date_of_birth class="form-control" placeholder="Date of Birth (mm/dd/yyyy)"%}
<span class="fa fa-calendar form-control-feedback left" aria-hidden="true"></span>
</div>
<div class="col-md-6 col-sm-6 col-xs-12 form-group has-feedback">
{% render_field form.email class="form-control has-feedback-left" placeholder="Email Address" %}
<span class="fa fa-envelope form-control-feedback left" aria-hidden="true"></span>
</div>
<div class="form-buttons">
<div class="col-md-9 col-sm-9 col-xs-12 col-md-offset-9">
Cancel
Reset
<input type="submit" value="Save" class="btn btn-round btn-success"/>
</div>
</div>
</form>
</div>
</div>
</div>
Step 5: On view now I can use CreateView, UpdateView, ListView with Modelforms.
So far it works for me.
I hope this helps to other member who is looking to be creative with their forms.

Django - I want to display current rate depending on the category i select

here is my front-end and everything is working fine however, i don't want all rate to display at once, i want the rate to display one at a time depending on the card category i select.
From the image i uploaded, current rate of other card category are showing which i don't want, please i need help even if it will require using javascript of ajax
Here is my index(template)
{% for giftcard in giftcards %}
<!-- Card -->
<div class="col-lg-4 gift__card col-6 p-0">
<a type="button" class="btn">
<img class="img-fluid gift__card-img" src="{{ giftcard.card_image.url }}">
</a>
<div class="container d-flex align-items-center justify-content-center">
<div class="gift__card-modal-container py-5">
<div class="card__container">
<div class="gift__card-overlay"></div>
<div class="container-fluid bg-light gift__card-modal shadow-lg">
<div class="pop p-5">
<div class="row d-flex align-items-center justify-content-between">
<div class="col-lg-5 col-12 p-0 m-0">
<img class="img-fluid gift__card-img" style="width: 40rem;" src="{{ giftcard.card_image.url }}">
<p class="text-muted">Select the card category and the amount.</p>
</div>
<div class="col-lg-6 col-sm-12 card-details">
<form class="card-form">
<div class="form-group py-2">
<label for="card-category">Card category</label>
<select id="category" class="form-select py-2" aria-label="Default select example">
{% for spec in giftcard.category_set.all %}
<option value="{{ spec.category }}">{{ spec.category }}</option>
{% endfor %}
</select>
</div>
<div class="form-group py-2">
<label for="Amount">Amount</label>
<div class="d-flex align-items-center amount">
<input type="text" class="form-control" id="amount"
placeholder="Please enter amount">
<span class="">#100,000</span>
</div>
</div>
<div class="form-group py-3">
{% for spec in giftcard.category_set.all %}
<label for="rate">Current rate - {{ spec.rate }}</label>
{% endfor %}
</div>
<div class="border-none pt-2 pl-3 d-flex justify-content-end">
<button type="button" class="btn process-card-btn">Proceed</button>
</div>
</form>
</div>
</div>
</div>
</div>
<div class="gift__terms-card hide fade" id="terms" tabindex="-1" role="dialog"
aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content terms">
<div class="p-5">
<h4 class="terms-title pb-4">Trading terms</h4>
{% for spec in giftcard.category_set.all %}
<p class="pb-2">{{ spec.terms }}</p>
{% endfor %}
<div class="border-none pt-3 pl-3 d-flex justify-content-end">
<button type="button" class="btn process-card-btn">Proceed</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
{% endfor %}
Here is my models
class Giftcard(models.Model):
name = models.CharField(max_length=100, unique=True)
card_image = models.ImageField(upload_to='Giftcard/', blank=False)
date = models.DateTimeField(auto_now_add=True)
publish = models.BooleanField(default=False)
class Category(models.Model):
category = models.CharField(max_length=250)
rate = models.IntegerField()
terms = models.TextField()
card_category = models.ForeignKey(Giftcard, on_delete=models.CASCADE)
Here is my views
def giftcard(request):
giftcards = Giftcard.objects.filter(publish=True)
context = {
'giftcards': giftcards
}
return render(request, 'dashboard/giftcard.html', context)

How is it possible to get data from one form that has multiple textareas in 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')

Custom Form for create and update the blogposts give Page Not Found error

I've create a simple form to create and update the blogposts. After the creation of the update view happen something strange that I can't solve.
views.py
def createPost(request):
if request.method == "POST":
form = BlogPostForm(request.POST or None)
if form.is_valid():
new_post = form.save(commit=False)
new_post.slug_post = slugify(new_post.title)
new_post.save()
return redirect('post_list')
else:
form = BlogPostForm()
context = {
'form': form,
}
template = 'blog/editing/create_post.html'
return render(request, template, context)
def updatePost(request, slug_post=None):
update_post = get_object_or_404(BlogPost, slug_post=slug_post)
form = BlogPostForm(request.POST or None, instance=update_post)
if form.is_valid():
update_post = form.save(commit=False)
update_post.slug_post = slugify(update_post.title)
update_post.save()
return redirect('post_list')
context = {
'form': form,
}
template = 'blog/editing/create_post.html'
return render(request, template, context)
urls.py
urlpatterns = [
path("blog/", views.listPost, name='post_list'),
path("blog/<str:slug_post>/", views.singlePost, name='single_post'),
path("blog/create-post/", views.createPost, name='create_post'),
path("blog/<str:slug_post>/update-post/", views.updatePost, name='update_post'),
path("blog/<str:slug_post>/delete-post/", views.deletePost, name='delete_post'),
]
post_list.html
<div class="row">
{% for post in post_list %}
{% if forloop.first %}<div class="card-deck">{% endif %}
<div class="card mb-3 shadow" style="max-width: 540px;">
<div class="row no-gutters">
<div class="col-md-4">
<img src="{{ post.header_image_link }}" class="card-img" alt="{{ post.title }}" style="height: 250px;">
</div>
<div class="col-md-8">
<div class="card-body">
<h4 class="card-title">{{ post.title }}</h4>
<p class="card-text">{{ post.description }}</p>
<p class="card-text my-0 py-0"><small class="text-muted"><strong>Published: </strong>{{ post.publishing_date|date }}</small></p>
</div>
</div>
</div>
</div>
{% if forloop.counter|divisibleby:"4" or forloop.last %}</div>{% endif %}
{% if forloop.counter|divisibleby:"4" and not forloop.last %}<div class="card-deck">{% endif %}
{% empty %}
<div class="row justify-content-md-center my-3 mx-1 py-2 shadow bg-danger rounded">
<div class="col-md-auto">
<h1 class="text-center px-2 py-2" id="text-shadow">Empty list!</h1>
</div>
</div>
{% endfor %}
</div>
create_post.html
<form class="" method="POST" enctype="multipart/form-data" novalidate>{% csrf_token %}
<div class="form-group">
<div class="row">
<div class="col-sm-9">
<div class="form-group mb-4">
<div>{{ form.title }}</div>
<label for="id_title">
<span class="text-info" data-toggle="tooltip" title="{{ form.title.help_text }}">
<i class="far fa-question-circle"></i>
</span>
<small class="text-danger">{{ form.title.errors }}</small>
</label>
</div>
<div class="form-group mb-4">
<div>{{ form.description }}</div>
<label for="id_description">
<span class="text-info" data-toggle="tooltip" data-placement="bottom" title="{{ form.description.help_text }}">
<i class="far fa-question-circle"></i>
</span>
<small class="text-danger">{{ form.description.errors }}</small>
</label>
</div>
<div class="form-group mb-4">
<div>{{ form.contents }}</div>
<label for="id_contents">
<span class="text-info" data-toggle="tooltip" data-placement="bottom" title="{{ form.contents.help_text }}">
<i class="far fa-question-circle"></i>
</span>
<small class="text-danger">{{ form.contents.errors }}</small>
</label>
</div>
<div class="form-group mb-4">
<div>{{ form.header_image_link }}</div>
<label for="id_highlighted">
<span class="text-info" data-toggle="tooltip" title="{{ form.header_image_link.help_text }}">
<i class="far fa-question-circle"></i>
</span>
<small class="text-danger">{{ form.header_image_link.errors }}</small>
</label>
</div>
</div>
<div class="col-sm-3">
<div class="form-inline mb-4 py-0">
<div class="input-group mx-1">
<label for="id_highlighted">{{ form.highlighted.label }}</label>
<div class="ml-1">{{ form.highlighted }}</div>
</div>
<div class="input-group mx-1">
<label for="id_draft">{{ form.draft.label }}</label>
<div class="ml-1">{{ form.draft }}</div>
</div>
</div>
<div class="form-group mb-4">
<label for="publishing_date_field">
{{ form.publishing_date.label }}
<small class="text-danger">{{ form.publishing_date.errors }}</small>
</label>
<div class="input-group date" data-target-input="nearest">
{{ form.publishing_date }}
<div class="input-group-append" data-target="#publishing_date_field" data-toggle="datetimepicker">
<div class="input-group-text"><i class="fa fa-calendar"></i></div>
</div>
</div>
<script>
$(function () {
$("#publishing_date_field").datetimepicker({
format: 'DD/MM/YYYY HH:mm',
});
});
</script>
</div>
<div class="form-group mb-4">
<div class="row justify-content-md-center py-4 border border-warning rounded">
<h5 class="text-justify px-3">Clicca sul tasto che segue per vedere l'elenco delle immagini. Potrai copiare il link all'immagine che ti interessa ed usarlo per creare l'immagine di testata o migliorare i contenuti del post.</h5>
<button type="button" class="btn btn-primary mt-2 mx-2" data-toggle="modal" data-target=".bd-example-modal-xl">Image list</button>
</div>
<div class="modal fade bd-example-modal-xl" tabindex="-1" role="dialog" aria-labelledby="myExtraLargeModalLabel" aria-hidden="true">
<div class="modal-dialog modal-xl modal-dialog-scrollable">
<div class="modal-content">
<div class="modal-body">
{% for image in images_url_list %}
{% if forloop.first %}<div class="card-deck">{% endif %}
<div class="card mx-1 my-1" style="height: 100%; width: 300px;">
<img src="{{ image.file.url }}" class="card-img-top h-100" alt="{{ image.file.url }}" id="{{ image.id }}">
<div class="card-body">
<button class="btn btn-outline-primary btn-sm" type="button" onclick="CopyToClipboard('{{ image.id }}')">Copy URL</button>
</div>
</div>
{% if forloop.counter|divisibleby:"3" or forloop.last %}</div>{% endif %}
{% if forloop.counter|divisibleby:"3" and not forloop.last %}<div class="card-deck">{% endif %}
{% endfor %}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<hr>
<div class="row justify-content-md-center">
<div class="col-md-auto">
<input type="submit" class="btn btn-info" value="Pubblica">
</div>
</div>
</div>
</form>
I have this error message if I try to create a new post with my form:
Page not found (404) Request Method: GET Request URL:
http://127.0.0.1:8000/blog/create-post/ Raised by:
blog.views.singlePost
As I said this happen after the creation of updatePost. If I comment the path of the single post path("blog/<str:slug_post>/", views.singlePost, name='single_post'), I can create a post whitout problems.
What I've wrong?
Move path("blog/<str:slug_post>/", views.singlePost, name='single_post') to the bottom of your list, below the update and delete paths.
urlpatterns = [
path("blog/", views.listPost, name='post_list'),
path("blog/create-post/", views.createPost, name='create_post'),
path("blog/<str:slug_post>/update-post/", views.updatePost, name='update_post'),
path("blog/<str:slug_post>/delete-post/", views.deletePost, name='delete_post'),
path("blog/<str:slug_post>/", views.singlePost, name='single_post'),
]

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 %}