django form wizard - NoReverseMatch - looking for a specific named step - python

I'm trying to setup a multi-step form using Django Form Wizard, but running into a "NoReverseMatch" error.
From previous experience with this error, it was because I was not passing through an argument when the url takes one, i.e. (?P<pk>\d+).
In my specific case:
Reverse for 'task_step' with arguments '()' and keyword arguments '{'step': u'address'}' not found. 0 pattern(s) tried: []
What I've tried so far:
passing wizard.steps.current in the <form action="">
passing wizard.steps.next in the <form action="">
Is it something to do with my urls.py?
// views.py
FORMS = [("subcategory", ChooseSubcategoryForm),
("address", SetAddressForm),
("task-details", AddTaskDetailsForm),]
TEMPLATES = {"subcategory": "tasks/create_task_form/step1.html",
"address": "tasks/create_task_form/step2.html",
"task-details": "tasks/create_task_form/step3.html",
}
class AddTaskWizard(NamedUrlSessionWizardView):
form_list = [ChooseSubcategoryForm, SetAddressForm, AddTaskDetailsForm]
def get_template_names(self):
return [TEMPLATES[self.steps.current]]
def get_context_data(self, form, **kwargs):
context = super(AddTaskWizard, self).get_context_data(form=form, **kwargs)
# add extra variables for a specific step
# if self.steps.current == "step_name":
# context.update({'another_variable': True})
return context
def done(self, form_list, form_dict, **kwargs):
# do something with the form data(form_list)
subcategory = form_dict['subcategory'].save()
print("============")
print(subcategory)
print("============")
address = form_dict['address'].save()
task = form_dict['task-details'].save()
return HttpResponseRedirect('/tasks')
def get_step_url(self, step):
return reverse(self.url_name, kwargs={'step':step})
// urls.py
from django.conf.urls import url
from .views import CreateTaskView, TaskDetailView
from . import views
from .forms import ChooseSubcategoryForm, SetAddressForm, AddTaskDetailsForm
app_name='tasks'
named_task_forms = (
("subcategory", ChooseSubcategoryForm),
("address", SetAddressForm),
("task-details", AddTaskDetailsForm),
)
task_wizard = views.AddTaskWizard.as_view(named_task_forms, url_name="task_step")
urlpatterns = [
url(r'^add_task/(?P<step>\w+)/$', task_wizard, name='task_step'),
]
// step1.html => subcategory form
<div class="row" id="create-task-progress">
<div class="container">
<div class="col-md-4 section-static border-top-gray text-center">
<span class="glyphicon glyphicon-search glyphicon-md orange" ></span> <span class="orange">1. Choose Subcategory</span>
</div>
<div class="col-md-4 section-static col-middle text-center">
<span class="glyphicon glyphicon-home glyphicon-md" ></span> <span>2. Set Address</span>
</div>
<div class="col-md-4 section-static border-top-gray text-center">
<span class="glyphicon glyphicon-pencil glyphicon-md"></span> <span>3. Task Details</span>
</div>
</div>
</div>
<div class="row section-light-gray border-top-gray">
<div class="container" id="task-form-container">
<div class="col-md-12">
<form action="{% url 'tasks:task_step' wizard.steps.current %}" method="POST" enctype="multipart/form-data" class="col-md-10 col-md-push-1">
{% csrf_token %}
{{ wizard.management_form }}
<div class="col-md-12 task-field-container">
{{ wizard.form.subcategory.label }}
{{ wizard.form.subcategory }}
</div>
<input type="submit" value="Continue" id="add_task" class="btn btn-primary col-xs-12" />
</form>
</div>
</div>
</div>

Based on what I see in your template, you're using url namespaces.
I believe you need to change
task_wizard = views.AddTaskWizard.as_view(named_task_forms, url_name="task_step")
to
task_wizard = views.AddTaskWizard.as_view(named_task_forms, url_name="tasks:task_step")
So you're just missing the tasks:

Related

Django POST request parameters returns none in views.py

