How would I make it so I could pass the model name as a parameter in the url to a view? I would like to reuse this view and just pass the model name through to show a list of whatever model the parameter was.
Heres what I have so far
View
class ModelListView(ListView,objects):
model = objects
template_name = "model_list.html"
def get_context_data(self,**kwargs):
context = super(ModelListView, self).get_context_data(**kwargs)
context['listobjects'] = model.objects.all()
return context
URLS
url(r'^musicpack', MusicPackListView.as_view(), name='musicpack-list', objects = 'MusicPack'),
url(r'^instruments', MusicPackListView.as_view(), name='instrument-list', objects = 'Instrument'),
ANSWERED
Hey thanks for the answer
I've gone with the following and it seems to work.
View
class ModelListView(ListView):
template_name = "model_list.html"
def get_context_data(self,**kwargs):
context = super(ModelListView, self).get_context_data(**kwargs)
return context
URLS
#models
from inventory.views import MusicPack
from inventory.views import Instrument
#views
from inventory.views import ModelListView
url(r'^musicpacks', ModelListView.as_view(model = MusicPack,), name='musicpack-list'),
url(r'^instruments', ModelListView.as_view(model = Instrument,), name='instrument-list'),
I would pass perameter from urls to views like this:
VIEWS:
class ModelListView(ListView):
model = None
model_name= ''
object = None
template_name = "model_list.html"
def get_context_data(self,**kwargs):
context = super(ModelListView, self).get_context_data(**kwargs)
context['listobjects'] = model.objects.all()
return context
URLS:
url(r'^musicpack', ModelListView.as_view( model= MusicPackList,model_name= 'music_pack_list' object = 'MusicPack')),
url(r'^instruments', ModelListView.as_view( model=InstrumentPackList,model_name= 'instrument_pack_list', object= 'InstrumentPack'))
Related
I have two parameters I wish to use to get a single row from my database and use that in my template.
my url looks like:
enter code here{{ divisions }}
my view looks like this but doesn't work:
class detailView(generic.DetailView):
model = divisiondisplay
template_name = 'wondjinainfo/detail.html'
def get_queryset(self):
divisiondisplay.objects.get(divisioncode = divisioncode,freetradezone = freetradezone)
and my model looks like:
class divisiondisplay(models.Model):
freetradezone = models.ForeignKey(ftz, on_delete=models.CASCADE)
divisioncode = models.IntegerField()
bodytext = models.TextField()
imagename = models.CharField(max_length = 25)
def __str__(self):
return self.bodytext
how can I use those two parameters to select my row
I tried this change:
divisiondisplay.objects.get(divisioncode = self.kwargs['divisioncode'],freetradezone = self.kwargs['freetradezone'])
it got me new error of: Generic detail view detailView must be called with either an object pk or a slug.
because my model needed to be searched by fields other than the keys. the detail generic view was the wrong solution. I defined my own view and used it:
def divisiondisplay_detail_view(request,freetradezone, divisioncode):
try:
sometext = divisiondisplay.objects.get(divisioncode = divisioncode, freetradezone = freetradezone)
except divisiondisplay.DoesNotExist:
raise Http404('Book does not exist')
# from django.shortcuts import get_object_or_404
# book = get_object_or_404(Book, pk=primary_key)
return render(request, 'wondjinainfo/detail.html', context={'sometext': sometext})
I need to write a DetailView in Django. I achieved this functionality. However, I need to add some more data along with the context object. How will I achieve this.
My generic view is:
class AppDetailsView(generic.DetailView):
model = Application
template_name = 'appstore/pages/app.html'
context_object_name = 'app'
I need to add one more variable to the context object:
response = list_categories(storeId)
How about using get_context_data
class AppDetailsView(generic.DetailView):
model = Application
def get_context_data(self, **kwargs):
context = super(AppDetailsView, self).get_context_data(**kwargs)
context['categories'] = list_categories(storeId)
return context
Please, help to understand, why the following doesn't work for me.
So, I need display information on a page from logged in user.
In order not to retype code in every view I decided to create a mixin.
class MyMixin(object):
def my_view(self):
args = {}
args['username'] = auth.get_user(request).username
args['first_name'] = auth.get_user(request).first_name
args['last_name'] = auth.get_user(request).last_name
return args
class someview (TemplateView, LoginRequiredMixin, MyMixin):
template_name = 'index.html
But this doesn't show anything in a template.
{{ first_name }}
There are at least two ways of getting these "context variables" into your template:
Your TemplateView already includes ContextMixin. So you could simply override ContextMixin's get_context_data method for that view, like this:
class someview (TemplateView, LoginRequiredMixin):
template_name = 'index.html
def get_context_data(self, **kwargs):
context = super(someview, self).get_context_data(**kwargs)
context['username'] = self.request.user.username
context['first_name'] = self.request.user.first_name
context['last_name'] = self.request.user.last_name
return context
It seems that what you're actually looking for is a more DRY method, not necessarily a mixin. In that case, you should use write your own context_processor:
context_processors.py:
def extra_context(request):
args = {}
args['username'] = auth.get_user(request).username
args['first_name'] = auth.get_user(request).first_name
args['last_name'] = auth.get_user(request).last_name
return args
settings.py:
TEMPLATE_CONTEXT_PROCESSORS += (your_app.context_processors.extra_context,)
This second method will add these three context variables to every template in your app.
Exactly what the title says. I have a mixin that needs to pull in the id of a model field in order to be useful. I assume the easy way to do that would be to pull it from the URL.
class StatsMixin(ContextMixin):
def get_stats_list(self, **kwargs):
# the ??? is the problem.
return Stats.objects.filter(id=???).select_related('url')
def get_context_data(self, **kwargs):
kwargs['stats'] = self.get_stats_list()[0]
print kwargs
return super(StatsMixin, self).get_context_data(**kwargs)
Here's the view implementation for reference.
class ResourceDetail(generic.DetailView, StatsMixin):
model = Submissions
template_name = 'url_list.html'
queryset = Rating.objects.all()
queryset = queryset.select_related('url')
You can access URL parameters in Django by using, self.args and self.kwargs.
i have a dayarchiveview in my django views.py file
class day_archive(DayArchiveView):
model=Timer
paginate_by=12
allow_future =True
allow_empty=True
month_format = '%m'
day_format='%d'
date_field='start_hour'
template_name='timer/timer_archive_date'
def get_queryset(self):
return Timer.objects.filter(author=self.request.user)
but i would like to render the data returned as a table using djangotables2 with something like this:
import django_tables2 as tables
class Job_table(tables.Table):
class Meta:
model = Timer
attrs = {"class": "paleblue"}
fields= ('start_hour','end_hour','category','subcategory','duration')
def render_duration(self,value):
from timehuman import sectohour
hh= sectohour(value)
return hh
how would i render my data as a table instead of the list rendered? ( context object_list by django) how do i access the data thats going to be sent to the object_list context and modify it?
This is what i ended up doing:
may be hackish, but i gives me access to the same data that's going to the view and i can get to render it as a table.
class day_archive(DayArchiveView):
model=Timer
paginate_by=12
allow_future =True
allow_empty=True
month_format = '%m'
day_format='%d'
date_field='begin_time'
template_name='timer/timer_archive_date'
def get_queryset(self):
return Timer.objects.filter(author=self.request.user)
def render_to_response(self, context, **response_kwargs):
"""
Returns a response, using the `response_class` for this
view, with a template rendered with the given context.
If any keyword arguments are provided, they will be
passed to the constructor of the response class.
"""
tbl = context['object_list'] #this line is my hack, i dont know better.
if (tb1 != None):
jt = Timer_table(blo)
RequestConfig(self.request).configure(jt)
from django.db.models import Sum
total = tbl.aggregate(Sum('duration'))
t2 = total['duration__sum']
if (t2 != None):
timedel= str(datetime.timedelta(seconds=float(t2)))
context['table']= jt
context['total'] = timedel
return self.response_class(
request = self.request,
template = self.get_template_names(),
context = context,
**response_kwargs
)