Django Pass additional parameters from a link to another view - python

I have a page drag.htmlwhich is served at this URL
http://localhost:8000/dashboard?wid=ca1480f&ref_url=localhost&adpart=left this page have a link
<a id="btn-start" href="/dashboard/save" class="btn">Save Reward</a>
when a user click this link it will redirect to a SaveRewardview where i want to save all the information present in link i.e wid=ca1480f&ref_url=localhost&adpart=left
urls.py
url(r'^dashboard$', login_required(CouponPageView.as_view()), name='dashboard'),
url(r'^dashboard/save$', login_required(SaveRewardView.as_view()), name=''),
model.py
class SaveReward(models.Model):
widget = EmbeddedModelField(Widget)
campaign = EmbeddedModelField(Campaign)
coupon_part = models.CharField(max_length=200)
saved_on = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return self.widget.widget_name
Views.py
class SaveRewardView(TemplateView):
#Here how i will get wid , ref_url, adpart which is present in url parameters

You can directly give parameters in url like this.
<a id="btn-start" href="/dashboard/?{{request.META.QUERY_STRING}}" class="btn">Save Reward</a>
url is:
url(r'^dashboard/$', login_required(CouponPageView.as_view()), name='dashboard'),

Related

Django 3.0.8 URL/Template/Routing Troubles "No reverse match"

first post so please forgive my ignorance as this is my first django app.
I am trying to create a template that displays all of the information regarding a specific "Ticket" from a list of all open tickets.
Unfortunately I am receiving following message whenever I attempt to add an anchor with a template url tag:
NoReverseMatch at /tickets/tasks/ Reverse for 'order' with arguments
'('',)' not found. 1 pattern(s) tried:
['tickets/order/(?P<ticket_id>[^/]+)/$']
Error message updated. Please see Update below.
And it is ONLY on this one HTML Template.
Below is all of the code I believe will be able to shed some light into the issue:
models.py:
from django.db import models
# Create your models here.
class Ticket(models.Model):
"""A basic support ticket"""
# User ticket title.
ticket_Name = models.CharField(max_length=50)
# When the request was submitted.
ticket_Submitted = models.DateTimeField(auto_now_add=True)
#Ticket Type
ticketTypeChoices=[
('Update', 'Article Edit/Update'),
('Addition', 'New Content/Article Request'),
('Typo', 'Article Typo/Formatting Issue'),
('Issue', 'Website Error/Issue'),
('Other', 'Other'),
]
# Type of ticket (Update, Addition, Typo, Site Issue)
ticket_Type = models.CharField(
max_length=50,
choices=ticketTypeChoices,
default= 'Other'
)
# Users Name
ticket_Contact = models.CharField(max_length=50)
# User Email (for follow up)
ticket_Email = models.EmailField(max_length=254)
# Article URL (if applicable)
ticket_URL = models.CharField(blank=True, max_length=254)
# User description of the issue.
ticket_Description = models.TextField()
#Ticket Status Choices
StatusChoices = [
('Pending', 'Pending'),
('Open', 'Open'),
('Complete', 'Complete'),
('Deferred', 'Deferred'),
('Awaiting Response', 'Awaiting Response'),
]
# Status of the Ticket
ticket_Status = models.CharField(
max_length=50,
choices=StatusChoices,
default= 'Pending'
)
# Comments from HelpDesk Staff
ticket_Comments = models.TextField(blank=True )
#Shows when the ticket was last saved.
ticket_Last_Updated = models.DateTimeField(auto_now=True)
def __str__(self):
"""Return a string representation of the model"""
return self.ticket_Name
views.py:
# Imports Models from the app
from . models import *
# Imports from the Forms List
from . forms import TicketForm
# Create your views here.
# View of all active tickets
def ticket(request):
tickets = Ticket.objects.all().order_by('-ticket_Submitted')
context = {'ticket': tickets}
return render(request, 'tickets/joblist.html', context)
# User can view details about a Ticket
def order(request, ticket_id):
order = Ticket.objects.get(id=ticket_id)
context= {'order': order}
return render(request, 'tickets/tix.html', context)
urls.py
from django.urls import path,include
from . import views
app_name='tickets'
urlpatterns = [
# Include default auth urls.
path('', include('django.contrib.auth.urls')),
# Support Ticket Form
path('submit/', views.submit, name='submit'),
# Contact Us Form
path('contact/', views.contact, name='contact'),
# TicketWeblist
path('tasks/', views.ticket, name='tasks'),
# Ticket Details
path('order/<str:ticket_id>/', views.order, name='order' )
]
Template (joblist.html):
{% for tickets in ticket %}
<tr>
<td>{{tickets.ticket_Name}}</td>
<td>{{tickets.ticket_Type}}</td>
<td>{{tickets.ticket_Contact}}</td>
<td>{{tickets.ticket_Status}}</td>
<td>{{tickets.ticket_Submitted}}</td>
<td>{{tickets.ticket_Last_Updated}}</td>
<td><a class="btn btn-sm btn-info" href="{% url 'tickets:order' ticket.id %}">View</a>
</tr>
{% endfor %}
After reviewing the code a dozen time, all I can be sure of is that is an issue that begins with the template anchor template url tag. (View) but no matter what format I try it comes up with this or a similar error.
UPDATE: At Mel's suggestion changed the url 'order' to 'tickets:order' and am now receiving the following message:
NoReverseMatch at /tickets/tasks/ Reverse for 'order' with arguments
'('',)' not found. 1 pattern(s) tried:
['tickets/order/(?P<ticket_id>[^/]+)/$']
I have been attempting to resolve this issue for about three days and was determined to solve it myself. Any type of help is appreciated and please feel free to point out any spaghetti code or lack of notes as well as I am looking for ways to grow.
Thanks!
You've set a namespace for your urls: app_name = 'tickets'
So correct reverse url would be.
{% url 'tickets:order' tickets.id %}
Can you try changing your order view function to this -
def order(request, ticket_id):
active_order = Ticket.objects.get(id=ticket_id)
context= {'order': active_order}
return render(request, 'tickets/tix.html', context)
You have created a separate urls.py for you app (it looks like it), so be sure to include namespace = tickets in your project urls.py file. And then in your template, you should do as follows:
{% url 'tickets:order' ticket.id %}
In other words, you need to include the name of the app as well.
I just saw that you are passing ticket.id from your template to the view, however there is no ticket.id anywhere in the code. Why don't you try passing a value that is there in the template. It should work.

