Django is not loading template form - django

I don't know why is not loading the template but every time I click in an url the page auto-reload and not load the template, here is my code:
urls.py
url(r'^pedidos/add',forms.PedidoCreateView.as_view(), name="pedido_add")
forms.py
class PedidoCreateView(CreateView):
template_name = 'ventas/form_pedido.html'
model = Pedido
form_class = PedidoModelForm
success_url = 'ventas/pedidos.html'
def form_valid(self, form):
form.save(commit=True)
return super(PedidoCreateView, self).form_valid(form)
form_pedido.html
{% extends '_layouts/base.html' %}
{% load url from future %}
{% block breadcrumb%}
<li>
Pedidos
<span class="divider">
<i class="icon-angle-right"></i>
</span>
</li>
<li class="active">Nuevo Pedido</li>
{% endblock %}
{% block page_content %}
<form class ="form" id="form" method="POST" action="{{ request.path }}">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3>Editar Empleado</h3>
</div>
<div class="modal-body">
{% csrf_token %}
{{ form.non_field_errors }}
{{ form_errors }}
{{form.as_p}}
</div>
<div class="modal-footer">
Cerrar
<input type="submit" class="guardar btn btn-primary" value="Guardar">
</div>
</form>
{% endblock %}
{% block scripts %}
{% endblock %}
link
<a href="{% url 'ventas:pedido_add' %}" class="btn btn-app btn-success">
For sure has to be some error that I'm not able to see now, I prove with other similar views and I don't have any problems, what could it be?

Related

Image ids apparently not being created

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

Django : How can I update my views? url problem

Like below code, I made update view but it doesn't work. after I click the , it doesn't work an just
"GET /moneylogs/update/7/ HTTP/1.1" 200 6243
console log printed. the page remain like just refresh.
How can I update my moneylog?
views.py
class moneylog_update(UpdateView):
model = moneylog_models.Moneylog
form_class = forms.UpdateMoneylogForm
template_name = "moneylogs/update.html"
def form_valid(self, form):
moneylog = form.save(commit=False)
moneybook = moneybook_models.Moneybook.objects.get(
pk=self.kwargs["pk"])
moneylog.save()
form.save_m2m()
return redirect(reverse("moneybooks:detail", kwargs={'pk': moneybook.pk}))
urls.py
app_name = "moneylogs"
urlpatterns = [
path("create/<int:pk>/",
views.moneylog_create.as_view(), name="create"),
path("update/<int:pk>/",
views.moneylog_update.as_view(), name="update"),
path("<int:moneybook_pk>/delete/<int:moneylog_pk>/",
views.moneylog_delete, name="delete"),
]
moneylog_form_update.html
<div class="input {% if field.errors %}has_error{% endif %}">
<div class="flex">
<div class="w-1/4">
{{form.memo.label}}
</div>
<div class="w-3/4 border-b my-2 py-3">
{{form.memo}}
</div>
</div>
{% if form.memo.errors %}
{% for error in form.memo.errors %}
<span class="text-red-700 font-medium text-sm">{{error}}</span>
{% endfor %}
{% endif %}
</div>
<a href="{% url 'moneylogs:update' moneylog.pk %} ">
<div class="px-2 py-1 rounded bg-red-500 text-white">{{cta}}</div>
</a>
Since Update view processes the form on a post request, you need HTML form with post request to submit your data.
<form method="post" action="{% url 'moneylogs:update' moneylog.pk %}">
<div class="input {% if field.errors %}has_error{% endif %}">
<div class="flex">
<div class="w-1/4">
{{form.memo.label}}
</div>
<div class="w-3/4 border-b my-2 py-3">
{{form.memo}}
</div>
</div>
{% if form.memo.errors %}
{% for error in form.memo.errors %}
<span class="text-red-700 font-medium text-sm">{{error}}</span>
{% endfor %}
{% endif %}
</div>
<input type="submit" value="{{cta}}" />
</form>
<a></a> will hit the server using the GET request.

Django page navigation- home list not visible

