Django function redirects back to class - python

I am trying to get it so anytime my function delete_curricula_info is activated it then redirects to CurriculumClasses url
class CurriculumClasses(TemplateView):
template_name = 'architect/assignclasses.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['form'] = AssignClassForm(self.request.GET or None)
context['classes'] = Classes.objects.all()
context['curricula_infos'] = CurriculaInfo.objects.all()
context['course_abbr'] = self.kwargs.get('course_abbr')
context['year'] = self.kwargs.get('year')
context['semester'] = self.kwargs.get('semester')
context['module_abbr'] = self.kwargs.get('module_abbr')
context['curricula'] = Curricula.objects.get(
course_period__course__course_abbreviation=self.kwargs.get('course_abbr'),
module_period__module__module_abbreviation=self.kwargs.get('module_abbr'),
course_period__period__academic_year=self.kwargs.get('year'),
course_period__period__semester=self.kwargs.get('semester')).pk
return context
def delete_curricula_info(request, pk):
curricula_info = get_object_or_404(CurriculaInfo, pk=pk)
curricula_info.delete()
return redirect('curriculum_classes')
Heres my urls.py
path('courses/<str:course_abbr>/<str:module_abbr>/<int:year>/<int:semester>/classes/',
views.CurriculumClasses.as_view(), name='curriculum_classes'),
path('delete-curricula-info/<int:pk>/', views.delete_curricula_info, name='delete_curricula_info')
The url for my CurriculumClasses is using a dynamic one so i could not hardcode the url to the return redirect of my function. So how do i redirect as my current method does not work. Thanks.

You can redirect it like this:
from django.urls import reverse
def delete_curricula_info(request, pk):
curricula_info = get_object_or_404(CurriculaInfo, pk=pk)
curricula_info.delete()
course_abbr = 'xxx'
module_abbr = 'xxx'
year = 2018
semester = 1
args = (course_abbr, module_abbr, year, semester)
return redirect(reverse('curriculum_classes', args=args))

Related

django can't reverse match url from template

