Reputation: 561
I have wrote models,views and urls like this
class PreventionField(models.Model):
name = models.SlugField(max_length=200)
verbose_name = models.CharField(max_length=200)
class PreventionFieldDetailView(DetailView):
model = PreventionField
template_name = 'prevention-fields-details.html'
template_name = "prevention-field-details.html"
def get_object(self, **kwargs):
return PreventionField.objects.get(slug=self.kwargs['slug'])
urlpatterns = [
url(r'^$', Frontpage.as_view(), name='frontpage'),
path('fields/<slug>/',PreventionFieldDetailView.as_view(),name='fields')]
And what I want is to generate slug urls based on entries in PreventionField model that I can switch between subpages in my website like
http://mywebsite.com/fields/neuro where neuro slugfield from model,but this return error
and ok,so I have to switch from 'slug' into 'name' because this is my SlugField in model PreventionField,right? Well, when I change views.py code to
return PreventionField.objects.get(slug=self.kwargs['name'])
then got following error:
and now I've lost it.
I don't understand why DetailView works this way and how I should change it to obtain slug url.
I should mention that I didin't have problems when I was using pk instead of slug.
Upvotes: 3
Views: 1023
Reputation: 600041
You've got this the wrong way round. The field in your model is called name
. So:
return PreventionField.objects.get(name=self.kwargs['slug'])
It would be much better though to just set slug_field = 'name'
at class level in the view, then you don't need to define get_object
at all.
Upvotes: 2