簡體   English   中英

將多個參數傳遞給Django URL

[英]Passing multiple parameters to Django URL

我有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)

    country = CountryField(blank_label='(Seleccionar país)', verbose_name='Pais')

    city = models.CharField(max_length=255, blank = False, verbose_name='Ciudad')

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

    pub_date = models.DateTimeField(
        auto_now_add=True,
    )

    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 DetailView ,其中顯示了LodgingOffer對象的數據

一個重要的LodgingOffer條件是,在LodgingOffer記錄的詳細信息中,我可以聯系要約的所有者(創建要約的用戶)以向她申請。

為此,我具有contact_owner_offer()函數,該函數用於向所有者報價發送電子郵件。 我在HostingOfferDetailView中通過這種方式所做的所有事情:

class HostingOfferDetailView(UserProfileDataMixin, LoginRequiredMixin, DetailView):
    model = LodgingOffer
    template_name = 'lodgingoffer_detail.html'
    context_object_name = 'lodgingofferdetail'

    def get_context_data(self, **kwargs):
        context = super(HostingOfferDetailView, self).get_context_data(**kwargs)
        user = self.request.user

        # LodgingOffer object
        #lodging_offer_owner = self.get_object()

        # Get the full name of the lodging offer owner        
        lodging_offer_owner_full_name = self.get_object().created_by.get_long_name()

        # Get the lodging offer email owner
        lodging_offer_owner_email = self.get_object().created_by.email

        # Get the lodging offer title
        lodging_offer_title = self.get_object().ad_title

        # Get the user interested email in lodging offer
        user_interested_email = user.email

        # Get the user interested full name 
        user_interested_full_name = user.get_long_name()

        context['user_interested_email'] = user_interested_email

        # Send the data (lodging_offer_owner_email
        # user_interested_email and lodging_offer_title) presented 
        # above to the contact_owner_offer function
        contact_owner_offer(self.request, lodging_offer_owner_email,
                    user_interested_email, lodging_offer_title)

        return context

我的contact_owner_offer函數接收這些參數要約,並通過以下方式將電子郵件發送給要約的所有者:

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

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

            'offer': lodging_offer_title,
            # offer title

            'user_interested_email': user_interested_email,
            # user interested in the offer

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

        message = render_to_string('contact_user_own_offer.html', context)

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

直到這里,所有的工作。 一切正常,當我輸入要約的詳細信息時,我會向所有者要約發送電子郵件。

我的意圖是在模板提供的報價詳細信息中,呈現一個對聯系所有者報價有用的按鈕,然后,我繼續定義我的URL,該URL調用contact_owner_offer()函數

我根據接收contact_owner_offer()函數的參數定義url:

這意味着(根據我的理解-我不知道我是否錯-),我的url應該會收到住宿優惠所有者的電子郵件,對該優惠感興趣的用戶的電子郵件以及住宿優惠標題,為此,我創建以下URL:

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

但是,當我在URL上方定義此消息時,會收到以下消息:

File "/home/bgarcial/.virtualenvs/hostayni/lib/python3.6/sre_parse.py", line 759, in _parse
    raise source.error(err.msg, len(name) + 1) from None
sre_constants.error: redefinition of group name 'email' as group 2; was group 1 at position 43

django.core.exceptions.ImproperlyConfigured: "^contact-to-owner/(?P<email>[\w.@+-]+)/(?P<email>[\w.@+-]+)/(?P<slug>[\w-]+)/$" is not a valid regular expression: redefinition of group name 'email' as group 2; was group 1 at position 43

在這一刻,我對如何定義與該場景相關的URL感到困惑,並且我也想知道如何在住宿報價模板詳細信息的按鈕中調用此URL。

我是這樣打電話的,但是我不知道我是否很刻薄:

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

我對此有所了解。

最好的祝福

您在正則表達式中有兩個具有相同名稱的組。 更改正則表達式以對URL中的每個組進行不同的命名。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM