i get an error. django.urls.exceptions.NoReverseMatch - html

l am started to learn Django few days ago, and I get this error:
django.urls.exceptions.NoReverseMatch: Reverse for 'create_order' with no arguments not found. 1 pattern(s) tried: ['create_order/(?P[^/]+)/$']*
urls.py
path('create_order/<str:pk>/', views.createOrder, name='create_order'),
views.py
def createOrder(request, pk):
customer = Customer.objects.get(id=pk)
form = OrderForm(initial={'customer': customer})
if request.method == 'POST':
# print('Printing:', request.POST)
form = OrderForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
context = {
'form': form
}
return render(request, 'accounts/order_form.html', context)
order_form.html
{% extends 'accounts/main.html' %}
{% load static %}
{% block content %}
<br>
<div class="row">
<div class="col-12 col-md-6">
<div class="card card-body">
<form action="" method="post">
{% csrf_token %}
{{form}}
<input class="btn btn-sm btn-danger" type="submit" value="Conform">
</form>
</div>
</div>
</div>
{% endblock %}
customer.html
<div class="row">
<div class="col-md">
<div class="card card-body">
<h5>Customer:</h5>
<hr>
<a class="btn btn-outline-info btn-sm btn-block" href="">Update Customer</a>
<a class="btn btn-outline-info btn-sm btn-block" href="{% url 'create_order' customer.id %}">Place Order</a>
</div>
</div>

As the error said, it tried with empty argument, means there was no customer value available in context. So you need to send the customer value through context, like this:
context = {
'customer' : customer,
'form': form
}

I was also following this tutorial from youtube(dennis ivy) and got the same error,
don't know what is the problem but just replace the file urls.py from github with the same context and it's not showing that error,.
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name="home"),
path('products/', views.products, name='products'),
path('customer/<str:pk_test>/', views.customer, name="customer"),
path('create_order/<str:pk>/', views.createOrder, name="create_order"),
path('update_order/<str:pk>/', views.updateOrder, name="update_order"),
path('delete_order/<str:pk>/', views.deleteOrder, name="delete_order"),
]
views.py
from django.forms import inlineformset_factory
def createOrder(request, pk):
OrderFormSet = inlineformset_factory(Customer, Order, fields=('product', 'status'), extra=10 )
customer = Customer.objects.get(id=pk)
formset = OrderFormSet(queryset=Order.objects.none(),instance=customer)
#form = OrderForm(initial={'customer':customer})
if request.method == 'POST':
#print('Printing POST:', request.POST)
#form = OrderForm(request.POST)
formset = OrderFormSet(request.POST, instance=customer)
if formset.is_valid():
formset.save()
return redirect('/')
context = {'form':formset}
return render(request, 'accounts/order_form.html', context)
order_form.html
{% extends 'accounts/main.html' %}
{% load static %}
{% block content %}
<div class="row">
<div class="col-md-6">
<div class="card card-body">
<form action="" method="POST">
{% csrf_token %}
{{ form.management_form }}
{% for field in form %}
{{field}}
<hr>
{% endfor %}
<input type="submit" name="Submit">
</form>
</div>
</div>
</div>
{% endblock %}
again I don't know why it was showing this error and where was the problem but just relapced it with the same code from github and it worked..if someone know how it worked , that will be really helpful in near future. thanks to all regards Haris Ahmad

Related

ValueError at /plants/plants/ too many values to unpack (expected 2) when using django_filters