I am having difficulty reverse matching a url, getting the error:
NoReverseMatch at /patient/46cb4bd5-ef39-4697-84ff-9aa2b6e85e6b/
Reverse for 'treatment_detail' with no arguments not found. 1 pattern(s) tried: ['patient/(?P<patient_id>[^/]+)/$']
The url is:
/patient/46cb4bd5-ef39-4697-84ff-9aa2b6e85e6b/
(the string is the 'apatient_id' and changes each time the user submits the 'add' page)
urls.py is
app_name = "patient"
urlpatterns = [
path(
route='add/',
view=views.PatientAddView.as_view(),
name="patient_add"),
path(
route='<patient_id>/',
view=views.TreatmentTemplateView.as_view(),
name='treatment_detail'),
]
html
<form action="{% url 'patient:treatment_detail' %}" method="get">
<input type="submit" class="btn btn-primary" value="get_doc" name="get_doc">
</form>
views.py
class TreatmentTemplateView(TemplateView):
template_name = "../templates/patient/treatment_detail.html"
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)
context["patient_id"] = self.kwargs["patient_id"]
result = find_treatment(context["patient_id"])
context = result[0]
context["patient"] = result[1]
return context
class PatientAddView(LoginRequiredMixin, TemplateView):
model = Patient
template_name = "../templates/patient/add.html"
def get(self, *args, **kwargs):
patient_form = PatientForm
currentmed_formset = CurrentmedFormSet(queryset=CurrentMed.objects.none())
pastmed_formset = PastmedFormSet(queryset=PastMed.objects.none())
diagnosis_formset = DiagnosisFormSet(queryset=Diagnosis.objects.none())
problem_formset = ProblemFormSet(queryset=Problem.objects.none())
sideeffect_formset = SideeffectFormSet(queryset=SideEffect.objects.none())
return self.render_to_response(
{
"diagnosis_formset": diagnosis_formset,
"problem_formset": problem_formset,
"sideeffect_formset": sideeffect_formset,
"currentmed_formset": currentmed_formset,
"pastmed_formset": pastmed_formset,
"patient_form": patient_form,
"med_formsethelper": MedFormSetHelper,
"problem_formsethelper": ProblemFormSetHelper,
"diagnosis_formsethelper": DiagnosisFormSetHelper,
"sideeffect_formsethelper": SideEffectFormSetHelper,
}
)
def post(self, *args, **kwargs):
form = PatientForm(data=self.request.POST)
currentmed_formset = CurrentmedFormSet(data=self.request.POST)
pastmed_formset = PastmedFormSet(data=self.request.POST)
diagnosis_formset = DiagnosisFormSet(data=self.request.POST)
problem_formset = ProblemFormSet(data=self.request.POST)
sideeffect_formset = SideeffectFormSet(data=self.request.POST)
if form.is_valid():
print("pt_valid")
patient_instance = form.save()
patient_instance.user = self.request.user
patient_instance.save()
if diagnosis_formset.is_valid():
print("diag_valid")
diag_name = diagnosis_formset.save(commit=False)
for diag in diag_name:
diag.patient = patient_instance
diag.save()
if problem_formset.is_valid():
prob_name = problem_formset.save(commit=False)
for prob in prob_name:
prob.patient = patient_instance
prob.save()
if sideeffect_formset.is_valid():
se_name = sideeffect_formset.save(commit=False)
for se in se_name:
se.patient = patient_instance
se.save()
if currentmed_formset.is_valid():
med_name = currentmed_formset.save(commit=False)
for med in med_name:
med.patient = patient_instance
med.save()
if pastmed_formset.is_valid():
med_name = pastmed_formset.save(commit=False)
for med in med_name:
med.patient = patient_instance
med.save()
return redirect(
reverse(
"patient:treatment_detail",
kwargs={"patient_id": patient_instance.patient_id},
)
)
If I have 'patient:patient_add' instead of 'patient:treatment_detail' it works fine so the issue seems to be about the
route="<patient_id>"/
In urls.py
Your url route should include patient_id such that:
path(
route='<uuid:patient_id>/',
view=views.TreatmentTemplateView.as_view(),
name='treatment_detail'),
I assume you're using uuid field in your model.
You can take a look at the docs for more detail.
In your template, you should also pass uuid field to the template tag:
"{% url 'patient:treatment_detail' patient.patient_id %}"

How can I pass a model id from the url to a class based view?

I have a class-based view:
class Create(View):
note_id = None
http_method_names = ['post', 'patch']
default_title = "You fool! This was left empty"
default_body = "Why did you leave this blank :("
def dispatch(self, *args, **kwargs):
method = self.request.POST.get('_method', '').lower()
print('method = ', method)
if method == 'patch':
return self.patch(*args, **kwargs)
elif method == 'post':
self.post(*args, **kwargs)
return super(Create, self).dispatch(*args, **kwargs)
def post(self, note_id):
date = datetime.date.today()
title = self.request.POST.get('title', '')
body = self.request.POST.get('note', '')
# check for blank attributes
if title == "":
title = Create.default_title
if body == "":
body = Create.default_body
note = Note(note_title=title, note_body=body, publish_date=date, edit_date=None)
note.save()
return HttpResponseRedirect(reverse('notes:note'))
def patch(self, note_id):
note = Note.objects.get(id=note_id)
title = self.request.POST.get('title', '')
body = self.request.POST.get('note', '')
# if something changed
if title != note.note_title or body != note.note_body:
# check for blank attributes
if title == "":
title = Create.default_title
if body == "":
body = Create.default_body
note.note_title = title
note.note_body = body
note.edit_date = datetime.date.today()
note.save()
return HttpResponseRedirect(reverse('notes:note'))
and in url.py I have
urlpatterns = [
path('<int:note_id>/create/', views.Create.as_view(), name='create'),
path('<int:note_id>/edit/', views.Create.as_view(), name='edit')
]
Previously, with function-based views the note_id would just be passed to the function automatically. I can not figure out the equivalent of this in class based views. I've tried explictiely passing note_id to each function, but that did not work. I tried included Create.as_view(note_id=note_id) in my url.py, but to no avail.
Currently, running this code I get:
post() got multiple values for argument 'note_id'
As mentioned in the comment above, you need to access these values through self.kwargs. e.g:
class Create(View):
note_id = None # Delete this line
...
# delete the dispatch method - no need to overwrite this.
# Don't include note_id as an argument, but request should be an argument
def post(self, request):
note_id = self.kwargs['note_id']
....
def put(self, request): # Likewise here
note_id = self.kwargs['note_id']
....
It doesn't look like you need to write a custom dispatch method. If all you are doing is calling the appropriate method, then the dispatch method that comes for free with View is just fine :)

How to move some code from post method to a separate method in Django views

I have a class that take some info from a form, make some changes to it. And than saves it into database
At the moment all the logic is in the post method. And I want to make the code more structured and I want to put some part of it to a separate method. Is it possible? If so, how can I do it?
here is my code:
class AddSiteView(View):
form_class = AddSiteForm
template_name = 'home.html'
def get(self, request, *args, **kwargs):
form = self.form_class()
return render(request, self.template_name, { 'form': form })
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
if form.is_valid():
site_instanse = form.save()
url = request.POST.get('url', '')
if url.endswith('/'):
url = url + "robots.txt"
else:
url = url + "/robots.txt"
robot_link = Robot(
site = site_instanse,
link = url,
)
robot_link.save()
pk = Robot.objects.get(site=site_instanse)
return redirect('checks:robots', pk.id)
return render(request, self.template_name, { 'form': form })
I want to make 2 changes to it:
The 1st thing I want to do is to move this part of code to a separate method
if url.endswith('/'):
url = url + "robots.txt"
else:
url = url + "/robots.txt"
And the 2nd thing I want to do is to move this part of code also in a separate method
robot_link = Robot(
site = site_instanse,
link = url,
)
robot_link.save()
pk = Robot.objects.get(site=site_instanse)
return redirect('checks:robots', pk.id)
The reason is that I will be adding more functions here. And I don't want to have it all in post method. If it is possible, please, help me. I've already tried several ways of solving this problem, but they didn't work
Thank you
There is nothing special about Django preventing you from using plain python functions. So, if you know how to define methods and functions, you should take the same approach. For example, the first part can be the function
def get_robots_url(url):
if url.endswith('/'):
url = url + "robots.txt"
else:
url = url + "/robots.txt"
return url
Then you call the extracted function in the same place
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
if form.is_valid():
site_instance = form.save()
url = request.POST.get('url', '')
url = get_robots_url(url)
....
You can also define a function inside the class - a method, to group the code. For the 2nd part:
class AddSiteView(View):
...
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
if form.is_valid():
site_instanse = form.save()
url = request.POST.get('url', '')
url = get_robots_url(url)
return self.create_robot(site_instanse, url)
return render(request, self.template_name, { 'form': form })
def create_robot(self, site_instance, url):
robot_link = Robot(
site = site_instanse,
link = url,
)
robot_link.save()
pk = Robot.objects.get(site=site_instance)
return redirect('checks:robots', pk.id)

Django Pagination: switch between paginated/non-paginated ListView

