向Django URL传递多个参数意外的关键字argumen

2024-09-30 05:29:06 发布

您现在位置:Python中文网/ 问答频道 /正文

如何解决这个NoReverseMatch错误?在

上下文

我想尽可能多地记录这个问题,以便能够详细说明问题的起源。在

我有一个名为LodgingOffer的模型,可以创建一个住宿优惠,并有详细的信息

class LodgingOffer(models.Model):

    # Foreign Key to my User model      
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

    ad_title = models.CharField(null=False, blank=False,
        max_length=255, verbose_name='Título de la oferta')

    slug = models.SlugField(max_length=100, blank=True)

    # ... Another fields ...

    def __str__(self):
        return "%s" % self.ad_title

    def get_absolute_url(self):
        return reverse('host:detail', kwargs = {'slug' : self.slug })

# I assign slug to offer based in ad_title field,checking if slug exist
def create_slug(instance, new_slug=None):
    slug = slugify(instance.ad_title)
    if new_slug is not None:
        slug = new_slug
    qs = LodgingOffer.objects.filter(slug=slug).order_by("-id")
    exists = qs.exists()
    if exists:
        new_slug = "%s-%s" % (slug, qs.first().id)
        return create_slug(instance, new_slug=new_slug)
    return slug

# Brefore to save, assign slug to offer created above.
def pre_save_article_receiver(sender, instance, *args, **kwargs):
    if not instance.slug:
        instance.slug = create_slug(instance)

pre_save.connect(pre_save_article_receiver, sender=LodgingOffer)

对于这个模型,我有一个名为HostingOfferDetailView的详细视图。在

我想追求的一个重要目标是,在LodgingOffer对象的详细视图中,我应该能够联系该offer的所有者(objectLodgingOffer-创建它的用户),以便其他感兴趣的用户可以应用它。在

我希望在LodgingOffer对象的详细视图中能够联系报价所有者(objectLodgingOffer-创建它的用户),这样其他感兴趣的用户就可以应用它了

为此,我有一个contact_owner_offer()函数,在这个函数中我向这个报价的所有者发送电子邮件。在

我使用HostingOfferDetailView详细信息视图,如下所示:

^{pr2}$

我的contact_owner_offer()函数接收这些报价参数并向报价的所有者或发布者发送电子邮件,如下所示:

def contact_owner_offer(request, lodging_offer_owner_email, user_interested_email, lodging_offer_title):
    user = request.user
    if user.is_authenticated:
        # print('Send email')
        mail_subject = 'Interest in your offer'

        context = {
            'lodging_offer_owner_email': lodging_offer_owner_email,
            # User owner offer - TO send email message

            'offer': lodging_offer_title,
            # offer for which a user asks 

            'user_interested_email': user_interested_email,
            # Interested user offer

            'domain': settings.SITE_URL,
            'request': request
        }

        message = render_to_string('contact_user_own_offer.html', context)
        #to_email = lodging_offer_owner.email,

        send_mail(mail_subject, message, settings.DEFAULT_FROM_EMAIL,
                  [lodging_offer_owner_email], fail_silently=True)

我做了一个测试,到目前为止,一切都是我想要的,结果是当我输入一个详细的offer对象LodgingOffer的URL时,会向该offer的所有者发送一封电子邮件。在

我希望优惠详情模板有一个包含联系优惠所有者“的按钮,当任何用户按下该按钮时,会向优惠的所有者发送电子邮件。在

为此,我为contact_owner_offer()函数定义了一个URL,它在我的模板中有一个按钮的href属性的链接。在

我根据contact_owner_offer()函数接收到的参数数量定义了URL(根据我的理解,这就是我的疑问和问题的原因所在)。在

这意味着我的URL必须接收:

  • 报价所有者的电子邮件地址
  • 对报价感兴趣的用户的电子邮件地址
  • 报价的标题,尽管我 给你发一个标题,我不知道这是否正确。在

根据上面的网址,我创建了:

url(r'^contact-to-owner/(?P<email>[\w.@+-]+)/from/'
        r'(?P<interested_email>[\w.@+-]+)/(?P<slug>[\w-]+)/$',
        contact_owner_offer, name='contact_owner_offer'),

然后,在我的模板中,我生成了一个html按钮,在这里我调用了这个URL,并向它们发送了它们各自的预期参数:

<div class="contact">
    <a class="contact-button" href="{% url 'host:contact_owner_offer' email=lodging_offer_owner_email interested_email=user_interested_email slug=lodgingofferdetail.slug %}">
        <img src="{% static 'img/icons/contact.svg' %}" alt="">
        <span>Contact owner offer</span>
    </a>
