Can someone spot the mistake? What i'm expecting to happen is to dynamically pass in the ids of the classes I have created, so that I can update an entry I created in a previous form.
Here is my HTML:
<td><a class="btn btn-sm btn-info" href="{% url 'update_type_4_service' type_4_service.order_reference.id type_4_service.id %}>Update</a></td>
Here is my urls:
path('order/<str:pk_test>/update_type_4_service/<str:pk>', views.updateType_4_Service, name="update_type_4_service"),
Here is my views:
def updateType_4_Service(request, pk_test, pk):
type_4_service = Type_4_Service.objects.get(id=pk)
type_4_service_form = Type_4_ServiceForm(instance=type_4_service)
if request.method == 'POST':
type_4_service_form = Type_4_ServiceForm(request.POST, order_reference=order)
type_4_service_form.instance.order_reference = order
if type_4_service_form.is_valid():
type_4_service_form.save()
return redirect('/')
context = {'type_4_service_form': type_4_service_form}
return render(request, 'orchestration/type_4_service_form.html', context)
This is the error:
Reverse for 'update_type_4_service' with arguments '('', '')' not found. 1 pattern(s) tried: ['order/(?P<pk_test>[^/]+)/update_type_4_service/(?P<pk>[^/]+)\\Z']
Try passing the name too:
<td>
<a
class="btn btn-sm btn-info"
href="{% url 'update_type_4_service' pk_test=type_4_service.order_reference.id pk=type_4_service.id %}"
>
Update
</a>
</td>
Related
How can i pass a urls path that has str:pk into my views and templates, I want to redirected a user to the viewPhoto template but when I click on read more, it's throw an error like this: Reverse for 'photo' not found. 'photo' is not a valid view function or pattern name. How can I pass this into my view and template ?
the urls:
path('view/<str:pk>/', views.viewPhoto, name='Photo'),
path('like/<str:pk>/', views.like, name='Photo'),
the views:
def like(request, pk):
post = Photo.objects.get(pk=pk)
liked = False
like = Like.objects.filter(user=request.user, post=post)
if like:
like.delete()
else:
like = True
Like.objects.create(user=request.user, post=post)
resp = {
'liked': liked
}
response = json.dumps(resp)
return redirect('photo')
return HttpResponse(response, content_type = "application/json")
viewPhoto view:
def viewPhoto(request, pk):
post = get_object_or_404(Photo, id=pk)
photo = Photo.objects.get(id=pk)
liked = [i for i in Photo.objects.all() if like.objects.filter(user= request.user,
post = i )]
return render(request, 'photo.html', {'photo': photo, 'post': post, 'liked': liked})
this is how i pass my url in the home emplate:
<a href="{% url 'Photo' photo.id %}" class="btn btn-outline-primary btn-sm m-1">Read
More</a>
You would do something like this to avoid url conflicts :
path('view/<int:pk>/', views.viewPhoto, name='view_photo'),
path('like/<int:pk>/', views.like, name='user_likes'),
# this is for the viewPhoto
<a href="{% url 'view_photo' photo.id %}" class="btn btn-outline-primary btn-sm m-1">Read
More</a>
# Url for the like object, this would actaully help you avoid any form of url conflict
<a href="{% url 'user_likes' photo.id %}" class="btn btn-outline-primary btn-sm m-1">
I have a serch field on my page
<form method="GET" class="container mb-5">
<input type="search" class="form-control rounded" placeholder="Write a name" aria-label="Search"
aria-describedby="search-addon" name="search"/>
<button type="submit" class="btn btn-outline-primary px-5" >Search</button>
</form>
And here is my views
def my_view(request):
value_one = request.GET.get("search", None)
objects = MyModel.objects.all()
if value_one:
objects = objects.filter(field_one=value_one)
After I input something in a search field and push the button 'search', text which was in search field dissapears, I want it to stay until the next input. Is it possible to do with Django or not? Don't even know how to google it, everything I found was on different topic
on your template add value to your input:
<form method="GET" class="container mb-5">
<input type="search" class="form-control rounded" placeholder="Write a name" aria-label="Search" value="{{value_one"}}
aria-describedby="search-addon" name="search"/>
<button type="submit" class="btn btn-outline-primary px-5" >Search</button>
</form>
and on your view add that value to your context :
def my_view(request):
value_one = request.GET.get("search", None)
objects = MyModel.objects.all()
if value_one:
objects = objects.filter(field_one=value_one)
return render(request,'template.html',{'value_one':value_one,'objects':objects})
Have you heard of django's Form class ? You should be using the Form class to create forms in Django and that would allow you to preserve data between "submit" calls as well as handle errors. Some example code snippets for you:
forms.py
from django import forms
class SearchForm(forms.Form):
search = forms.CharField(label="Search Query", widget=forms.TextInput(attrs={"class": "form-control rounded", "placeholder": "Write a name", "aria-label": "Search", "aria-describedby": "search-addon"}))
views.py
from django.shortcuts import render
from .forms import SearchForm
def my_view(request):
form = SearchForm({"search": request.GET.get("search", None)})
if form.is_valid():
search_query = form.cleaned_data.get("search")
if search_query:
objects = MyModel.objects.filter(field_one=search_query).all()
# ...snip...
return render(request, 'searchform.html', {"form": form})
searchform.html
<form action="{% url 'my_view' %}" method="get">
{{ form }}
<input type="submit" value="Submit" class="btn btn-outline-primary px-5">
</form>
I am trying to learn django and I have encountered this error. It has persisted irrespective of the fact that I have tried the available SO remedies but for some reason, it refuses to go away. Can someone please see an error anywhere.
show_options.html
<a class="btn btn-sm btn-block bg-dark" style="color: black;" href="{% url 'Management:addProduct' %}"> Add </a>
**<a class="btn btn-sm btn-danger" href="{% url 'Management:sales' add_user_sales.pk %}"> Add Sales </a>**
<a class="btn btn-sm btn-danger" href="{% url 'Management:total' %}"> View Total </a>
function to render my show_options page
def show_options(request):
return render(request, 'show_options.html', {})
function add_user_sales
#login_required
def add_user_sales(request , pk):
current_user = request.user
context = {}
context["data"] = MadeSale.objects.get(id=pk)
profiles = UserProfile.get_profile()
for profile in profiles:
if profile.profile_name.id == current_user.id:
if request.method == 'POST':
form = SalesForm(request.POST)
if form.is_valid():
upload = form.save(commit=False)
upload.posted_by = current_user
upload.profile = profile
upload.save()
messages.success(request, f'Hi, Your data has successfully been updated' )
return redirect('addProduct')
else:
form = SalesForm()
return render(request,'addProduct.html',{"user":current_user,"form":form}, context)
my app urls
from django.conf.urls import url
from . import views
from django.conf import settings
from django.conf.urls.static import static
from rest_framework.authtoken.views import obtain_auth_token
app_name = 'Management'
url(r'^sales/(?P<pk>\d+)/$', views.add_user_sales, name='sales')
,
Error:
NoReverseMatch at /leachers/11/donate/
Reverse for 'donate' with no arguments not found. 1 pattern(s) tried: ['leachers/(?P[0-9]+)/donate/$']
views.py
#login_required
def donate(request,pk):
if request.method == 'POST':
form = forms.UserDonateForm(request.POST)
if form.is_valid():
user = form.save()
user.refresh_from_db()
user.donator = request.user
user.save()
return redirect('leacher_list')
else:
form = forms.UserDonateForm()
return render(request,'my_app/donation_form.html',{'form':form})
urls.py
from django.urls import path
from . import views
from .views import donate
urlpatterns = [
path('',views.HomePageView.as_view(),name='home_page'),
path('about/',views.AboutView.as_view(),name='about'),
path('leachers/',views.LeacherListView.as_view(),name='leacher_list'),
path('leachers/<int:pk>/donate/',donate,name='donate'),
]
here I am assigning pk to link:
{% for member in leacher_list %}
<h4>Name : {{ member.name }}</h4>
<h5>Address : {{ member.address }}</h5>
<h5>Location : {{ member.location }}</h5>
<!--original href="donate" -->
<a class="btn btn-primary" href="{% url 'donate' pk=member.pk %}" role="button">Donate</a>
I am new to django.
Please add app_name before namespace in url. I would suggest doing something like this:
<a class="btn btn-primary" href="{% url 'my_app:donate' pk=member.pk %}" role="button">Donate</a>
Here we consider my_app is app_name. Please try this.
I have a problem with update of my DetailView, so once i try to submit the updated values I am receiving an error NoReverseMatch at /task/164/. Could you please give me a hint what is wrong?
Thx!
urls:
path('excel_upload', ex_views.ExcelUploadView.as_view(), name='excel-upload'),
path('user_list', ex_views.UsersListView.as_view(), name = "user-list"),
path('excel_table', ex_views.ExcelTableView.as_view(), name = "excel-table"),
path("task/add", ex_views.TaskAddView.as_view(), name="task-add"),
path("task/<int:pk>/", ex_views.TaskDetailView.as_view(), name="task-detail"),
forms.py
class AddEditTaskForm(forms.ModelForm):
class Meta:
model = Task
exclude = ['created_by']
widgets = {
"due_date": forms.DateInput(attrs={'type':'date'}),
"completed_date": forms.DateInput(attrs={'type': 'date'}),
"name":forms.TextInput(),
"note": forms.Textarea(),
}
views.py
class TaskDetailView(DetailView):
model = Task
template_name = "hana/task_detail.html"
# Add POST method
def post(self, request, pk):
task = get_object_or_404(Task, pk=pk)
form = AddEditTaskForm(request.POST, instance=task)
if "add_edit_task" in request.POST:
if form.is_valid():
form.save()
messages.success(request, "The task has been edited.")
return redirect('excel-table')
return render(request, 'hana/task_detail.html', {'form': form})
error:
NoReverseMatch at /task/164/
Reverse for 'task-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['task\/(?P[0-9]+)\/$']
Request Method: POST
Request URL: http://127.0.0.1:8000/task/164/
Django Version: 3.0.6
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'task-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['task\/(?P[0-9]+)\/$']
Exception Location: /home/lukasz/envtest2/lib/python3.6/site-packages/django/urls/resolvers.py in _reverse_with_prefix, line 677
template:
<form method="post" action="{% url 'task-detail' object.id %}" role="form" class="d-inline">
{% csrf_token %}
<div style="display:inline;">
<button class="btn btn-info btn-sm" type="submit" name="toggle_done">
{% if task.completed %} Mark Not Done {% else %} Mark Done {% endif %}
</button>
</div>
</form>
<a class="btn btn-danger btn-sm mt-1 mb-1" href={% url 'task-delete' object.id %}">Delete</a>
Your issue is caused by mixing class based and function based views. Your function based post view uses the same template as your class based TaskDetailView, but since it doesn't have the same "magic" inherited from DetailView, there is no object passed in the context dictionary (you only pass form).
The proper fix would be to stick to the same view architecture when possible, but a trivial fix would be:
return render(request, 'hana/task_detail.html', {'form': form, 'object': task})