I'm trying to elaborate a smart way to switch between a paginated template and a non-paginated one.
I already have a working paginator and I was thinking of adding a button next to it that read "Show all results" that linked to a non-paginated list, from there then there would be another button to go back to the paginated list.
1) Easy Solution
Use 2 ListViews with different assignations of the attribute paginate_by (django default to set pagination), but since I have many lists in my project it wouldn't be convenient (not much smart either).
2) Solution I'm stuck on
Write a Mixin (that will later be extended by my ListViews) to set the variable paginate_by based on a condition and then add some useful variables to the context :
class PaginationMixin:
no_pagination = False
no_pagination_url = ''
def get_paginate_by(self, queryset):
# overwrite django method
if self.no_pagination:
return None
else:
return super().get_paginate_by(queryset)
def get_no_pagination_url(self):
return self.no_pagination_url
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['no_pagination'] = self.no_pagination
context['no_pagination_url'] = self.get_no_pagination_url()
return context
class MyListView(PaginationMixin, ListView):
#...
def get_no_pagination_url(self):
return reverse('mylist_urlname')
PROBLEM: I don't know how to set the no_pagination variable from the template. Is there some way to do this?
Thanks for the help.
UPDATED SOLUTION (edited from #hi-lan solution):
This way it will show all results and also keep urlparams (from filters or other) if present.
class PaginationMixin:
toggle_pagination = False
toggle_pagination_url = ''
no_pagination = False
view_name = ''
urlparams_dict = {}
def get(self, request, page=None, *args, **kwargs):
#store current GET params and pop 'page' key
self.urlparams_dict = request.GET
self.urlparams_dict.pop('page', None)
page = page or request.GET.get('page', '1')
if page == 'all':
page = self.paginate_by = None
self.no_pagination = True
return super().get(request, page=page, *args, **kwargs)
def get_paginate_by(self, queryset):
if self.no_pagination:
return None
else:
return super().get_paginate_by(queryset)
def get_toggle_pagination_url(self):
# variables to set in view to toggle this mixin
if self.toggle_pagination and self.view_name:
if not self.no_pagination:
extra = {'page': 'all'}
self.urlparams_dict.update(extra)
else:
self.urlparams_dict.pop('page', None)
# url keeps track of urlparams adds page=all if toggled
self.toggle_pagination_url = reverse(self.view_name) + '?' + urlencode(self.urlparams_dict)
return self.toggle_pagination_url
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['toggle_pagination_url'] = self.get_toggle_pagination_url()
context['toggle_pagination'] = self.toggle_pagination
return context
The problem is at data flow back from user to indicate non pagination. The only way I can think of is to use special page number. There are two options, depends on which way you config urls.py.
In case of path('objects/page<int:page>/',
PaginatedView.as_view()), special number is 0 (as normal page number
is started from 1).
In case of /objects/?page=3, special number can be all.
In either case, we need to override get method as it is where we can retrieve user's selection.
class PaginationMixin:
no_pagination = False
view_name = ''
def get(self, request, page=None, *args, **kwargs):
page = page or request.GET.get('page', '1')
if page in ['0', 'all']:
page = self.paginate_by = None
else: pass
return super().get(request, page=page, *args, **kwargs)
def get_paginate_by(self, queryset):
# overwrite django method
if self.no_pagination:
return None
else:
return super().get_paginate_by(queryset)
def get_no_pagination_url(self):
# For using path
extra = {'page': '0'}
no_pagination_url = reverse(self.view_name, kwargs=extra)
# For using query params
extra = {'page': 'all'}
no_pagination_url = reverse(self.view_name) + '?' + urlencode(extra)
return no_pagination_url
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['no_pagination'] = self.no_pagination
context['no_pagination_url'] = self.get_no_pagination_url()
return context
class MyListView(PaginationMixin, ListView):
view_name = 'mylist_urlname'
#...
I'm trying the UPDATED SOLUTION of gccallie with this view :
class StageTempList(PaginationMixin, LoginRequiredMixin, SingleTableMixin, FilterView):
view_name = 'stagetemp-list'
table_class = StageTempTable
model = StageTemp
filterset_class = StageTempFilter
template_name = 'stage/stagetemp_list.html'
paginate_by = 30
strict = False
But when get_paginate_by return None, I get 25 rows.
Django version 2.1.2
UPDATE : the PaginationMixin Class I use
class PaginationMixin:
no_pagination = False
view_name = ''
def get(self, request, page=None, *args, **kwargs):
page = page or request.GET.get('page', '1')
if page in ['0', 'all']:
page = self.paginate_by = None
self.no_pagination = True
else: pass
return super().get(request, page=page, *args, **kwargs)
def get_paginate_by(self, queryset):
# overwrite django method
if self.no_pagination:
return None
else:
return super().get_paginate_by(queryset)
def get_no_pagination_url(self):
extra = {'page': 'all'}
no_pagination_url = reverse(self.view_name) + '?' + urlencode(extra)
return no_pagination_url
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['no_pagination'] = self.no_pagination
context['no_pagination_url'] = self.get_no_pagination_url()
return context

Django Gaurdian + Haystack search results permissions

I am trying to limit the results a user returns during a search based on permissions in django guardian... I have tried many things, but i am going in circles. Any advice would be appreciated :
Scenario : user should only see search results in which they have view_product permissions to.
In my search template i added :
{% load guardian_tags %}
{% get_obj_perms request.user for product as "product_perms" %}
{% if "view_product" in product_perms %}
Which results in Exception Type: VariableDoesNotExist
haystack urls.py
from __future__ import unicode_literals
try:
from django.conf.urls import patterns, url
except ImportError:
from django.conf.urls.defaults import patterns, url
from haystack.views import SearchView
urlpatterns = patterns('haystack.views',
url(r'^$', SearchView(), name='haystack_search'),
)
haystack views.py
from __future__ import unicode_literals
from django.conf import settings
from django.core.paginator import Paginator, InvalidPage
from django.http import Http404
from django.shortcuts import render_to_response
from django.template import RequestContext
from haystack.forms import ModelSearchForm, FacetedSearchForm
from haystack.query import EmptySearchQuerySet
RESULTS_PER_PAGE = getattr(settings, 'HAYSTACK_SEARCH_RESULTS_PER_PAGE', 20)
class SearchView(object):
template = 'search/search.html'
extra_context = {}
query = ''
results = EmptySearchQuerySet()
request = None
form = None
results_per_page = RESULTS_PER_PAGE
def __init__(self, template=None, load_all=True, form_class=None, searchqueryset=None, context_class=RequestContext, results_per_page=None):
self.load_all = load_all
self.form_class = form_class
self.context_class = context_class
self.searchqueryset = searchqueryset
if form_class is None:
self.form_class = ModelSearchForm
if not results_per_page is None:
self.results_per_page = results_per_page
if template:
self.template = template
def __call__(self, request):
"""
Generates the actual response to the search.
Relies on internal, overridable methods to construct the response.
"""
self.request = request
self.form = self.build_form()
self.query = self.get_query()
self.results = self.get_results()
return self.create_response()
def build_form(self, form_kwargs=None):
"""
Instantiates the form the class should use to process the search query.
"""
data = None
kwargs = {
'load_all': self.load_all,
}
if form_kwargs:
kwargs.update(form_kwargs)
if len(self.request.GET):
data = self.request.GET
if self.searchqueryset is not None:
kwargs['searchqueryset'] = self.searchqueryset
return self.form_class(data, **kwargs)
def get_query(self):
"""
Returns the query provided by the user.
Returns an empty string if the query is invalid.
"""
if self.form.is_valid():
return self.form.cleaned_data['q']
return ''
def get_results(self):
"""
Fetches the results via the form.
Returns an empty list if there's no query to search with.
"""
return self.form.search()
def build_page(self):
"""
Paginates the results appropriately.
In case someone does not want to use Django's built-in pagination, it
should be a simple matter to override this method to do what they would
like.
"""
try:
page_no = int(self.request.GET.get('page', 1))
except (TypeError, ValueError):
raise Http404("Not a valid number for page.")
if page_no < 1:
raise Http404("Pages should be 1 or greater.")
start_offset = (page_no - 1) * self.results_per_page
self.results[start_offset:start_offset + self.results_per_page]
paginator = Paginator(self.results, self.results_per_page)
try:
page = paginator.page(page_no)
except InvalidPage:
raise Http404("No such page!")
return (paginator, page)
def extra_context(self):
"""
Allows the addition of more context variables as needed.
Must return a dictionary.
"""
return {}
def create_response(self):
"""
Generates the actual HttpResponse to send back to the user.
"""
(paginator, page) = self.build_page()
context = {
'query': self.query,
'form': self.form,
'page': page,
'paginator': paginator,
'suggestion': None,
}
if self.results and hasattr(self.results, 'query') and self.results.query.backend.include_spelling:
context['suggestion'] = self.form.get_suggestion()
context.update(self.extra_context())
return render_to_response(self.template, context, context_instance=self.context_class(self.request))
haystack forms.py
def search(self):
if not self.is_valid():
return self.no_query_found()
if not self.cleaned_data.get('q'):
return self.no_query_found()
sqs = self.searchqueryset.auto_query(self.cleaned_data['q'])
if self.load_all:
sqs = sqs.load_all()
return sqs

Categories

Resources