Hej!
I'm having trouble with my django filter.
When I put {{myFilter}} in the template I only get an ObjectNumber and when I put {{myFilter.form}} I get the error:
ValueError at /plants/plants/
too many values to unpack (expected 2)
Does anyone have an idea what's going on?
# views.py
def plants_view(request):
plants = Plant.objects.all()
myFilter = PlantFilter(plants)
context = {"plants": plants, "myFilter": myFilter}
return render(request, 'plants/search_table.html', context)
# filters.py
class PlantFilter(django_filters.FilterSet):
class Meta:
model = Plant
fields = ['name',]
it doesn't matter if I use fields = [ ] or fields = '__all__' .
template.html
{% extends "landing/base.html" %}
{% load static %}
{% load i18n %}
{% load admin_urls %}
{% block page-title %} {%translate "View Plants" %} {% endblock %}
{% block head %}
<link href="{% static 'landing/vendor/tabulator/dist/css/tabulator.min.css' %}" rel="stylesheet">
<link href="{% static 'landing/vendor/tabulator/dist/css/bootstrap/tabulator_bootstrap4.min.css' %}" rel="stylesheet">
{% endblock %}
{% block content %}
<br>
<div class="row">
<div class="col">
<div class="card card-body">
<form method="get">
{{myFilter.form}}
<button class="btn-primary" type="submit">Search</button>
</form>
</div>
</div>
</div>
</br>
# models.py
class Plant(models.Model):
name = models.CharField(
max_length=200
)
def __str__(self):
return f"{self.name}"
def serialize(self):
return {
"Name": self.name
}
Did you follow the documentation on this page ?
views.py
def plants_view(request):
plants = Plant.objects.all()
myFilter = PlantFilter(request.GET, queryset=plants)
context = {"plants": plants, "myFilter": myFilter}
return render(request, 'plants/search_table.html', context)
template.html
<form method="get">
{{ myFilter.form.as_p }}
<button class="btn-primary" type="submit">Search</button>
</form>

I am getting an error when trying to click on Like button This page isn’t working HTTP ERROR 405

I am new to Django and trying to implemet Like and Dislike option in Blog application.
I have issue where once any logged in user click Like button the browser gives HTTP ERROR 405
Once user click Like button it redirect to PostDetailView (post_detail)
I have also added POST in form method as below in post_detail.html page
view.py
class PostDetailView(DetailView):
model = Post
template_name = 'blog/post_detail.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
data = get_object_or_404(Post, id=self.kwargs['pk'])
total_likes = data.total_likes()
liked = False
if data.likes.filter(id=self.request.user.id).exists():
liked = True
else:
pass
context["total_likes"] = total_likes
context["liked"] = liked
return context
def LikeView(request,pk):
if request.method == 'POST':
post = get_object_or_404(Post, id=request.POST.get('post_id'))
liked = False
if post.likes.filter(id=request.user.id).exists():
post.likes.remove(request.user)
else:
post.likes.add(request.user)
liked = True
post.likes.add(request.user)
return HttpResponseRedirect(reverse('post_detail', args=[str(pk)]))
post_detail.html
{% extends 'blog/base.html' %}
{% block content %}
{% csrf_token %}
<article class="media content-section">
<img class="rounded-circle article-img" src="{{ object.author.profile.image.url }}">
<div class="media-body">
<div class="article-metadata">
<a class="mr-2" href="{% url 'user_post' object.author.username %}">{{ object.author }}</a>
<small class="text-muted">{{ object.date_posted }}</small>
</div>
<h2 class="article-title">{{ object.title }}</h2>
<p class="article-content">{{ object.content|urlize }}</p>
{% if object.author == user %}
<div>
<a class="btn sm btn btn-secondary mb-1" href="{% url 'post_update' object.id %}">Update</a>
<a class="btn sm btn btn-danger mb-1" href="{% url 'post_delete' object.id %}">Delete</a>
</div>
{% endif %}
<br/><br/>
<form action="{% url 'like_post' object.id %}"
method="POST">
{% csrf_token %}
{% if liked %}
<button class="btn btn-danger btn-sm" type="submit", name "post_id", value={{post.id}}>Unlike
</button>
{% else %}
<button class="btn btn-primary btn-sm" type="submit", name "post_id", value={{post.id}}>Like
</button>
{% endif %}
- {{ total_likes }}
</form>
</div>
</article>
{% endblock %}
urls.py
urlpatterns = [
path('', PostListView.as_view(), name='home'),
path('user/<str:username>', UserPostListView.as_view(), name='user_post'),
path('post/<int:pk>/', PostDetailView.as_view(), name='post_detail'),
path('post/<int:pk>/update', PostUpdateView.as_view(), name='post_update'),
path('post/<int:pk>/delete', PostDeleteView.as_view(), name='post_delete'),
path('post/new/', PostCreateView.as_view(), name='post_create'),
path('about/', views.about, name='about'),
path('contact/', views.contactView, name='contact'),
path('success/', views.successView, name='success'),
path('post/<int:pk>/', views.LikeView, name='like_post'),
]
In your urls.py
"like_post" and "post_detail"
have the same pattern.I think your code chooses "post_detail" instead of "like_post" when you post to this url.
urlpatterns = [
path('post/<int:pk>/like', views.LikeView, name='like_post'),
]
can solve you problem