I want to take values from a POST request. I want to take "taken_name" value from html form to views.
I tried several question's answers, but I think I' m missing very simple thing. I can not figure it out nearly 2 hours.
Parameter name in html is 'taken_name'.
Also urls and views parameters are true and matching with the methods which mentioned on stackoverflow.
I' m getting this error :
'null value in column "visitor_name" of relation "visitor" violates
not-null constraint DETAIL: Failing row contains (15, null, null,
null).'
This means I can't get the value from html.
Tried:
get value from POST request in Django
res.html
{% for i in allList %}
<div id="createRecordModal-{{forloop.counter}}" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<form method="POST" action="/session/{{visitor_id}}">
{% csrf_token %}
<div class="modal-header">
<h4 class="modal-title" name="taken_table">Masa {{i.table_number}}</h4>
<button
type="button"
class="btn-close btn-close-white"
data-bs-dismiss="modal"
aria-hidden="Close"
></button>
</div>
<div class="modal-body">
<div class="form-group">
<label>İsim</label>
<input
name="taken_name"
type="text"
class="form-control"
required
/>
</div>
</div>
<div class="modal-footer">
<button
type="button"
class="btn btn-secondary"
data-bs-dismiss="modal"
aria-label="Close"
>
İptal
</button>
Kaydet
</div>
</form>
</div>
</div>
</div>
{% endfor %}
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.loginUser, name="login"),
path('reservation', views.reservation, name="reservation"),
path('delete/<str:table_number>', views.delete, name='delete'),
path('create/<str:table_number>', views.create, name='create'),
path('session/<str:visitor_id>', views.createSession, name='create2')
]
views.py
def createSession(request, visitor_id):
addSession = visitor.objects.filter(visitor_id = visitor_id)
if request.method == "POST":
taken_name = request.POST.get('taken_name')
taken_surname = request.POST.get('taken_surname')
taken_time = request.POST.get('taken_time')
print(taken_name)
print(taken_surname)
print(taken_time)
else:
print('method is not POST')
addSession.create(
visitor_name = taken_name,
visitor_surname = taken_surname,
res_time = taken_time
)
context = {
'addSession': addSession
}
return redirect('reservation')
def reservation(request):
allList = table_inventory.objects.all()
max_rating = table_inventory.objects.aggregate(Max('table_number')).get('table_number__max')
visitor_no = visitor.objects.aggregate(Max('visitor_id')).get('visitor_id__max')
visitor_no +=1
return render(request, 'reservation.html', {
'allList': allList,
'max_rating': max_rating,
'visitor_no': visitor_no
})
In your template, you are using the following:
Kaydet
If you were intending to use this to submit your form, it won't work. It will simply link to the URL nominated in the href attribute.
Try something like:
<button type="submit" class="btn btn-danger">Kaydet</button>

The modal appears but the profile edit form don't appear on it, any idea why?