How to connect Detail Class Based View to Template URL Mapping?

How to connect Detail Class Based View to Template URL Mapping?
Here is views.py file in myapp:
class ModelDetailView(DetailView):
model = models.mymodel
template_name = 'mymodel_detail.html'
Here is urls.py of myapp
.....path('<pk>', ModelDetailView.as_view(), name = 'detail')...........
Here is mymodel_detail.html file:
........<li>{{ object.title }}</li>.......
I want that when I click on object.title, it leads me to its detailed view? How do I do that?
Have also tried: (urls.py)
path('(?P<pk>[-\W]+)/', ModelDetailView.as_view(), name = 'detail')
and
path('detail<pk>', ModelDetailView.as_view(), name = 'detail'),
path('detail/<int:pk>/', ModelDetailView.as_view(), name ='detail'),

Problem getting a delete button on an UpdateView to redirect

Python and Django newbie here
I've been trying to get a delete button onto a standard UpdateView form from Django and then get that to redirect to the DeleteView if that button is pressed instead of the submit button. I have that working but im not sure how to redirect to the corresponding delete page on click.
I expect i need to change the reverse_lazy('app:submission_delete') to include the id somehow but im a bit lost here, and my google fu isnt helping much either.
views.py
class AssessmentUpdate(UpdateView):
model = Submission
fields = '__all__'
success_url = reverse_lazy('app:index')
def form_valid(self, request):
if 'Delete' in self.request.POST:
reverse_lazy('app:Submission_delete')
else:
self.object = request.save()
return HttpResponseRedirect(self.get_success_url())
urls.py
app_name = 'app'
urlpatterns = [
re_path(r'^$', views.index, name='index'),
path('<int:submission_id>/', views.detail, name='detail'),
path('<int:pk>/update/', views.AssessmentUpdate.as_view(), name='Submission_update'),
path('<int:pk>/delete/', views.AssessmentDelete.as_view(), name='Submission_delete'),
]
If a URL needs args or kwargs:
reverse_lazy('app:Submission_delete', kwargs={'pk': object.pk})
where object is the object which would be deleted.
ALTERNATIVELY:
Just use a regular hyper link to the delete page. Use django's template tag url for that:
{% url 'app:Submission_delete' pk=object.pk %}
You can still style that link like a button via CSS, so user's wouldn't even know the difference.