Django from is not being past into html template

As in the question title "{{form}}" from is not being loaded into html template I checked by previous projects I have almost the same code, differences are required fields, naming etc. mechanic is the same.
In those projects registration function works perfectly here it's not even throwing an error just don't display anything.
No wonder what might be wrong in here.
forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from .models import Profile
class RegistrationForm(UserCreationForm):
email = forms.EmailField(max_length=60, help_text="Required field")
class Meta:
model = Profile
fields = ["email", "username", "password", "password2", "calories_plan", "diet_type"]
views.py
def registration_view(request):
context = {}
if request.POST:
form = RegistrationForm(request.POST)
if form.is_valid():
email = form.cleaned_data.get("email")
password = form.cleaned_data.get("password")
new_account = authenticate(email=email, password=password)
login(request, new_account)
else:
context["registration_form"] = form
else:
form = RegistrationForm()
context["registration_form"] = form
return render(request, "Account/registration.html", context)
html template
{% extends 'main.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>Join today
{{ form }}
</legend>
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Sign Up</button>
</div>
</form>
<div class="border-top pt-3">
<small class="text-muted">
Already have an account?
<a href="#" class="ml-2">
Log In
</a>
</small>
</div>
</div>
{% endblock %}
And how it looks in browser.
You're passing 'registration_form' to the context, but in template you are calling {{ form }}.
Replace:
{{ form }}
with:
{{ registration_form }}

multiple html form from a single form model in django

i need your assistance
im building a school president vote tallying system
the vote results are saved in the polls table as
candidate id | pollingstationid | result |
when capturing the results the html page will render the form for each candidate. for example if there are 3 candidates the html form will have 3 forms:
candidate 1:
result _______
candidate id 1001
pollingstationid 301
candidate 2:
result _______
candidate id 1002
pollingstationid 301
candidate 3:
result _______
candidate id 1003
pollingstationid 301
[submit button]
the problem:
when i click submit, its only saving the last form(i.e candidate 3)
how do i get all three entries into the database each as a new row.
views.py
class candidatesview(AjaxFormMixin, View):
form_class = pollsForm
model = Polls
template_name = 'app/candidates.html'
def get(self, request):
form = self.form_class()
candidatesls = Candidates.objects.all()
context = {'title':'polls','form' : form, 'candidates': candidatesls }
#print(context)
return render(request, self.template_name, context )
def post(self, request):
form = pollsForm(request.POST)
candidatesls = Candidates.objects.all()
if form.is_valid():
print(form.cleaned_data['Result'])
print(form.cleaned_data['Candidateid'])
print(form.cleaned_data['PollingstationID'])
form.save()
messages.success(request,('Form submitted successfuly'))
else:
messages.warning(request,('nah!'))
print(messages)
context = {'title':'polls','form' : form, 'candidates': candidatesls, 'message':messages}
return render(request, self.template_name, context)
forms.py
class pollsForm(forms.ModelForm):
class Meta:
model = Polls
fields = ['Result', 'Candidateid','PollingstationID']
html (candidates.html)
{% extends "app/base.html" %}
{% load widget_tweaks %}
{% block content %}
<div class="bg-white">
<div class="row">
<div class="col-lg-4 col-md-4 col-sm-8">
{% if messages %}
{% for message in messages %}
<div class="alert alert-warning alert-dismissible show" role="alert">
{{ message }}
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="false">×</span>
</button>
</div>
{% endfor %}
{% endif%}
<div id="alertbox">
</div>
<div class="form-group">
<form class="my-ajax-form" method="POST" action="{% url 'polls' %}">
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{#{% for field in form.visible_fields %}#}
<table class="table">
{% for candidates in candidates %}
<tr>
<td>
{% render_field form.Result class="form-control" placeholder=candidates.CandidateName id=forloop.counter %}
<input type="number" class="form-control" id={{ forloop.counter }} value={{ candidates.CandidateID }}>
{% render_field form.PollingstationID type="hidden" class="form-control" id="C1_Pollingstation" %}
{% for error in field.errors %}
<span class="help-block">{{ error }}</span>
{% endfor %}
</td>
<td>
<div class="circle" style="background:{{ candidates.CandidateColor }}">2</div>
</td>
</tr>
{% endfor %}
</table>
<div class="pull-right">
<input type='submit' class='btn btn-next btn-fill btn-success btn-wd' name='Post' value='Post' />
</div>
</form>
</div>
</div>
</div>
</div>
<br />
{% endblock content %}
{% block javascript %}
<script>
$(document).ready(function(){
var $myForm = $(".my-ajax-form")
var $myMessage = $("#alertbox")
$myForm.submit(function(event){
event.preventDefault()
var $formData = $(this).serialize()
var $endpoint = $myForm.attr("data-url") || window.location.href
console.log($formData)
console.log($endpoint)
$.ajax({
method: "POST",
url: $endpoint,
data: $formData,
success: handleFormSuccess,
error: handleFormError,
})
function handleFormSuccess(data, textStatus, jqXHR){
console.log(data)
console.log(textStatus)
console.log(jqXHR)
$myForm[0].reset();
$myMessage.replaceWith('<div class="alert alert-success show" role="alert" id="alertbox"> post succcess</div> ');
}
function handleFormError(jqXHR, textStatus, errorThrown){
console.log(jqXHR)
console.log(textStatus)
console.log(errorThrown)
$myMessage.replaceWith('<div class="alert alert-warning show" role="alert" id="alertbox"> post failure</div> ');
}
})
})
</script>
{% endblock %}

Why won't my UserCreationForm render in chronological order?

I want the form to show
Username
Email
Password
Password(2)
At the moment, it is showing
Username
Password
Password (2)
Email
I am trying to follow this tutorial https://www.youtube.com/watch?v=q4jPR-M0TAQ.
I have looked at the creators notes on Github but that has not helped.
I have double checked my code and cannot see any daft typos.
Can anyone provide any insight?
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
from django.shortcuts import render, redirect
from django.contrib import messages
from .forms import UserRegisterForm
def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
messages.success(request, f'Account created for {username}!')
return redirect ('blog-home')
else:
form = UserRegisterForm()
return render(request, 'users/register.html', {'form':form})
{% 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">Join Today</legend>
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Sign Up</button>
</div>
</form>
<div class="border-top pt-3">
<small class="text-muted">
Already Have An Account? <a class="ml-2" href="#">Sign In</a>
</small>
</div>
</div>
{% endblock content %}
you can customize the look and order of the form by this method, create a new template in the account/ template directory, name it register.html, and make it look as follows:
{% extends "base.html" %}
{% block title %}Create an account{% endblock %}
{% block content %}
<h1>Create an account</h1>
<p>Please, sign up using the following form:</p>
<form action="." method="post">{% csrf_token %}
{{ form.username }}
{{ form.other_fields_as_you_like }}
<p><input type="submit" value="Create my account"></p>
</form>
{% endblock %}