When I access the update page it doesn't populate the fields with the existing entry data (which is there, and print statements I've placed in parts of the view show that it's accessible and exists), I'm not really sure why it's not populating.
This is my view:
#login_required
def sites_update_view(request, place_id=None):
if place_id:
place = get_object_or_404(SiteMeta, pk=place_id)
else:
return redirect('sites-index')
if request.POST:
form = SitesAddForm(request.POST, instance=place)
if form.is_valid():
form.save()
return redirect('sites-index')
else:
form = SitesAddForm(instance=place)
return render(request, 'sites-update.html', {
'form': form,
'site': place,
'place_id': place_id
})
My template:
{% extends "newbase.html" %}
{% load url from future %}
{% load floppyforms %}
{% load staticfiles %}
{% block title %} - Update Site {% endblock %}
{% block content %}
<div class="row">
<div class="col-sm-6 col-md-6">
<h3 class="heading">Update Surveillance Site</h3>
<form method="post" action={% url 'sites-update' place_id=site.pk %}>
{% csrf_token %}
<div class="formSep">
<div class="row">
<div class="col-sm6 col-md-6">
<label for="id_name">Site Name:<span class="f_req">*</span></label>
{{ form.name }}
<span class="help-block">What is the site name?</span>
</div>
<div class="col-sm-6 col-md-6">
<label for="id_lga">LGA:<span class="f_req">*</span></label>
{{ form.lga }}
<span class="help-block">What is the LGA?</span>
</div>
<div class="col-sm-6 col-md-6">
<label for="id_site_type">Site Type:<span class="f_req">*</span></label>
{{ form.site_type }}
<span class="help-block">What type of site is this?</span>
</div>
<div class="col-sm-6 col-md-6">
<label for="id_site_priority">Site Priority:<span class="f_req">*</span></label>
{{ form.site_priority }}
<span class="help-block">What is the priority of this site?</span>
</div>
<div class="col-sm-6 col-md-6">
<label for="id_site_category">Site Category:<span class="f_req">*</span></label>
{{ form.site_category }}
<span class="help-block">What category should the site be in?</span>
</div>
</div>
</div>
<div class="row">
<input class="btn btn-default" type="submit" value="Save" />
<a class="btn btn-default" href={% url "sites-index" %}>Cancel</a>
</div>
</form>
</div>
</div>
{{ form.errors }}
{% endblock %}
{% block sidebar %}
{% include "afp-sidebar.html" %}
{% endblock %}
if request.POST: should be if request.method == 'POST':
Related
who can explain me why my SearchView doesn't work. I have some code like this.It doesn't show me any mistakes, but it doesn't work. The page is clear. Seems like it doesn't see the input.
search.html
<div class="justify-content-center mb-3">
<div class="row">
<div class="col-md-8 offset-2">
<form action="{% url 'search' %}" method="get">
<div class="input-group">
<input type="text" name="q" class="form-control" placeholder="Search..." />
<div class="input-group-append">
<button class="btn btn-dark" type="submit" id="button-addon2">Search</button>
</div>
</div>
</form>
</div>
</div>
</div>
search/urls.py
path('search/', SearchView.as_view(), name='search')
search/views.py
class SearchView(ListView):
model = Question
template_name = 'forum/question_list.html'
def get_queryset(self):
query = self.request.GET.get("q")
object_list = Question.objects.filter(
Q(title__icontains=query) | Q(detail__icontains=query)
)
return object_list
forum/question_list.html
{% extends 'main/base.html' %}
{% block content %}
{% for question in object_list %}
<div class="card mb-3">
<div class="card-body">
<h4 class="card-title">{{ question.title }}</h4>
<p class="card-text">{{ question.detail }}</p>
<p>
{{ question.user.username }}
5 answers
10 comments
</p>
</div>
</div>
{% endfor %}
{% endblock %}
I would like to customize the Django login authentication form. The original form looks like this and it works perfectly:
{% extends "blog/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4 ">Log In</legend>
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Login</button>
</div>
</form>
<div class="border-top pt-3">
<small class="text-muted">
Need An Account? <a class="ml-2" href="{% url 'register' %}">Sign Up Now</a>
</small>
</div>
</div>
{% endblock content %}
My goal is to modify the form style so that I can place the objects wherever I want. I was able to achieve this for the username and password fields, however I cannot display the error message just like in the original format.
This is what I tried:
{% extends "blog/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4 ">Log In</legend>
{% if formset.non_form_errors %}
<div class="alert alert-block alert-danger">
{% if formset_error_title %}<h4 class="alert-heading">{{ formset_error_title }}</h4>{% endif %}
<ul class="m-0">
{{ formset.non_form_errors|unordered_list }}
</ul>
</div>
{% endif %}
<div class="row">
<div class="col-md-4 col-sm-12 register-field">
{{ form.username|as_crispy_field }}
</div>
<div class="col-sm-12 register-field">
{{ form.password|as_crispy_field }}
</div>
</div>
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Login</button>
</div>
</form>
<div class="border-top pt-3">
<small class="text-muted">
Need An Account? <a class="ml-2" href="{% url 'register' %}">Sign Up Now</a>
</small>
</div>
</div>
{% endblock content %}
Basically I saw that crispy uses a object called formset.non_form_errorshowever it looks like it is not working when I insert an invalid username/password.
Would you be able to suggest a smart and elegant way to achieve my goal please? This is what it should look like:
I was able to achieve my goal with this trick:
{% extends "blog/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4 ">Log In</legend>
<div class="row">
<!-- Added this new rows -->
{% if form.errors %}
<div class="col-12 register-field">
<div class="alert alert-block alert-danger">
<ul>
<li>Please enter a correct username and password. Note that both fields may be
case-sensitive.
</li>
</ul>
</div>
</div>
{% endif %}
<!-- ------------------- -->
<div class="col-md-4 col-sm-12 register-field">
{{ form.username|as_crispy_field }}
</div>
<div class="col-sm-12 register-field">
{{ form.password|as_crispy_field }}
</div>
</div>
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Login</button>
</div>
</form>
<div class="border-top pt-3">
<small class="text-muted">
Need An Account? <a class="ml-2" href="{% url 'register' %}">Sign Up Now</a>
</small>
</div>
</div>
{% endblock content %}
Basically I check if there are any errors and then I create a div with the custom error message.
I want to hide the field form.name_of_parent_if_minor if the age (CharField) < 18 else show. I am not getting where to write jQuery or JS code or add separate js file. For this do I need to the html definition and add tag for age (CharField) or we can perform action on this as well.
I am new to the Django so if you find any mistakes in my code then any help would be appreciated for guidance.
forms.py
class StudentDetailsForm(forms.ModelForm):
class Meta:
model = StudentDetails
views.py
class StudentCreateView(LoginRequiredMixin, CreateView):
template_name = 'student/student_details_form.html'
model = StudentDetails
form_class = StudentDetailsForm
success_url = "/"
html
{% extends 'student/base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<div id="idParentAccordian" class="content-section">
<form method="POST">
{% csrf_token %}
<div class="card mt-3">
<div class="card-header">
<a class="collapsed card-link" style="display: block;" data-toggle="collapse"
href="#idPersonalInformation">Personal Information</a>
</div>
<div id="idPersonalInformation" class="collapse show" data-parent="#idParentAccordian">
<div class="card-body">
<div class="row">
<div class="col-6">
{{ form.joining_date|as_crispy_field }}
</div>
<div class="col-6">
{{ form.class|as_crispy_field }}
</div>
</div>
{{ form.student_name|as_crispy_field }}
{{ form.father_name|as_crispy_field }}
{{ form.mother_name|as_crispy_field }}
{{ form.gender|as_crispy_field }}
<div class="row">
<div class="col-6">
{{ form.date_of_birth|as_crispy_field }}
</div>
<div class="col-6">
{{ form.age|as_crispy_field }}
</div>
</div>
<div>
{{ form.name_of_parent_if_minor|as_crispy_field }}
</div>
</div>
</div>
</div>
<div class="form-group mt-3">
<button class="btn btn-outline-info" type="submit">Save</button>
<a class="btn btn-outline-secondary" href="javascript:history.go(-1)">Cancel</a>
</div>
</form>
</div>
{% endblock content %}
the easiest way but not the cleanest is to add JS script in your html
the recommanded way is to add static folder to your app and load static files in your html template using {% load static %}
I have created a template for displaying a photo gallery and giving users the ability to add photos to that gallery:
{% extends 'nowandthen/base.html' %}
{% block body_block %}
<br>
<br>
{% if pictures %}
<ul>
{% for p in pictures %}
<div class="container">
<div class="row">
<div class="col-md-8 card mb-4 mt-3 ">
<!-- Card -->
<!-- Card content -->
<div class="card-body d-flex flex-row">
<!-- Content -->
<div>
<!-- Title -->
<h4 class="card-title font-weight-bold mb-2">{{ p.title }}</h4>
<!-- Subtitle -->
<p class="card-text"><i class="far fa-clock pr-2"></i>{{ p.when_added }}</p>
</div>
</div>
<!-- Card image -->
<div class="view overlay">
<img class="card-img-top rounded-0" src="{{ p.image.url }}" alt="Card image cap">
<a href="#!">
<div class="mask rgba-white-slight"></div>
</a>
</div>
<!-- Card content -->
<div class="card-body">
<div class="collapse-content">
<!-- Text -->
<p class="card-text collapse" id="collapseContent">{{ p.description }}</p>
<!-- Button -->
<a class="btn btn-flat red-text p-1 my-1 mr-0 mml-1 collapsed" data-toggle="collapse" href="#collapseContent" aria-expanded="false" aria-controls="collapseContent">Click for description</a>
<i class="fas fa-share-alt text-muted float-right p-1 my-1" data-toggle="tooltip" data-placement="top" title="Share this post"></i>
<i class="fas fa-heart text-muted float-right p-1 my-1 mr-3" data-toggle="tooltip" data-placement="top" title="I like it"></i>
</div>
</div>
<div class="card-body">
<!-- comments -->
<h2>comments</h2>
{% if not p.comments %}
No comments
{% endif %}
{% for x in p.comment %}
<div class="comments" style="padding: 10px;">
<p class="font-weight-bold">
<h4>Comment by</h4> {{ x.user }}
<span class=" text-muted font-weight-normal">
{{ x.created_on }}
</span>
</p>
{{ x.body | linebreaks }}
</div>
{% endfor %}
</div>
<div class="card-body">
{% if new_comment %}
<h2>Your comment has been posted.</h2>
{% else %}
<h3>Leave a comment</h3>
<form action="{% url 'nowandthen:add_comment' p.image_id %}" method="POST">
{{ comment_form.as_p }}
{% csrf_token %}
<button type="submit" class="btn btn-primary btn-lg">Submit</button>
{% endif %}
</div>
</div>
</div>
</div>
<!-- Card -->
{% endfor %}
</ul>
{% else %}
<li><strong>There are no photographs present.</strong></li>
{% endif %}
{% endblock %}
The idea is that there is an image associated with each comment - there is a for loop of {% for p in pictures %} at the start of the page, and I use variations of p. (e.g. p.image_id) to associate particular pictures with particular comments.
In addition, the urls.py contains the following:
path('add_comment/<int:p.image_id>', views.add_comment, name='add_comment')
However, when I run the code, I get an error message that suggests that image ids aren't being created (even though image is a field in he Pictures model I created):
Reverse for 'add_comment' with arguments '('',)' not found. 1 pattern(s) tried: ['add_comment/$']
What do you suggest, please?
EDIT: This is my view:
#login_required
def add_comment(request, image_id):
new_comment = None
template_name = 'add_comment.html'
image = get_object_or_404(Picture, id=image_id)
comment = image.comments.filter(active=True)
new_comment = None
# Comment posted
if request.method == 'POST':
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
# Create Comment object and don't save to database yet
new_comment = comment_form.save(commit=False)
# Assign the current post to the comment
new_comment.post = post
# Save the comment to the database
new_comment.save()
else:
comment_form = CommentForm()
context = {'image': image,'comment': comment, 'new_comment': new_comment,'comment_form': comment_form}
return render(request, template_name, context)
And this is my add_comment.html template:
{% extends 'nowandthen/base.html' %}
{% load staticfiles %}
{% block title_block %}
Add self
{% endblock %}
{% block body_block %}
<h1>Add a Comment</h1>
<div>
<form id="comment_form" method="post" action="{% url 'nowandthen:add_comment' comment_id%}" enctype="multipart/form-data" >
{% csrf_token %}
{{ form.as_p }}
<input type="submit" name="submit" value="Add Comment" />
</form>
</div>
{% endblock %}
Since you pictures variable is a Queryset, when you loop through it in your template, to access its ID, you just need to do it that way. instance.id
Based on your case, you will have:
{% url 'nowandthen:add_comment' p.id %}
And you will be able to access the id in your view with image_id
I have custom registration form with my own registration view. I've started to using django-allauth recently and I would like to add email confirmation to my registration. Is it possible?
registration view:
def registration(request):
user_creation_form = UserProfileCreationForm(request.POST or None)
if request.method == 'POST':
if user_creation_form.is_valid():
user_creation_form.save()
username = user_creation_form.cleaned_data['username']
password = user_creation_form.cleaned_data['password2']
user = authenticate(username=username, password=password)
login(request, user)
messages.add_message(request, messages.SUCCESS, YOU_HAVE_BEEN_REGISTERED)
return HttpResponseRedirect(reverse('homepage'))
return render(request, 'dolava/accounts/registration.html',
context={'user_creation_form': user_creation_form})
This is how rewrite allauth templates:
in SETTINGS.PY
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
TEMPLATE_DIRS = (os.path.join(BASE_DIR, 'templates','allauth'),)
main app templates:
templates/account/password_reset.html (overriden allauth templates)
The problem is that I want to have many fields in registration template like type_of_user, telephone etc.
registration.html:
{% extends 'base.html' %}
{% load static %}
{% block head %}
<script src="{% static "js/registrationToggleFields.js" %}"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#id_country').select2();
$('#id_telephone_0').select2();
});
</script>
{% endblock %}
{% block content %}
<div class="col-md-12 text-center">
<h2>Register your account</h2>
<hr class="col-md-12 blackhr no-bottom-margin">
</div>
{# <div class="col-md-12 text-center center-block">#}
<form action="" method="post" class="col-md-6 col-md-offset-3" id="register-form">
{% csrf_token %}
{{ user_creation_form.non_field_errors }}
<div id="form-account-type">
<h3 align="center" class="main-color">Account Type</h3>
<hr>
{# <div class="col-md-12">#}
<div id="type-of-user-field-wrapper" class="fieldWrapper">
<div>
<label for="{{ user_creation_form.type_of_user.id_for_label }}">Type of user:</label>
{% if user_creation_form.type_of_user.field.required %} * {% endif %}
</div>
{{ user_creation_form.type_of_user }}
{{ user_creation_form.type_of_user.errors }}
</div>
<div id="country-field-wrapper" class="fieldWrapper">
<label for="{{ user_creation_form.country.id_for_label }}">Country:</label>
{% if user_creation_form.country.field.required %} * {% endif %}
<br>
{{ user_creation_form.country }}
{{ user_creation_form.country.errors }}
</div>
{# </div>#}
<hr>
</div>
<div id="form-login-credentials" class="form-group-container show-allways">
<h3 align="center" class="main-color">Credentials</h3>
<hr>
<div>
<div id="username-field-wrapper" class="fieldWrapper">
<label for="{{ user_creation_form.username.id_for_label }}">Username:</label>
{% if user_creation_form.username.field.required %} * {% endif %}
<br>
{{ user_creation_form.username }}
{{ user_creation_form.username.errors }}
</div>
<div id="password1-field-wrapper" class="fieldWrapper">
<label for="{{ user_creation_form.password1.id_for_label }}">Password:</label>
{% if user_creation_form.password1.field.required %} * {% endif %}
<br>
{{ user_creation_form.password1 }}
{{ user_creation_form.password1.errors }}
</div>
<div id="password2-field-wrapper" class="fieldWrapper">
<label for="{{ user_creation_form.password2.id_for_label }}">Confirm your password:</label>
{% if user_creation_form.password2.field.required %} * {% endif %}
<br>
{{ user_creation_form.password2 }}
{{ user_creation_form.password2.errors }}
</div>
</div>
<hr>
</div>
<div id="form-personal-information" class="form-group-container show-personal">
<h3 align="center" class="main-color">Personal information</h3>
<hr>
<div>
<div id="first-name-field-wrapper" class="fieldWrapper">
<label for="{{ user_creation_form.first_name.id_for_label }}">First name:</label>
{% if user_creation_form.first_name.field.required %} * {% endif %}
<br>
{{ user_creation_form.first_name }}
{{ user_creation_form.first_name.errors }}
</div>
<div id="last-name-field-wrapper" class="fieldWrapper">
<label for="{{ user_creation_form.last_name.id_for_label }}">Last name:</label>
{% if user_creation_form.last_name.field.required %} * {% endif %}
<br>
{{ user_creation_form.last_name }}
{{ user_creation_form.last_name.errors }}
</div>
</div>
<hr>
</div>
<div id="form-company-information" class="form-group-container show-company-sk show-company">
<h3 align="center" class="main-color">Company information</h3>
<hr>
<div>
<div id="company-name-field-wrapper" class="fieldWrapper">
<label for="{{ user_creation_form.company_name.id_for_label }}">Company name:</label>
{% if user_creation_form.company_name.field.required %} * {% endif %}
<br>
{{ user_creation_form.company_name }}
{{ user_creation_form.company_name.errors }}
</div>
<div id="address-field-wrapper" class="fieldWrapper">
<label for="{{ user_creation_form.address.id_for_label }}">Address:</label>
{% if user_creation_form.address.field.required %} * {% endif %}
<br>
{{ user_creation_form.address }}
{{ user_creation_form.address.errors }}
</div>
</div>
<hr>
</div>
<div id="form-billing-information" class="form-group-container show-company-sk">
<h3 align="center" class="main-color">Billing information</h3>
<hr>
<div>
<div id="ico-field-wrapper" class="fieldWrapper">
<label for="{{ user_creation_form.ICO.id_for_label }}">IČO:</label>
{% if user_creation_form.ICO.field.required %} * {% endif %}
<br>
{{ user_creation_form.ICO }}
{{ user_creation_form.ICO.errors }}
</div>
<div id="dic-field-wrapper" class="fieldWrapper">
<label for="{{ user_creation_form.DIC.id_for_label }}">DIČ:</label>
{% if user_creation_form.DIC.field.required %} * {% endif %}
<br>
{{ user_creation_form.DIC }}
{{ user_creation_form.DIC.errors }}
</div>
</div>
<hr>
</div>
<div id="form-contact-information" class="form-group-container show-allways">
<h3 align="center" class="main-color">Contact information</h3>
<hr>
<div>
<div id="email-field-wrapper" class="fieldWrapper">
<label for="{{ user_creation_form.email.id_for_label }}">Email:</label>
{% if user_creation_form.email.field.required %} * {% endif %}
<br>
{{ user_creation_form.email }}
{{ user_creation_form.email.errors }}
</div>
<div id="telephone-field-wrapper" class="fieldWrapper">
<label for="{{ user_creation_form.telephone.id_for_label }}">Telephone:</label>
{% if user_creation_form.telephone.field.required %} * {% endif %}
<br>
{{ user_creation_form.telephone }}
{{ user_creation_form.telephone.errors }}
</div>
<div id="fax-field-wrapper" class="fieldWrapper">
<label for="{{ user_creation_form.fax.id_for_label }}">Fax:</label>
{% if user_creation_form.fax.field.required %} * {% endif %}
<br>
{{ user_creation_form.fax }}
{{ user_creation_form.fax.errors }}
</div>
</div>
</div>
<div class=" clearfix top-margin">
<button class="btn btn-success center-block" style="width:100%; padding: 15px 0;" type="submit">
Register
</button>
</div>
</form>
{# </div>#}
{% endblock %}
Do you have any advices?
You have to override one class and then supply all required variables to thhe specific template. The view that returns confirmation_email is ConfirmEmailView of allauth/account/views.py override this class, pass all the required variables from view to the template and then override your template account/email_confirm to show required data.