从django表单处理数据

bvuwiixz  于 2023-03-20  发布在  Go
关注(0)|答案(1)|浏览(88)

我有一个带有下拉列表的表单:

CATEGORY_CHOICES= [
    ('sport', 'Sport'),
    ('mini', 'Mini'),
    ('economy', 'Economy'),
    ('electro', 'Electro'),
    ('business', 'Business'),
    ]

class CategoryChoice(forms.Form):
    category= forms.CharField(label='Поиск по категории:', widget=forms.Select(choices=CATEGORY_CHOICES, ), required = False)

URLS.PY

urlpatterns = [
    
    path("productsHTML/<str:uuid>", productHTML, name = "productHTML"),
    path("productsHTML/", productsHTML, name = "productsHTML"),
]

VIEWS.PY

def productsHTML(request):
    
    all_products = {"products": Product.objects.all()}
    return render(request, "products.html",all_products) 

def productHTML(request, uuid):
    product = Product.objects.get(id = uuid)
    img = product.category
    slovar = {"product": product, "img": img.image}
    return render(request, "product.html", slovar)

我需要当选择一个类别,并按下“搜索”按钮,用户将被重定向到与所选类别的商品页面?
我不知道如何把html模板和view.pyurls.py链接在一起,你能帮我一下吗?我会很感激的。

lnxxn5zx

lnxxn5zx1#

我需要看到你的views.py和urls.py文件,才能给予适合你的特定用例的答案,但假设你遵循了标准的Django约定,我猜你的代码应该是这样的:

视图.py文件

from django.shortcuts import render, redirect

from . import models, forms

def search(request):
    form = forms.CategoryChoice(request.POST or None)
    if request.method == 'POST' and form.is_valid():
        category = form.cleaned_data['category'].lower()
        new_destination = category + '_list'
        # This will output e.g. 'sport_list' or 'mini_list'
        return redirect(f'{new_destination}', permanent=True)
    context = {
        'form': form,
    }
    return render(request, 'app/search.html', context)

# I assume your views look roughly like this or the class-based equivalents
def sport_list(request):
    queryset = models.Sport.objects.all()
    context = {
        'objects': queryset
    }
    return render(request, 'app/sport_list.html', context)

def mini_list(request):
    queryset = models.Mini.objects.all()
    context = {
        'objects': queryset
    }
    return render(request, 'app/mini_list.html', context)
# ETC...

网址.py文件

from django.urls import path

from . import views

urlpatterns = [
    path('search/', views.search, name='search'),
    path('sport_list/', views.sport_list, name='sport_list'),
    path('mini_list/', views.mini_list, name='mini_list'),
    # ETC...
]

**TL;DR:**确保从表单中捕获“category”值,然后将其转换为在url配置中设置为“name”的任何格式,并基于此使用redirect函数。最佳实践是保持小写,因此我使用了.lower()方法。

相关问题