On my social app that I'm working on, there's still one issue. On my ProfileDetailView, to click on "Edit Profile" the modal form appear but there's no form. It was working before but when I fixed the close button and I don't know what happened.. I copied the modal html from bootstrap so i probably deleted/changed something and forgot to re-do it..
Form:
from django import forms
from .models import Profile, Post, Comment
class ProfileModelForm(forms.ModelForm):
class Meta:
model = Profile
fields = ('first_name', 'last_name', 'bio', 'avatar')
class PostModelForm(forms.ModelForm):
content = forms.CharField(widget=forms.Textarea(attrs={'rows':2, 'cols': 30}))
class Meta:
model = Post
fields = ('content', 'picture')
class CommentModelForm(forms.ModelForm):
body = forms.CharField(label='', widget=forms.TextInput(attrs={'placeholder': 'Add a comment...', 'class':'comment'}))
class Meta:
model = Comment
fields = ('body',)
Views:
from django.contrib.auth import authenticate, login, logout
from django.db import IntegrityError
from django.http import HttpResponse, HttpResponseRedirect
from django.http.response import JsonResponse
from django.shortcuts import render, redirect, resolve_url, get_object_or_404
from django.urls import reverse, reverse_lazy
from django.core import serializers
from django.core.paginator import Paginator
from django.contrib import messages
from django.contrib.auth.models import User
from django.db.models import Q
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from itertools import chain
from .models import Relationship, Post, Profile, Like
from django.views.generic import TemplateView, View, UpdateView, DeleteView, ListView, DetailView
from .forms import ProfileModelForm, PostModelForm, CommentModelForm
def search_view(request):
if request.method == "POST":
searched = request.POST['searched']
profiles = Profile.objects.filter(slug__contains=searched)
return render(request, 'network/search.html',
{'searched':searched,
'profiles':profiles})
else:
return render(request, 'network/search.html',
{})
class ProfileDetailView(LoginRequiredMixin, DetailView):
model = Profile
template_name = 'network/profile.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
user = User.objects.get(username__iexact=self.request.user)
profile = Profile.objects.get(user=user)
rel_r = Relationship.objects.filter(sender=profile)
rel_s = Relationship.objects.filter(receiver=profile)
rel_receiver = []
rel_sender = []
for item in rel_r:
rel_receiver.append(item.receiver.user)
for item in rel_s:
rel_sender.append(item.sender.user)
context["rel_receiver"] = rel_receiver
context["rel_sender"] = rel_sender
context["posts"] = self.get_object().get_all_authors_posts()
context["len_posts"] = True if len(self.get_object().get_all_authors_posts()) > 0 else False
return context
#login_required
def profile_view(request):
profile = Profile.objects.get(user=request.user)
form = ProfileModelForm(request.POST or None, request.FILES or None, instance=profile)
confirm = False
if request.method == 'POST':
if form.is_valid():
form.save()
confirm = True
context = {
'profile': profile,
'form': form,
'confirm': confirm,
}
return render(request, 'network/profile.html', context)
profile.html:
{% extends "network/layout.html" %}
{% load static %}
{% load crispy_forms_tags %}
{% block title %}
My Profile
{% endblock title %}
{% block body %}
<!--Modal-->
<div class="modal fade" id="profileModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Update Your Profile</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<img width="100px" src="{{object.avatar.url}}">
<form action="", method="POST", enctype="multipart/form-data" class="form-horizontal">
{% csrf_token %}
{{ form }}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Update</button>
</form>
</div>
</div>
</div>
</div>
<div>
{% if confirm %}
<div class="alert alert-info" role="alert">Your profile has been updated!</div>
{% endif %}
</div>
<div class="row py-5 px-4">
<div class="col-md-5 mx-auto">
<!-- Profile widget -->
<div class="bg-white shadow rounded overflow-hidden">
<div class="px-4 pt-0 pb-4 cover">
<div class="media align-items-end profile-head">
<div class="profile mr-3"><img src="{{object.avatar.url}}" width="130" class="rounded mb-2 img-thumbnail"></div>
<div class="media-body mb-5 text-white">
<h4 class="mt-0 mb-3">{{profile.first_name}} {{profile.last_name}}</h4>
<p style="color: black;" class="small mb-4"> <i class="fas fa-map-marker-alt mr-2"></i>{{profile.country}}</p>
</div>
</div>
</div>
<div class="bg-light p-5 d-flex justify-content-end text-center">
<ul class="list-inline mb-0">
<li class="list-inline-item">
<h5 class="font-weight-bold mb-0 d-block">{{object.get_posts_num}}</h5><small class="text-muted"> <i class="fas fa-image mr-1"></i>Posts</small>
</li>
<li class="list-inline-item">
<h5 class="font-weight-bold mb-0 d-block">{{object.get_followers_num}}</h5><small class="text-muted"> <i class="fas fa-user mr-1"></i>Followers</small>
</li>
<li class="list-inline-item">
<h5 class="font-weight-bold mb-0 d-block">340</h5><small class="text-muted"> <i class="fas fa-user mr-1"></i>Following</small>
</li>
<li class="list-inline-item">
<h5 class="font-weight-bold mb-0 d-block">{{object.like_count}}</h5><small class="text-muted"> <i class="fas fa-user mr-1"></i>Likes</small>
</li>
</ul>
</div>
<div class="ml-2">
{% if object.user not in rel_receiver and object.user not in rel_sender %}
<form action="{% url 'send-invite' %}" method="POST">
{% csrf_token %}
<input type="hidden" name="profile_pk" value={{object.pk}}>
<button type="submit" class=" btn btn-sm btn-success w-btn"><i class="bi-plus-lg"></i> Follow</button>
</form>
{% endif %}
{% if object.user in rel_receiver and request.user not in object.following.all %}
<button class="btn btn-sm disabled "><i class="bi-three-dots"></i> Waiting aprroval</button>
{% endif %}
{% if request.user in object.following.all %}
<form action="{% url 'remove-friend' %}" method="POST">
{% csrf_token %}
<input type="hidden" name="profile_pk" value={{object.pk}}>
<button type="submit" class=" btn btn-sm btn-dark w-btn"><i class="bi-dash-lg"></i> Unfollow</button>
</form>
{% endif %}
</div>
<div class="px-4 py-3">
<h5 class="mb-0">About</h5>
<button class="btn btn-sm btn-secondary float-right" id="modal-btn" data-toggle="modal" data-target="#profileModal">Edit Profile</button>
<div class="p-4 rounded shadow-sm bg-light">
<p class="font-italic mb-0">{{profile.bio}}</p>
</div>
</div>
<div class="py-4 px-4">
<div class="d-flex align-items-center justify-content-between mb-3">
<h5 class="mb-0">Recent posts</h5>Show all
</div>
{% if len_posts %}
<div class="row">
{% for post in posts %}
<div class="col-lg-6 mb-2 pr-lg-1 fluid">
{% if post.picture %}
<img class="card-img-profile" src="{{post.picture.url}}">
{% endif %}
{{post.content}}
</div>
{% endfor %}
{% else %}
<h1>This user didn't post anything yet..</h1>
{% endif %}
</div>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
Model:
class Profile(models.Model):
first_name = models.CharField(max_length=64, blank=True)
last_name = models.CharField(max_length=64, blank=True)
user = models.OneToOneField(User, on_delete=models.CASCADE)
country = models.CharField(max_length=64, blank=True)
avatar = models.ImageField(upload_to='avatars', default='avatar.png')
background = models.ImageField(upload_to='backgrounds', default='background.png')
following = models.ManyToManyField(User, related_name='following', blank=True)
bio = models.TextField(default="No Bio..")
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
slug = models.SlugField(unique=True, blank=True)
objects = ProfileManager()
def __str__(self):
return f"{self.user.username}"
def get_absolute_url(self):
return reverse("profile-view", kwargs={"slug": self.slug})
__initial_first_name = None
__initial_last_name = None
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.__initial_first_name = self.first_name
self.__initial_last_name = self.last_name
def save(self, *args, **kwargs):
ex = False
to_slug = self.slug
if self.first_name != self.__initial_first_name or self.last_name != self.__initial_last_name or self.slug=="":
if self.first_name and self.last_name:
to_slug = slugify(str(self.first_name) + " " + str(self.last_name))
ex = Profile.objects.filter(slug=to_slug).exists()
while ex:
to_slug = slugify(to_slug + " " + str(get_random_code()))
ex = Profile.objects.filter(slug=to_slug).exists()
else:
to_slug = str(self.user)
self.slug = to_slug
super().save(*args, **kwargs)
def get_followers(self):
return self.following.all()
def get_followers_num(self):
return self.following.all().count()
def get_my_posts(self):
return self.post_set.all()
def get_country(self):
return self.post_set.all()
def get_following_users(self):
following_list = [p for p in self.get_following()]
return following_list
def get_all_posts(self):
users = [user for user in self.get_following()]
posts = []
qs = None
for u in users:
p = Profile.objects.get(user=u)
p_posts = p.post_set.all()
posts.append(p_posts)
my_posts = self.post_set.all()
posts.append(my_posts)
if len(posts) > 0:
qs = sorted(chain(*posts), reverse=True, key=lambda obj: obj.created)
return qs
def get_posts_num(self):
return self.post_set.all().count()
def get_all_authors_posts(self):
return self.post_set.all()
def get_likes_given_num(self):
likes = self.like_set.all()
total_liked = 0
for item in likes:
if item.value == 'Like':
total_liked += 1
return total_liked
def get_likes_received_num(self):
posts = self.post_set.all()
total_liked = 0
for item in posts:
total_liked += item.all().count()
return total_liked
def get_proposals_for_following(self):
profiles = Profile.objects.all().exclude(user=self.user)
followers_list = [p for p in self.get_following()]
available = [p.user for p in profiles if p.user not in followers_list]
random.shuffle(available)
return available[:3]
STATUS_CHOICES = (
('send', 'send'),
('accepted', 'accepted')
)
Update posts html:
{% extends "network/layout.html" %}
{% block title %}
Update Post
{% endblock title %}
{% block body %}
<div class="card center" style="width: 30rem;">
<h3>Update post</h3>
<form action="" method="POST" enctype="multipart/form-data" class="form-group">
{% csrf_token %}
{{form}}
<button type='submit' class="btn float-right btn-sm btn-primary mt-5">Update</button>
</form>
</div>
{% endblock body %}
URLs:
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from . import views
from .views import (
posts_of_following_profiles,
like_unlike_post,
invites_received_view,
invite_profiles_list_view,
send_invitation,
remove_friends,
accept_invitation,
reject_invitation,
search_view,
post_comment_create_view,
login_view,
logout_view,
register,
ProfileDetailView,
PostDeleteView,
PostUpdateView,
ProfileListView,
)
urlpatterns = [
path("", ProfileListView.as_view(), name="all-profiles-view"),
path("posts/", views.post_comment_create_view, name="posts"),
path("posts-follow/", posts_of_following_profiles, name="posts-follow"),
path("login", views.login_view, name="login"),
path("logout", views.logout_view, name="logout"),
path("register", views.register, name="register"),
path("liked/", like_unlike_post, name="like-post-view"),
path("<pk>/delete", PostDeleteView.as_view(), name="post-delete"),
path("<pk>/update", PostUpdateView.as_view(), name="post-update"),
path("invites/", invites_received_view, name="invites-view"),
path("send-invite/", send_invitation, name="send-invite"),
path("remove-friend/", remove_friends, name="remove-friend"),
path("invites/accept/", accept_invitation, name="accept-invite"),
path("invites/reject/", reject_invitation, name="reject-invite"),
path("to-invite/", invite_profiles_list_view, name='invite-profiles-view'),
path("search/", views.search_view, name='search-view'),
path("<slug>", ProfileDetailView.as_view(), name="profile-view"),
]
screenchot
Code snippet:
<div class="modal-header">
<h5 class="modal-title">Update Your Profile</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<img src="/media/avatars/11892013_911718608883264_3848632245418610369_n.jpg" width="100px">
<form action="" ,="" method="POST" enctype="multipart/form-data">
<input type="hidden" name="csrfmiddlewaretoken" value="P2vu2WI916PGSbMOrXD14c9EFmfMVEk3T1vkf9rqsZC7hXD94Dq2Cjo4MVCIiEEp">
</form></div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Update</button>
</div>