Facing issue in building nested URL in Django 1.11

I am trying to create a Hierarchy where in homepage user has option to select Location in their Homepage and then once they select the location they get Respective Managers from that location and next once they select the managers they get respective associate.
Diagram -> (Homepage) all locations -on select specific location- > Managers - on select specific Manager- > List of associate (aligned to the manager )
Url Patterns:
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^(?P<hierarchy_id>[0-9]+)/$', views.managerview, name='managerview'),
url(r'(?P<associate_id>[0-9]+)/$', views.associatelist, name='associatelist'),
]
Views:
def index(request):
all_sites = Hierarchy.objects.all()
return render(request, "adash/index.html", {'all_sites': all_sites})
def managerview(request, hierarchy_id):
all_managers = Hierarchy.objects.get(pk=hierarchy_id)
return render(request, "adash/manager.html", {'all_managers': all_managers})
def associatelist(request, associate_id):
all_logins = Hierarchy.objects.get(pk=associate_id)
return render(request, "adash/associatelist.html", {'all_logins': all_logins})
Manager Html
<a class="list-group-item list-group-item-action"><h5 class = "text-monospace">{{ all_managers.direct_manager }}</h5></a>
Associate Html
<a class="list-group-item list-group-item-action"><h5 class = "text-monospace">{{ all_logins.login }}</h5></a>
currently am able to click on location and direct it to respective managers associated with that site but how to proceed to next step i.e click on manager and show list of associate.
Below is my model:
class Hierarchy(models.Model):
site = models.CharField(max_length=250)
direct_manager = models.CharField(max_length=250)
login = models.CharField(max_length=250)
Your direct_manager field needs to be a relationship, not a text field. This is a recursive relationship, where an instance of Hierarchy points to another instance which is its manager. So:
direct_manager = models.ForeignKey('self', related_name='direct_reports')
Now, given an instance of Hierarchy which is a manager, you can get all associates via the reverse relation:
associates = my_manager.direct_reports.all()

How can I get Django to create a unique URL view and page for each URLField entered

I'm trying to create a small app in a django project where when a URL is inputted into the URLField form, then a separate page is created for each URL creating a sort of directory page for each link people submit. For example, if I enter the URL http://www.facebook.com/username1 or http://www.facebook.com/username2 I'd like django to create a new page at www.mysite.com/username1 and www.mysite.com/username2 respectively. What's the best way to go about this? Thanks in advance very much! Here is my basic code for the Form field:
class newlinkform(forms.ModelForm):
link_comment = forms.CharField(max_length=256) #comment to go along with URL entered
url = forms.URLField(max_length = 512) #actual submitted link I'd like to get a view mapped to
class Meta:
model = newlink
If you had something like this in your urls.py:
...
url(r'URL/^(?P<url_param>[a-zA-Z0-9_]*)/$', 'views.view_for_all_pages', name='view_for_all_pages')
...
Then your views.py could look like this:
from django.shortcuts import render as render_original
def view_for_all_pages ( request, url_param ):
render (request, "template.html", { "url_param" : url_param })
And your template:
<h1>URL entered: {{url_param}}</h1>
Then you could request: http://yourserver.com:8000/URL/foo to see <h1>URL entered: foo</h1>

Categories

Resources