BootstrapError: Parameter "form" should contain a valid Django Form - django

I keep getting the above error (in the title) for my DeleteView.
Strangely my UpdateView, UpdateObject form and update_object template are identical to my DeleteView, DeleteObject form and delete_object template respectively. I'm not sure why bootstrap is giving me an error for this form and not my update form?
Here are the files:
forms.py:
from django import forms
from . import models
from django.forms import ModelForm
class CreateBouquetForm(ModelForm):
class Meta:
model = models.Bouquet
exclude = ('price',)
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
class UpdateBouquetForm(ModelForm):
class Meta:
model = models.Bouquet
exclude = ('price',)
class DeleteBouquetForm(ModelForm):
class Meta:
model = models.Bouquet
exclude = ('price',)
`
views.py:
class UpdateBouquet(UpdateView):
model = models.Bouquet
form_class = forms.UpdateBouquetForm
template_name = 'products/update_bouquet.html'
success_url = reverse_lazy('products:shop')
def form_valid(self,form):
self.object = form.save(commit=False)
result = 0
for flower in self.object.flower.all():
result += flower.price
self.object.price = result
self.object.save()
return super().form_valid(form)
class DeleteBouquet(DeleteView):
model = models.Bouquet
form_class = forms.DeleteBouquetForm
template_name = 'products/delete_bouquet.html'
success_url = reverse_lazy('products:shop')
products/update_bouquet.html:
{% extends 'site_base.html' %}
{% load bootstrap3 %}
{% block content_block %}
<form method="post">
{% csrf_token %}
{% bootstrap_form form %}
<input type="submit" class="btn btn-outline-success" value="Save bouquet and continue shopping">
</form>
<h6>Back to bouquet</h6>
{% endblock %}
products/delete_bouquet.html:
{% extends 'site_base.html' %}
{% load bootstrap3 %}
{% block content_block %}
<h5>Are you sure you want to delete your bouquet?</h5>
<form method="POST">
{% csrf_token %}
{% bootstrap_form form %}
<input type="submit" class="btn btn-outline-success" value="Delete">
</form>
<h6><a class="btn btn-outline-danger" href="{% url 'products:detail_bouquet' pk=bouquet.pk %}">Cancel</a></h6>
{% endblock %}
urls.py:
url(r'^bouquet/(?P<pk>\d+)/update/$',views.UpdateBouquet.as_view(),name="update_bouquet"),
url(r'^bouquet/(?P<pk>\d+)/delete/$',views.DeleteBouquet.as_view(),name="delete_bouquet"),
Here's what the error page says:
Error during template rendering
In template C:\Users\joann\Desktop\Flowers_Storefront\storefront\templates\site_base.html, error at line 8
Parameter "form" should contain a valid Django Form.
1 <!DOCTYPE html>
2 {% load static %}
3 {% load bootstrap3 %}
4 <html lang="en" dir="ltr">
5 <head>
6 <meta charset="utf-8">
7 <title></title>
8 <link href="https://cdn.jsdelivr.net/**npm/bootstrap#5.0.0-beta1/dist/css/boo**tstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
9 <link rel="stylesheet" href="{% static "/css/css_master.css" %}">
10 <link rel="preconnect" href="https://fonts.gstatic.com">
11 class="container-fluid">
...etc....
Thanks in advance if you can help!

DeleteView does not do any form handling and so does not add a "form" key to the context. Remove form_class from your view and remove the bootstrap_form tag from your template
class DeleteBouquet(DeleteView):
model = models.Bouquet
template_name = 'products/delete_bouquet.html'
success_url = reverse_lazy('products:shop')
{% extends 'site_base.html' %}
{% block content_block %}
<h5>Are you sure you want to delete your bouquet?</h5>
<form method="POST">
{% csrf_token %}
<input type="submit" class="btn btn-outline-success" value="Delete">
</form>
<h6><a class="btn btn-outline-danger" href="{% url 'products:detail_bouquet' pk=bouquet.pk %}">Cancel</a></h6>
{% endblock %}

Related

How to use a function in another class and modify it Django

Sup, need to use a function in a different class without losing the model, while still being able to change the function(not important, I can rewrite func into more flexible func). Can't solve this issue at least 10 hours. Google didnt help =( I know code is a little dirty, I will clean that :D
Don't worry
I have same header with form and another form in all pages.
Need form from class head in class stockpage. And everyone template and future classes as well.
Views
class head(View):
template_name = "dental/mainpage.html"
model = signup
def get(self,request):
if request.method == 'GET':
form = UserSign
return render(request, "dental/mainpage.html", {"form": form})
def FormSign(self,request):
if request.method == 'POST':
form = UserSign
if form.is_valid():
body = {
'Name': form.cleaned_data['Name'],
'email': form.cleaned_data['email'],
'Number': form.cleaned_data['Number'],
}
info_user = "\n".join(body.values())
send_mail(
'Sign',
info_user,
'eric1122221#mail.ru',
['eric1122221#mail.ru'],
fail_silently=False)
return render(request, "dental/mainpage.html", {"form": form}) #self.template_name
return render(request, "dental/mainpage.html", {"form": form})
class stockpage(ListView):
template_name = "dental/stocks.html"
model = stock
context_object_name = "stocks"
HTML
signuphtml
{% load static %}
{%block css_files %}
<link rel="stylesheet" href="{% static "signup.css" %}">
{% endblock %}
{% block content %}
<section id="forms">
<form action="" method="post">
{% csrf_token %}
<div id="txt" class="form-control {% if form.errors %}invalid{% endif %}">
{{ form.label_tag }}
{{ form }}
{{ form.errors }}
</div>
<div id="buttsig">
<button id="b4" type="submit">записаться</button>
</div>
</form>
</section>
{% endblock content %}
mainpage.html
{% extends 'main.html' %}
{% load static %}
{%block css_files %}
<link rel="stylesheet" href="{% static "header.css" %}">
<link rel="stylesheet" href="{% static "mainpage.css" %}">
<link rel="stylesheet" href="{% static "signup.css" %}">
<link rel="stylesheet" href="{% static 'assets/css/bootstrap.css' %}">
{% endblock %}
{% block title %}{% endblock %}
{% block content %}
{% include "dental/includes/header.html" %}
<div ="d1">
<ul>
<li>blabla</li>
<li>blabla</li>
<li>blabla</li>
<li>blabla</li>
</ul>
</div>
{% include "dental/includes/signup.html" %}
{% include "dental/includes/tail.html" %}
{% endblock content %}
stocks html
{% extends 'main.html' %}
{% load static %}
{%block css_files %}
<link rel="stylesheet" href="{% static "header.css" %}">
<link rel="stylesheet" href="{% static "mainpage.css" %}">
<link rel="stylesheet" href="{% static "signup.css" %}">
<link rel="stylesheet" href="{% static 'assets/css/bootstrap.css' %}">
<link rel="stylesheet" href="{% static "stocks.css" %}">
{% endblock %}
{% block title %}{% endblock %}
{% block content %}
{% include "dental/includes/header.html" %}
<section id="contentstock">
{% for stock in stocks %}
<li>
<h4>{{ stock.title }}</h4>
<img src="{{ stock.image.url }}" alt="{{ stock.image }}"/>
<h4>{{ stock.content|linebreaks}}</p>
</li>
{% endfor %}
</section>
{% include "dental/includes/signup.html" %}
{% include "dental/includes/tail.html" %}
{% endblock content %}
Try adding separate view for handling the form with hidden field for url to redirect to. Django's default auth views work like this. Also custom context processor may help to provide the form for all pages without overriding all their get or get_context_data methods.
Consider the example:
forms.py:
class MyForm(forms.Form):
next_url = forms.CharField(widget=forms.HiddenInput, required=False)
name = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput)
context_processors.py:
def my_form_context_processor(request):
my_form = MyForm()
my_form.fields['next_url'].initial = request.get_full_path()
return {'my_form': my_form}
settings.py:
TEMPLATES = [
{
...
'OPTIONS': {
'context_processors': [
...
'my_app.context_processors.my_form_context_processor',
],
},
},
]
views.py:
class MyFormView(FormView):
form_class = MyForm
template_name = 'my_form.html'
def form_valid(self, form):
# ...
next_url = form.cleaned_data.get('next_url')
if not next_url:
next_url = reverse('my_app:home') # default
return HttpResponseRedirect(next_url)
class ViewA(TemplateView):
template_name = 'template_a.html'
class ViewB(TemplateView):
template_name = 'template_b.html'
template_a.html:
{% include "my_form.html" %}
<h1>A</h1>
template_b.html:
{% include "my_form.html" %}
<h1>B</h1>
my_form.html:
<form action="{% url 'my_app:my_form' %}" method="POST">
{% csrf_token %}
{{ my_form.as_p }}
<p><input type="submit" value="Go!"></p>
</form>

GCBV Generic Class Based View, Django Classes Issue

$ Hello, I was trying to use "GCBV Generic Class Based View" for edit a post, but it seems not working and event it django can't find my HTML and I don't know why , Hope I get some support ….
$ edit button link
{% if post.created_by == user %}
<div class="mt-3">
<a class="btn btn-success float-end"
href="{% url 'edit_post' post.topic.board.pk post.topic.pk post.pk %}">Edit</a>
</div>
{% endif %}
$ edit HTML Page
{% extends 'base.html' %}
{% load static %}
{% block title %}Edit Post{% endblock %}<!-- | Page-title-->
{% block content %}
<link rel="stylesheet" href="{% static 'css/boards.css' %}">
<div class="newtopic">
<div class="container container-newtopic w-50">
<h1>Edit Post</h1>
<br>
{% include 'parts/alerts.html' %}
<div aria-label="breadcrumb">
<ol class="breadcrumb n1-head">
<li class="breadcrumb-item">Boards</li>
<li class="breadcrumb-item"><a href="{% url 'topics' post.topic.board.pk
%}">
{{post.topic.board.name}}</a></li>
<li class="breadcrumb-item active" aria-current="page"><a href="">Edit
Post</a></li>
</ol>
</div>
<form method="POST" action="" novalidate class="mb-4">
{% csrf_token %}
{% include 'includes/form.html' %}
<button type="submit" class="btn main-btn w-100 rounded-pill mt-5">
Save Changes
</button>
</form>
</div>
</div>
{% endblock %}
$ Views.py
#method_decorator(login_required, name='dispatch')
class PostUpdateView(UpdateView):
model = Post
fields = ('message',)
template_name = 'edit_post.html'
pk_url_kwarg = 'post_id'
context_object_name = 'post'
def form_valid(self, form):
post = form.save(commit=False)
post.updated_by = self.request.user
post.updated_date = timezone.now()
post.save()
return redirect('topic_posts', board_id=post.topic.board.pk, topic_id=post.topic.pk)
$ Urls.py
urlpatterns = [
path('<int:board_id>/topics/<int:topic_id>/posts/<int:post_id>/edit',
views.PostUpdateView.as_view(), name="edit_post"),
]
$error message
TemplateDoesNotExist at /boards/4/topics/24/posts/28/edit
edit_post.html
Request Method: GET
Request URL: http://localhost:8000/boards/4/topics/24/posts/28/edit
Django Version: 4.0.5
Exception Type: TemplateDoesNotExist
Exception Value: edit_post.html

Why is my Update URL link kicking me to the CreateNew html view

so this is a tag on from my previous stackoverflow post:
Django updateView saving another instance instead of updating
and i think i've narrowed it down. Whats happening is that when i click on the link to update my view, it sends me to the "create new" page. my problem is that I cant figure out why its doing that.
Any and all help is appreciated.
here is the code:
question_form.html
{% extends "base.html" %}
{% load bootstrap3 %}
{% block content %}
<h4>Create New Question</h4>
<form method="POST" action="{% url 'questions:create' %}" id="questionForm">
{% csrf_token %}
{% bootstrap_form form %}
<input type="submit" value="Post" class="btn btn-primary btn-large">
</form>
{% endblock %}
question_update.html
{% extends "base.html" %}
{% load bootstrap3 %}
{% block content %}
<h4>Update Question</h4>
<form method="POST" action="{% url 'questions:update' pk=question.pk %}" id="questionForm">
{% csrf_token %}
{% bootstrap_form form %}
<input type="submit" value="Update" class="btn btn-primary btn-large">
</form>
{% endblock %}
question_detail.html
{% block content %}
this is the question detail view
<h3>{{ question.question_html|safe }}</h3>
<h3>{{ question.answer_html|safe }}</h3>
Update Question
{% endblock %}
urls.py
url(r'new/$', views.CreateQuestion.as_view(), name='create'),
url(r'questionupdate/(?P<pk>\d+)/$', views.QuestionUpdate.as_view(), name='update'),
url(r'questiondetail/(?P<pk>\d+)/$', views.QuestionDetail.as_view(), name='single'),
views.py
class CreateQuestion(generic.CreateView):
model = models.Question
form = QuestionForm
fields = ('question', 'answer')
success_url = reverse_lazy('questions:all')
def form_valid(self, form):
self.object = form.save(commit=False)
self.object.user = self.request.user
self.object.save()
return super().form_valid(form)
class QuestionDetail(generic.DetailView):
model = models.Question
class QuestionUpdate(generic.UpdateView):
model = models.Question
form_class = QuestionForm
context_object_name = 'question'
From your urls.py the name of update view is only update. You can try only update tag in html file Like
{% extends "base.html" %}
{% load bootstrap3 %}
{% block content %}
<h4>Update Question</h4>
<form method="POST" action="{% url 'update' pk=question.pk %}" id="questionForm">
{% csrf_token %}
{% bootstrap_form form %}
<input type="submit" value="Update" class="btn btn-primary btn-large">
</form>
{% endblock %}
I've figured it out. it turns out I was missing the template name part under my Create and update views which directs them to their own html templates:
class CreateQuestion(generic.CreateView):
model = models.Question
form_class = QuestionForm
fields = ('question', 'answer')
template_name = "questions/question_form_create.html"
success_url = reverse_lazy('questions:all')
class QuestionUpdate(generic.UpdateView):
model = models.Question
form_class = QuestionForm
template_name = "questions/question_form_update.html"

How do I style my user registration form using Bootstrap in DJango?

So I have the following user registration form which I want to style. My forms.py look something like this. :
from django.contrib.auth.models import User
from django import forms
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())
class Meta:
model = User
fields = ['username','email','password']
Now this is my views.py:
class UserFormView(View):
form_class =UserForm
template_name = 'visit/registration/register.html'
def get(self,request):
form = self.form_class(None)
return render(request,self.template_name,{'form':form})
def post(self, request):
form = self.form_class(request.POST)
if form.is_valid():
user =form.save(commit=False)
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user.set_password(password)
user.save()
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request,user)
return redirect('visit:index')
return render(request, 'visit/registration/register.html', {'form': form})
Now What I am getting a bit confused in HTML, since there is only one line which passes all these fields in the page together. So how M I supposed to style these fields separately.
{% extends 'visit/base.html'%}
{%block content%}
<!DOCTYPE html>
<html>
{% load staticfiles %}
<link rel = "stylesheet" type = "text/css" href = "{% static "visit/registration.css"%}">
<head>
<title></title>
</head>
<body>
<form method="POST" class = "sign-up-form">
{% csrf_token %} {{ form.as_p }}
<button type="submit">Submit</button>
</form>
</body>
</html>
{%endblock%}
You have multiple options, each one with its pros and cons:
1. Add custom css classes within forms.py
To use the simplicity of {{ form.as_p }} approach you could manually add classes to all your forms fields, e.g.:
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput(
attrs={'class' : 'your-custom-class'})
)
Note that it could be a challenge to render the form to be perfectly aligned with Bootstrap's style.
2. Render the form manually
You could write your form by hand within your template, e.g.:
<div class="form-group">
<label for="{{ form.password.id_for_label }}">
{% trans 'Password' %}
</label>
<input type="text" id="{{ form.password.id_for_label }}"
name="{{ form.password.html_name }}"
{% if form.password.field.required %}required{% endif %}
class="form-control{% if form.password.errors %} is-invalid{% endif %}"
value="{% if form.password.value %}{{ form.password.value }}{% endif %}">
{% if form.password.help_text %}
<small class="text-muted">
{{ form.password.help_text }}
</small>
{% endif %}
{% for err in form.password.errors %}
<span class="invalid-feedback">{{ err }}</span>
{% endfor %}
</div>
More info on rendering form fields manually can be found here.
The above snippet will use most of the functionality existing in the default django form renders methods, but on the other hand forces you to write a lot of boilerplate code which is harden to maintain in the long run.
3. Use 3rd party app as a mix of the first two options
You could use custom app to handle the rendering of the forms, a good example would be django-crispy-forms.
You can simply use django-bootstrap
This will automatically render the bootstrap form for you.
{% extends 'visit/base.html'%}
{% load bootstrap3 %}
{%block content%}
<!DOCTYPE html>
<html>
{% load staticfiles %}
<link rel = "stylesheet" type = "text/css" href = "{% static "visit/registration.css"%}">
<head>
<title></title>
</head>
<body>
<form method="POST" class = "sign-up-form">
{% csrf_token %}
{% bootstrap_form form %}
<button type="submit">Submit</button>
</form>
</body>
</html>
{%endblock%}

Display the content of many to many fields in django template

I want to know how it is possible to display many-to-many relations in the django template. I posted my views.py and my models.py. I tried to find the solution by myself but I didn't really understand how to solve the problem :/
models.py
class topic(models.Model):
topic = models.TextField(verbose_name = 'Thema')
learningObjectivesTopic = models.ManyToManyField(learningObjective, verbose_name = "Lernziel")
class learningObjective(models.Model):
learningObjectives = models.TextField(verbose_name = 'Lernziel')
views.py
#login_required(login_url='login')
def themen(request):
return render(request, 'themen.html')
#login_required(login_url='login')
def create_themen(request):
neueThemen=topic(topic=request.POST['thema'])
neueThemen.save()
neueThemen_Lernziel=learningObjective(learningObjectives=request.POST['Lernziel'])
neueThemen_Lernziel.save()
neueThemen.learningObjectivesTopic.add(neueThemen_Lernziel)
return render(request, 'themen.html', {'thema': topic.objects.all(), 'lernziel': learningObjective.objects.all()})
and my unfinished template "themen.html"
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form action="{% url 'create_themen' %}" method="post">
{% csrf_token %}
<br>Hallo Benutzer: {{ user.username }}</br>
<br>Thema: <textarea name="thema" rows="3" cols="45"></textarea></br>
<br>Lernziel: <textarea name="Lernziel" rows="3" cols="45"></textarea></br>
<input type="submit" value="Absenden" />
<br>Aktuelle Themen:</br>
</form>
{% for thema_ in thema %}
{{ thema_.topic }}<br/>
{{ thema_.
{% endfor %}
</body>
</html>
Given the thema object, if you want to display the many to many fields,
{% for topic in thema %}
{{topic.topic}}
{% for lo in topic.learningObjectivesTopic.all %}
{{lo.learningObjectivesTopic}}
{% endfor %}
{% endfor %}