django 我可以在定义为ForeignkeyField的表单中输入任何字符值吗?

mkh04yzy  于 2023-06-07  发布在  Go
关注(0)|答案(1)|浏览(91)

首先,这是我在堆栈溢出中的第一个问题,请耐心等待.
使用Django。我想让用户输入一个字符值的形式定义为外键字段(在这种情况下,它的类别形式)。

models.py

class Category(models.Model):
    # id = models.BigAutoField(primary_key=True)
    name = models.CharField(max_length=15)
    def __str__(self):
        return f"{self.name}"

class Listing(models.Model):
    id = models.BigAutoField(primary_key=True)
    title = models.CharField(max_length=15)
    description = models.CharField(max_length=100)
    starting_bid = models.IntegerField()
    image = models.ImageField(upload_to='images', null=True)
    category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True, related_name="category_name")
    
    def __str__(self):
        return f"{self.id}: {self.title}: {self.description}: {self.starting_bid}: {self.image}: {self.category}"

forms.py

class ListingForm(forms.ModelForm):
    class Meta:
        model = Listing
        fields = ["title", "description", "starting_bid", "image", "category"]

views.py

def create_listing_view(request):
    if request.method == "POST":
        form = ListingForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('listings'))
    else:
        form = ListingForm()
    return render(request, 'auctions/create.html', {'form': form})

create.html

{% block body %}
    <h1>create</h1>
    <form action="{% url 'create' %}" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.as_p }}
    <br><br>
    <button type="submit" value="Submit">Create</button>
    </form>
{% endblock %}

this image is present condition
我试着自己做,但我不能随心所欲。到目前为止,我妥协,让用户输入一个值的类别形式作为下拉式值一样上传的图像(不输入字符值)。
我很感激给我一个解决方案,也告诉我哪一个是最好的主意,让用户输入一个字符值,无论用户想输入到类别表单或只提示用户输入下拉值到类别表单像现在这样。

y1aodyip

y1aodyip1#

更好的说法是,我们可以在一个表单中使用多个模型:是的,有一种方法可以创建不同的表单类,然后通过视图将它们传递给模板,并在模板中提到这两种表单。通过这种方法,用户可以在listingform中输入自己的类别,就像你想要的那样,你应该像这样修改代码:

forms.py:

from django.forms import ModelForm
from .models import Listing
from .models import Category

class ListingForm(ModelForm):
    class Meta:
        model = Listing
        fields = ["title", "description", "starting_bid", "category"]

class CategoryForm(ModelForm):
    class Meta:
        model = Category
        fields = ["name"]

views.py:

from django.shortcuts import render, reverse
from django.http import HttpResponseRedirect
from .forms import ListingForm
from .forms import CategoryForm
# Create your views here.

def create_listing_view(request):
    if request.method == "POST":
        form_l = ListingForm(request.POST, request.FILES)
        form_c = CategoryForm(request.POST, request.FILES)

        if form_l.is_valid() and form_c.is_valid():
            form_l.save()
            form_c.save()
            return HttpResponseRedirect(reverse('home'))
    else:
        listing_form = ListingForm()
        category_form = CategoryForm()
    return render(request, 'app/create.html', {
        "listing_form": listing_form,
        "category_form": category_form,
    })

create.html:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>

    <h1>create</h1>
    <form action="{% url 'home' %}" method="post" enctype="multipart/form-data">
    {% csrf_token %}
        {{ listing_form }}
        {{ category_form }}
    <br><br>
    <button type="submit" value="Submit">Create</button>
    </form>

</body>
</html>

相关问题