</div>

我遇到的情况是,当我输入报价详细信息模板并单击上面的联系所有者报价参考按钮时,我会收到以下错误消息:

 TypeError: contact_owner_offer() got an unexpected keyword argument 'email'
[10/Oct/2017 01:04:06] "GET /host/contact-to-owner/botibagl@gmail.com/from/ces@ces.edu.co/apartacho/ HTTP/1.1" 500 77979  

我的追踪到了

Traceback:

File "/home/bgarcial/.virtualenvs/hostayni/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
  42.             response = get_response(request)

File "/home/bgarcial/.virtualenvs/hostayni/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "/home/bgarcial/.virtualenvs/hostayni/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

Exception Type: TypeError at /host/contact-to-owner/botibagl@gmail.com/from/botibagl@gmail.com/apartacho/
Exception Value: contact_owner_offer() got an unexpected keyword argument 'email'

我不明白的是,它告诉我我的URL没有等待一个名为email的参数,在这个参数中,我通过模板中的按钮传递参数email=lodging_offer_owner_owner_email。在

我很感激你的指导 谨致问候


更新

根据@RajKris@Daniel建议,我对URL regex做了一些修改,指定了我传递的关键字参数的名称。URL保持不变:

url(r'^contact-to-owner/(?P<lodging_offer_owner_email>[\w.@+-]+)/from/'
        r'(?P<interested_email>[\w.@+-]+)/(?P<slug>[\w-]+)/$',
        contact_owner_offer,
        name='contact_owner_offer'
    ),

这意味着,我命名url参数的方式与命名contact_owner_offer()接收的参数的方式相同。在

当我输入offer detail模板并单击联系所有者offerreference按钮时,我得到NoReverseMatch错误

Template error:
In template /home/bgarcial/workspace/hostayni_platform/hosts/templates/lodgingoffer_detail.html, error at line 193
   Reverse for 'contact_owner_offer' with arguments '()' and keyword arguments '{'email': 'botibagl@gmail.com', 'interested_email': 'botibagl@gmail.com', 'slug': 'apartacho'}' not found. 1 pattern(s) tried: ['host/contact-to-owner/(?P<lodging_offer_owner_email>[\\w.@+-]+)/from/(?P<interested_email>[\\w.@+-]+)/(?P<slug>[\\w-]+)/$']   183 :                                </tr>
   184 :                                <tr>
   185 :                                    <td>{{ lodgingofferdetail.room_value }}</td>
   186 :                                    <td>{{ lodgingofferdetail.additional_description }}</td>
   187 :                                    <td>{{ lodgingofferdetail.lodging_offer_owner_email }}</td>
   188 :                                </tr>
   189 :                            </tbody>
   190 :                        </table>
   191 :                    </div>
   192 :                    <div class="contact">
   193 :                        <a class="contact-button" href=" {% url 'host:contact_owner_offer' email=lodging_offer_owner_email interested_email=user_interested_email slug=lodgingofferdetail.slug %} ">
   194 :                            <img src="{% static 'img/icons/contact.svg' %}" alt="">
   195 :                            <span>Contactar</span>
   196 :                        </a>
   197 :                    </div>

一般回溯如下:

File "/home/bgarcial/.virtualenvs/hostayni/lib/python3.6/site-packages/django/urls/resolvers.py" in _reverse_with_prefix
  392.             (lookup_view_s, args, kwargs, len(patterns), patterns)

Exception Type: NoReverseMatch at /host/lodging-offer/apartacho/
Exception Value: Reverse for 'contact_owner_offer' with arguments '()' and keyword arguments '{'email': 'botibagl@gmail.com', 'interested_email': 'botibagl@gmail.com', 'slug': 'apartacho'}' not found. 1 pattern(s) tried: ['host/contact-to-owner/(?P<lodging_offer_owner_email>[\\w.@+-]+)/from/(?P<interested_email>[\\w.@+-]+)/(?P<slug>[\\w-]+)/$']

如何解决这个NoReverseMatch错误?在


Tags: toinstancehosturl参数emailcontact报价
2条回答

为什么不在get参数中使用简单url?在

例如“联系业主/?所有者电子邮件=xxx&user email=xxx&title=xxx“

在必须指定的URL regex中,要传递的kyword arg的名称:

url(r'^contact-to-owner/(?P<email1>[\w.@+-]+)/from/' r'(?P<email1>[\w.@+-]+)/(?P<email3>[\w-]+)/$', contact_owner_offer, name='contact_owner_offer'),

这里指的是:

Django Doc

相关问题 更多 >

    热门问题