I am super new to Dango; pardon me for a rookie question :)
I am learning Django by creating a "Note taking app". This is how the application home page looks.
When I click on any of the notes from the note list, it opens the details on the right-side page. But the problem is it wipes-out the left-hand side note list. To reload the list I need to click on the Home link again. The expected behavior is, it should retain the note-list on the left side as well as show the details on the right frame.
urls.py
from django.urls import path
from .views import NoteListView, NoteDetailView, NoteCreateView, NoteUpdateView, NoteDeleteView
from . import views
urlpatterns = [
path('', NoteListView.as_view(), name='lekha-home'),
path('note/<int:pk>/', NoteDetailView.as_view(), name='note-detail'),
path('note/new/', NoteCreateView.as_view(), name='note-create'),
path('note/<int:pk>/update', NoteUpdateView.as_view(), name='note-update'),
path('note/<int:pk>/delete', NoteDeleteView.as_view(), name='note-delete'),
path('about/', views.about, name='lekha-about'),
]
enter code here
views.py
class NoteListView(ListView):
model = Note
template_name = 'lekha/home.html'
context_object_name = 'notes'
ordering = ['-date_created']
class NoteDetailView(DetailView):
model = Note
# success_url = 'lekha/note_detail.html'
class NoteCreateView(LoginRequiredMixin, CreateView):
model = Note
fields = ['title', 'content']
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
home.html
{% extends "lekha/base.html" %}
{% block content %}
{% for note in notes %}
<div class="list-group">
{{ note.title }}
</div>
{% endfor %}
{% endblock content %}
note_detail.html
{% extends "lekha/base.html" %}
{% block content2 %}
<article class="media content-section">
<div class="media-body">
<div class="article-metadata">
<a class="mr-8" href="#">{{ object.author }}</a>
<small class="text-muted">{{ object.date_created|date:"F d, Y" }}</small>
{% if object.author == user %}
<a class="btn float-right btn-secondary ml-1 btn-sm" href="{% url 'note-update' object.id %} ">Update</a>
<a class="btn float-right btn-danger ml-1 btn-sm" href="{% url 'note-delete' object.id %} ">Delete</a>
{% endif %}
</div>
<h4 class="article-title">{{ object.title }}</h4>
<hr>
<p class="article-content">{{ object.content }}</p>
</div>
</article>
{% endblock content2 %}
And this is how I am calling it in base.html
<main role="main" class="container-fluid px-2">
<div class="row">
<div class="col-md-3">
<div class="content-section">
<h4>Notes</h4>
{% block content %}{% endblock %}
</div>
</div>
<div class="col-md-8">
{% block content2 %}{% endblock %}
</div>
</div>
</main>
Sorry for the detailed post. I would appreciate any pointers. Thanks!
Welcome to Django!
Your template note_detail.html extends base.html, which doesn't contain the HTML for the list of notes, and note_detail.html doesn't add the list, so that's why it's not showing up - you haven't added it!
To do this, you need the same {% block content %} from home.html in note_detail.html, and you also need to manually pass a notes context variable to the template. You get that for free with the ListView class.
First, the change to the template:
note_detail.html
{% extends "lekha/base.html" %}
{% block content %}
{% for note in notes %}
<div class="list-group">
{{ note.title }}
</div>
{% endfor %}
{% endblock content %}
{% block content2 %}
<article class="media content-section">
<div class="media-body">
<div class="article-metadata">
<a class="mr-8" href="#">{{ object.author }}</a>
<small class="text-muted">{{ object.date_created|date:"F d, Y" }}</small>
{% if object.author == user %}
<a class="btn float-right btn-secondary ml-1 btn-sm" href="{% url 'note-update' object.id %} ">Update</a>
<a class="btn float-right btn-danger ml-1 btn-sm" href="{% url 'note-delete' object.id %} ">Delete</a>
{% endif %}
</div>
<h4 class="article-title">{{ object.title }}</h4>
<hr>
<p class="article-content">{{ object.content }}</p>
</div>
</article>
{% endblock content2 %}
And the change to the view:
views.py
class NoteListView(ListView):
model = Note
template_name = 'lekha/home.html'
context_object_name = 'notes'
ordering = ['-date_created']
class NoteDetailView(DetailView):
model = Note
def get_context_data(self):
data = super().get_context_data
data['notes'] = Note.objects.all().order_by('-date_created')
One last tip: to keep your HTML templates "DRY," you should really extract the list of notes into a separate html template (often called a partial) that you can plug into multiple other templates. Your template setup would look like this:
partials/all_notes.html
{% for note in notes %}
<div class="list-group">
{{ note.title }}
</div>
{% endfor %}
home.html
{% extends "lekha/base.html" %}
{% block content %}
{% include 'lekha/partials/all_notes.html' %}
{% endblock content %}
note_detail.html
{% extends "lekha/base.html" %}
{% block content %}
{% include 'lekha/partials/all_notes.html' %}
{% endblock content %}
{% block content2 %}
<article class="media content-section">
<div class="media-body">
<div class="article-metadata">
<a class="mr-8" href="#">{{ object.author }}</a>
<small class="text-muted">{{ object.date_created|date:"F d, Y" }}</small>
{% if object.author == user %}
<a class="btn float-right btn-secondary ml-1 btn-sm" href="{% url 'note-update' object.id %} ">Update</a>
<a class="btn float-right btn-danger ml-1 btn-sm" href="{% url 'note-delete' object.id %} ">Delete</a>
{% endif %}
</div>
<h4 class="article-title">{{ object.title }}</h4>
<hr>
<p class="article-content">{{ object.content }}</p>
</div>
</article>
{% endblock content2 %}
base.html
<main role="main" class="container-fluid px-2">
<div class="row">
<div class="col-md-3">
<div class="content-section">
<h4>Notes</h4>
{% block content %}{% endblock %}
</div>
</div>
<div class="col-md-8">
{% block content2 %}{% endblock %}
</div>
</div>
</main>

django-formtools, saving data between form steps

I am trying to create a multi-step form wizard using django-formtools. I have a main model called Report and several ModelForms as follows:
class ReportFormP1(forms.ModelForm):
class Meta:
model = Report
fields = [
'company',
'address_line_1',
'address_line_2',
'responsible_person',
'person_consulted',
'assessor_name',
'previous_assessment_date',
'review_date',
]
# section 1
class ReportFormP2(forms.ModelForm):
class Meta:
model = Report
fields = [
"premise_num_floors",
"premise_floor_area",
"premise_occupancy",
"premise_occupancy_comments",
]
in my views, I have created the following view:
class ReportWizardView(SessionWizardView):
template_name = 'reporting/report_create2.html'
form_list = [ReportFormP1, ReportFormP2]
def done(self, form_list, **kwargs):
return render(self.request, 'done.html', {
'form_data': [form.cleaned_data for form in form_list],
})
And my relevant template looks as follows:
{% extends '_base.html' %}
{% load static %}
{% load i18n %}
{% load crispy_forms_tags %}
<!-- templates/home.html -->
{% load socialaccount %}
{% block title %}Create a report{% endblock title %}
{% block extra_css %}
{{ wizard.form.media }}
{% endblock extra_css %}
{% block content %}
<div class="container">
<h1>Create a report</h1>
<p>Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}</p>
<form action="" method="post">
{% csrf_token %}
{{ wizard.management_form }}
{% if wizard.form.forms %}
{{ wizard.form.management_form }}
{% for form in wizard.form.forms %}
{{ form|crispy }}
{% endfor %}
{% else %}
{{ wizard.form|crispy }}
{% endif %}
<div class="text-center">
{% if wizard.steps.prev %}
<button class="btn btn-lg btn-warning" name="wizard_goto_step" type="submit" value="{{ wizard.steps.first }}" formnovalidate>{% trans "first step" %}</button>
<button class="btn btn-lg btn-primary" name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}" formnovalidate>{% trans "prev step" %}</button>
{% endif %}
{% if wizard.steps.next %}
<button class="btn btn-lg btn-primary" name="wizard_goto_step" type="submit" value="{{ wizard.steps.next }}">{% trans "next step" %}</button>
{% endif %}
<input class="btn btn-lg btn-success" type="submit" name="Submit" value="Create report">
</div>
</form>
<hr>
<hr>
</div>
{% endblock content %}
My urls.py look as follows:
path('create_report2', ReportWizardView.as_view(), name="report_create2"),
My problem is that the form steps are not being saved when I click on next, and then previous (the form is valid). Bellow is an example
First form loaded:
(source: imge.to)
After clicking on 'next':
(source: imge.to)
Now when i click on 'previous', everything is gone:
(source: imge.to)
I wonder what I have missed?
As per Formtools documentation you need to Enable Session.
https://django-formtools.readthedocs.io/en/latest/wizard.html#formtools.wizard.views.SessionWizardView

Doesn't populate fields with existing data

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':