How to pass context result as argurment for another function in django?

I have my django app which searches youtube and return result as a dictionary which i render them in template, one of the returned value is link , now I have a download button they way i wish it to function is whenever you click a button it should take the url for the clicked result and pass it to another download function as an argument. How do I accomplish that ?
Here is my view.py
def index(request):
if request.method == 'POST':
query = request.POST['video_name']
n = 12
search = SearchVideos(str(query), offset = 1, mode = "json", max_results = n)
ytresults = search.result()
result_dict = json.loads(ytresults)
context = {
"result" : result_dict,
}
template_name = "youloader/results.html"
return render(request, template_name, context)
else:
query = "no copyright sound"
n = 12
search = SearchVideos(str(query), offset = 1, mode = "json", max_results = n)
index_results = search.result()
result_dict = json.loads(index_results)
context = {
"result" : result_dict
}
template_name = "youloader/index.html"
return render(request, template_name, context)
def downloading_video(request):
try:
with youtube_dl.YoutubeDL(video_opts) as ydl:
ydl.download(link)
except:
pass
here are my template.html
<div class="my-4" >
<div style="padding-top: 20px">
<div class="row" >
{% for result in result.search_result %}
<div class="col-12 col-sm-6 col-md-4 col-lg-4">
<div class="card shadow-sm border-0 my-2">
<img src="{{ result.thumbnails.1 }}" alt="{{ result.channelId }}">
<div class="card-body">
<h5 class="card-title">{{ result.link }}</h5>
<div class="d-flex flex-wrap justify-content-between card-subtitle my-2 text-muted small">
<a href="{{ result.link }}" class="text-secondary font-weight-bold">
<i class="fa fa-tablet mr-1"></i>{{ result.channel }}
</a>
<span><i class="fa fa-stopwatch mr-1"></i>{{ result.duration }}</span>
<span><i class="fa fa-eye mr-1"></i>{{ result.views }}</span>
<button type="button" class="btn btn-info dropdown-toggle" data-toggle="dropdown">Download</button>
<div class="dropdown-menu">
<a class="dropdown-item" href="#">Audio</a>
<a class="dropdown-item" href="#">Video</a>
</div>
<br>
</div>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
</div>
and here is the sample of the template rendered.
in the index function you can use redirect instead of render
index function:
def index(request):
if request.method == 'POST':
.
.
.
result_dict = json.loads(index_results)
link = result_dict.link
return redirect('youtubedl:download', link ) # first arg is your url route to downloading_video function like 'appname:urlname' and second is the link that coming from result_dic
else:
.
.
downloading_video function:
def downloading_video(request, link):
try:
with youtube_dl.YoutubeDL(video_opts) as ydl:
ydl.download(link)
except:
pass
this is the way i think you should use because your download function is in a separate template

