【问题标题】:I want to add user's id on the url path or in the address of the page我想在 url 路径或页面地址中添加用户的 id
【发布时间】:2021-07-06 15:59:13
【问题描述】:

我的网页上有一个网址是“http://127.0.0.1:8000/affiliation/link/10006/”。

在上面的网址中,我想添加用户 ID,使其看起来像:“http://127.0.0.1:8000/affiliation/link/01/10006/”这样的东西,而“01”是上传产品的用户的用户 ID。

以下是文件。

观看次数:

#Display individual product and render short links for all using pyshorteners
def link_view(request, uid):
    results = AffProduct.objects.get(uid=uid)
    slink = "http://127.0.0.1:8000/" + request.get_full_path()
    shortener = pyshorteners.Shortener()
    short_link = shortener.tinyurl.short(slink)
    return render(request, 'link.html', {"results": results, "short_link": short_link})

型号:

#Product details uploaded
class AffProduct(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='foo')
    product_title = models.CharField(max_length=255)
    uid = models.IntegerField(primary_key=True)
    specification = models.CharField(max_length=255)
    sale_price = models.IntegerField()
    discount = models.IntegerField()
    img1 = models.ImageField(max_length=255, null=True, blank=True, upload_to="images/")
    img2 = models.ImageField(max_length=255, null=True, blank=True, upload_to="images/")
    promote_method = models.TextChoices
    terms_conditions = models.CharField(max_length=255, null=True)
    promote_method = models.CharField(
        max_length=20,
        choices=promote_choices,
        default='PPC'
    )
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

网址:

urlpatterns = [
    path('link/<int:uid>/', views.link_view, name='link_view')
]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

【问题讨论】:

    标签: python django url


    【解决方案1】:

    如果你真的想在你的路径中添加 user.id,你可以像在你当前的 urlpatterns 中添加“uid”一样添加它

    path('link/<int:user_id>/<int:uid>/', views.link_view, name='link_view')
    # and your view signature would be:
    def link_view(request, user_id, uid):
    

    但如果你只需要当前的用户对象,它可以从传入你视图的“请求”对象中获取

    def link_view(request, uid):
        user = request.user
        # ...
    

    【讨论】:

    • 当我尝试这个时,我在那个位置得到 NoReverseMatch。
    • "NoReverseMatch" 通常发生在您在视图或模板中的 django.urls.reverse() 中传递未定义的名称时。如果您是 django 新手,我建议您按照教程(例如 docs.djangoproject.com/en/3.2/intro/tutorial01)了解整个请求到响应周期。
    猜你喜欢
    • 1970-01-01
    • 2022-11-18
    • 2011-03-06
    • 2016-07-08
    • 2013-01-20
    • 2023-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多