删除带有2个争论的帖子和用户

时间:2018-04-21 22:02:04

标签: python django python-3.x django-views django-urls

我有 2 条件的删除视图"帖子"和"用户"。

用户要求由self.object.user = self.request.user完成,帖子要求由slug = self.kwargs['slug']完成(我认为这可能是罪魁祸首)

我的观点是否正确?

我是 python 的新手,请原谅任何愚蠢的错误。

Views.py

class ProofDelete(LoginRequiredMixin, DeleteView):
    model = Proof

    def delete(self, *args, **kwargs):
        return super().delete(*args, **kwargs)

    def get_success_url(self, *args, **kwargs):
        slug = self.kwargs['slug']
        print(slug)
        obj = get_object_or_404(Post, slug=slug)
        url_ = obj.get_absolute_url()
        user = self.request.user
        if user.is_authenticated():
            if user in obj.made.all():
                obj.made.remove(user)
            else:
                obj.made.add(user)
        return url_

models.py

User = get_user_model() 
class Proof(models.Model):
    user = models.ForeignKey(User, related_name='proofmade')
    post = models.ForeignKey(Post, related_name='proofmade')
    made_at = models.DateTimeField(auto_now=True)
    image_of_proof= models.ImageField()
    proof_ = models.ImageField()
    suggestions = models.TextField(max_length=1000)

def __str__(self):
    return self.post.title

urls.py

    app_name = 'proof'

    urlpatterns = [

        url(r'^new_proof/(?P<slug>[-\w]+)/$', views.ProofCreate.as_view(), name='new_proof'),

        url(r'^proof_delete/(?P<pk>\d+)/$', views.ProofDelete.as_view(),name='proof_delete'),

也尝试了

url (r'^proof_delete/(?P<slug>[-\w]+)/(?P<pk>\d+)/$', views.ProofDelete.as_view(), name='proof_delete'),

我收到以下错误。在视图中指出错误

Error Message Click to see Error message

Same error message after scrolling down. Click to open

1 个答案:

答案 0 :(得分:1)

答案在模板中。在“if”语句解决问题后添加forloop。这样做可以处理Url的两个参数。 “后”模型的“slu”“和”证明“模型的”pk“。没有forloop几乎不可能满足URL的两个参数

正确的网址归功于“Paulo Almeida”

url (r'^proof_delete/(?P<slug>[-\w]+)/(?P<pk>\d+)/$', views.ProofDelete.as_view(), name='proof_delete') 

以下是模板

{% if user in post.made.all %}
    {% for proof in user.proofmade.all %}
        <a href="{% url 'proof:proof_delete' slug=post.slug pk=proof.pk %}">
            <img src="{% static 'images/thumbs_up_RED.png' %}" height="25px">
        </a><br/>
    {% endfor %}
{% else %}
    <a href="{% url 'proof:new_proof' slug=post.slug %}">
        <img src="{% static 'images/thumbs_up_BLANK.png' %}" height="25px">
    </a><br/>
{% endif %}