将主键传递到URL的正确方法应该是什么?

时间:2019-06-27 06:54:46

标签: python django

现在,我正在使用基于类的删除视图,并且URL包含两个参数,它们是我的2个模型的主键:PostLesson。但是,我遇到了Attribute Error: Generic detail view LessonDeleteView must be called with either an object pk or a slug in the URLconf

这是我的两个模型LessonPost

class Post(models.Model):

    title = models.CharField(max_length=100)
    image = models.ImageField(default = 'default0.jpg', upload_to='course_image/')
    description = models.TextField()
    price = models.DecimalField(decimal_places=2, max_digits=6)
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    rating = models.IntegerField(default = 0)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('post-detail', kwargs={'pk' : self.pk})

class Lesson(models.Model):

    title = models.CharField(max_length=100)
    file = models.FileField(upload_to="lesson/pdf")
    date_posted = models.DateTimeField(default=timezone.now)
    post = models.ForeignKey(Post, on_delete=models.CASCADE, null=False, blank=False)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('lesson_upload', kwargs={'pk': self.pk})

这是我的URLs.py:

path('post/<int:post_id>/lesson_uploaded/<int:lesson_id>', LessonDeleteView.as_view(), name='lesson_delete'),

现在这是我尝试在HTML模板中插入参数的方法:

{% block content %}
<div id="main">
    <table class="table mb-0">
    <thead>
      <tr>          
        <th>Title</th>
        <th>Author</th>
        <th>Download</th>
        <th>Delete</th>
      </tr>
    </thead>
    <tbody>
      {% for l in Lesson %}
      <tr>
        <td>
            {% if l.file %}
                {{ l.title }}
            {% else %}                  
            <h6>Not available</h6>
            {% endif %}
        </td>
        <td>{{ l.post.author }}</td>
        <td>{% if l.file %}                 
            <a href="{{ l.file.url }}" class="btn btn-primary btn-sm" target="_blank">Download</a>
            {% else %}
            <h6>Not available</h6>
            {% endif %}    
        </td>
        <td> <a class="btn btn-danger btn-sm mt-1 mb-1" href="{% url 'lesson_delete' post.id l.id %}">Delete</a>
        </td>
      </tr>
      {% endfor %}
    </tbody>
  </table>
</div>
{% endblock %}

这是我基于类的视图:

class LessonDeleteView(DeleteView):

    model = Lesson
    success_url = '../'
    template_name = 'lesson_confirm_delete.html'

2 个答案:

答案 0 :(得分:2)

在删除void Math::foo(int n) { lapack_complex_double* A = new lapack_complex_double[n]; for (int i=0; i<n; i++) A[i] = {0.0, 0.0}; delete A; return; } 时,无需提供Math math(); int num=64; std::thread trd(&Math::foo, &math, num); trd.detach(); ID。您只需在此处使用Lesson ID。所以尝试这样:

Post

更新

在评论部分,您可以像这样覆盖delete方法:

Lesson

答案 1 :(得分:0)

您为什么要传递课程ID。 由于默认情况下删除帖子,因此课程也将被删除。观看此视频,以更好地了解如何在删除视图中传递ID和详细信息。

DeleteView(Class Based Views)