How to resolve reverse match error in django

I'm new to Django and I cannot understand why this error is popping up:
django.urls.exceptions.NoReverseMatch: Reverse for 'updater' with no arguments not found. 1 pattern(s) tried: ['update/(?P<updating>[0-9]+)$']
[26/Jul/2020 19:05:05] "GET /update/2 HTTP/1.1" 500 127513
my urls:
urlpatterns=[
path('update/<int:updating>',views.update,name='updater'),
]
the html page:
<!DOCTYPE html>
<html lang="en">
<head>
{% load static %}
<title>NEW PRODUCT</title>
</head>
<body>
<div class="bg-contact2" style="background-image: url('images/bg-01.jpg');">
<div class="container-contact2">
<div class="wrap-contact2">
<form class="contact2-form validate-form" method="post" action="{%url 'updater' %}" enctype="multipart/form-data">
{% csrf_token %}
<span class="contact2-form-title">
Provide Product details Below
</span>
<div class="wrap-input2 validate-input" data-validate="type is required">
<input class="input2" type="text" name="type" value="{{details.product_type}}">
<span class="focus-input2" data-placeholder="PRODUCT-TYPE"></span>
</div>
<div class="wrap-input2 validate-input" data-validate = "Name is required">
<input class="input2" type="text" name="name" value="{{details.product_name}}">
<span class="focus-input2" data-placeholder="PRODUCT NAME"></span>
</div>
<div class="wrap-input2 validate-input" data-validate = "description is required">
<textarea class="input2" name="description">{{details.product_description}}</textarea>
<span class="focus-input2" data-placeholder="PRODUCT DESCRIPTION"></span>
</div>
<div class="wrap-input2 validate-input" data-validate = "Price is required">
<input class="input2" type="number" name="price" value="{{details.product_price}}">
<span class="focus-input2" data-placeholder="PRICE"></span>
</div>
<div class="wrap-input2 validate-input" data-validate = "Picture is required">
<label >product sample picture</label>
<input class="input2" type="file" name="picture">
<span class="focus-input2" data-placeholder=""></span>
</div>
<div class="container-contact2-form-btn">
<div class="wrap-contact2-form-btn">
<div class="contact2-form-bgbtn"></div>
<button class="contact2-form-btn">
Update Product Listing
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
my views:
def update (request,updating):
if request.method=='POST':
product_details=product_info.objects.get(id=updating)
product_details.product_type=request.POST.get('type')
product_details.product_name=request.POST.get('name')
product_details.product_description=request.POST.get('description')
product_details.product_price=request.POST.get('price')
if (len(request.FILES) != 0):
image = request.FILES['picture']
product_details.product_pic = image
product_details.save()
alldetails = product_info.objects.all()
return render(request, 'adminside/editingpage.html', {'editing_details': alldetails})
else:
product_details = product_info.objects.get(id=updating)
return render(request,'adminside/updating.html',{'details':product_details})
def update (request,updating) :
if request.method=='POST' :
product_details=product_info.objects.get(id=updating)
product_details.product_type=request.POST.get('type')
product_details.product_name=request.POST.get('name')
product_details.product_description=request.POST.get('description')
product_details.product_price=request.POST.get('price')
if (len(request.FILES) != 0):
image = request.FILES['picture']
product_details.product_pic = image
product_details.save()
alldetails = product_info.objects.all()
return render(request, 'adminside/editingpage.html', {'editing_details': alldetails})
else:
product_details = product_info.objects.get(id=updating)
return render(request,'adminside/updating.html',{'details':product_details})
def update (request,updating):
if request.method=='POST':
product_details=product_info.objects.get(id=updating)
product_details.product_type=request.POST.get('type')
product_details.product_name=request.POST.get('name')
product_details.product_description=request.POST.get('description')
product_details.product_price=request.POST.get('price')
if (len(request.FILES) != 0):
image = request.FILES['picture']
product_details.product_pic = image
product_details.save()
alldetails = product_info.objects.all()
return render(request, 'adminside/editingpage.html', {'editing_details': alldetails})
else:
product_details = product_info.objects.get(id=updating)
return render(request,'adminside/updating.html',{'details':product_details})
I think it has something to do with passing the id of the product in the url, but I'm not sure about how to resolve it.
you have not put any argument in the url you have to put argument in the form action for updating like this
<form class="contact2-form validate-form" method="post" action="{%url 'updater' updating='ANYVALUE' %}" enctype="multipart/form-data">
because you haven't specify any value your url is not matching
This urlpattern update/ takes an int route parameter
path('update/<int:updating>',views.update,name='updater'),
In your template, you're trying to reverse updater with no included argument. So it's trying to reverse to a urlpattern of update/ which it can't find because you only have a path for update/<int:updating>
{%url 'updater' %}
You will need to change it to the following as you gave the context object the name details and you can access
{%url 'updater' details.id %}

Attribute error : 'WSGIRequest' object has no attribute 'get'

I've been working on a project lately and got the above error. It says " Error during template rendering".I have a similar model, which works perfectly fine. I've looked for similar errors but got none matching my situation. I don't know where I went wrong. It would be great if I get helpful answers.
Models.py
class ServiceTax(models.Model):
user = models.ForeignKey(User,on_delete=models.CASCADE,related_name="service_tax",null=True,blank=True)
name=models.CharField(max_length=100)
percent=models.FloatField(default='0')
add_amount=models.IntegerField(default='0')
def __str__(self):
return self.name
Forms.py
class ServiceTaxForm(forms.ModelForm):
class Meta:
model = ServiceTax
fields = "__all__"
widgets = {
'name' : forms.TextInput(attrs={'class': 'form-control'}),
'percent' : forms.NumberInput(attrs={'class': 'form-control','step':'0.01'}),
'add_amount' : forms.NumberInput(attrs={'class':'form-control','maxlength':5}),
}
labels={
'add_amount': "Additional Amount"
}
Views.py
def tax_form(request,id=0):
if request.method == 'GET':
if id == 0:
form = ServiceTaxForm(request)
else:
tax = ServiceTax.objects.get(pk=id)
if tax in request.user.service_tax.all():
form = ServiceTaxForm(request,instance=tax)
else:
return redirect('/revenue/tax')
return render(request,'tax-form.html',{'form':form})
else:
if id==0:
form = ServiceTaxForm(request,request.POST)
if form.is_valid():
name = form.cleaned_data["name"]
percent = form.cleaned_data["percent"]
add_amount = form.cleaned_data["add_amount"]
t = AnnualTax(
name=name,
percent=percent,
add_amount=add_amount,
)
t.save()
request.user.service_tax.add(t)
else:
tax = ServiceTax.objects.get(pk=id)
if tax in request.user.service_tax.all():
form = ServiceTaxForm(request,request.POST,instance=tax)
if form.is_valid():
name = form.cleaned_data["name"]
percent = form.cleaned_data["percent"]
add_amount = form.cleaned_data["add_amount"]
tax_obj = ServiceTax.objects.get(pk=id)
tax_obj.name = name
tax_obj.percent = percent
tax_obj.add_amount = add_amount
tax_obj.save()
return redirect('/revenue/tax')
tax-form.html
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<i class="fa fa-chevron-circle-left fa-3x m-2"></i>
<div class="content">
<div class="container-fluid">
<div class="row">
<div class="col-lg-12">
<div class="card">
<div class="card-header">
<h4 class="card-title">Add Service Tax</h4>
</div>
<div class="card-body">
<form action="" method="POST" autocomplete="off">
{% csrf_token %}
<div class="row">
<div class="col-md-4 pr-1">
<div class="form-group">
{{ form.name | as_crispy_field}}
</div>
</div>
<div class="col-md-4 pr-1">
<div class="form-group">
{{ form.percent | as_crispy_field}}
</div>
</div>
<div class="col-md-4 pr-1">
<div class="form-group">
{{ form.add_amount | as_crispy_field}}
</div>
</div>
</div>
<button type="submit" class="btn btn-success btn-fill pull-right">
{% if request.get_full_path == '/income/tax/add/' %}
Add Tax
{% else %}
Update
{% endif %}
</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
You should retrieve your forms passing request.METHOD, not just request
As an example this piece of code form = ServiceTaxForm(request) should be form = ServiceTaxForm(request.POST)

Categories