简体   繁体   中英

django url without pk

I have been trying for too long now to get my urls working with my simple models and view. There is something I am definitely not understanding.

I wish to create a url similar to: .../department/team , where I do not use the PK of department object but the name instead.

My model looks like:

class Department(models.Model):
    name = models.CharField(max_length=50, blank=True, null=True)
    def __str__(self):
        return 'Department: ' + self.name

class Hold(models.Model):
    name = models.CharField(max_length=50, blank=True, null=True)
    department = models.ForeignKey(Department, on_delete=models.CASCADE)

my view looks like ( UPDATED ):

class IndexView(generic.ListView):
   template_name = 'index.html'
   context_object_name = 'departments_list'

   def get_queryset(self):
       return Department.objects.all()

class DepartmentView(generic.DetailView):
    model = Department
    template_name="depdetail.html"
    slug_field = "name"
    slug_url_kwarg = "name"

my url looks the following: UPDATED

urlpatterns = [
    path('', views.IndexView.as_view(), name='index'),
    path('<name>', views.DepartmentView.as_view(), name='depdetail')
 ]

and finally my html:

<h1> Hello there {{ object.name }} student</h1> </br>
<b> Choose your team:<b> </br>

however i keep getting page not found or must be slug or pk .. I hope someone can help me out so I can wrap my head around this.

UPDATED It works now :) Thank you for the replies.

By default Django will look for a pk or a slug field when you use a DetailView . You must override get_object() method to change this behaviour:

get_object() looks for a pk_url_kwarg argument in the arguments to the view; if this argument is found, this method performs a primary-key based lookup using that value. If this argument is not found, it looks for a slug_url_kwarg argument, and performs a slug lookup using the slug_field .

That being said, your approach has other problems. It is always better to use a slug instead of a name for other reasons. For example, name is not guaranteed to be unique and also it may have characters which are not URL safe. See this question for a detailed discussion on how to use slug fields.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM