【问题标题】:ModelForm in Django - select is not populating with appropriate data?Django中的ModelForm - 选择没有填充适当的数据?
【发布时间】:2017-11-06 08:04:58
【问题描述】:

我在 Django 中有一个显示良好的模型表单 - 但它没有提取适当的信息。

选择下拉菜单出现,但没有填充选项,我正在努力找出原因。

我的模型如下所示:

class Mileage(models.Model):
    start_location = models.ForeignKey(Location, on_delete=models.PROTECT, related_name='start_locations')
    end_location = models.ForeignKey(Location, on_delete=models.PROTECT, related_name='end_locations')
    miles = models.DecimalField(max_digits=8, decimal_places=2)
    user_id = models.IntegerField(null=True)

    def __str__(self):
        return self.miles

class Location(models.Model):
    name = models.CharField(max_length=255)
    address = models.CharField(max_length=255, null=True)
    latitude = models.DecimalField(max_digits=9, decimal_places=6, null=True)
    longitude = models.DecimalField(max_digits=9, decimal_places=6, null=True)
    user_id = models.IntegerField(null=True)

    def __str__(self):
        return self.id

class Trip(models.Model):
    start_location = models.CharField(max_length=255)
    end_location = models.CharField(max_length=255)
    miles = models.DecimalField(max_digits=7, decimal_places=2)
    user = models.ForeignKey(User, on_delete=models.PROTECT)
    trip_date = models.DateTimeField('trip date')

    def __str__(self):
        return self.id

我的 ModelForm 如下所示:

class TripsForm(ModelForm):
    class Meta:
        model = Trip
        fields = ['start_location', 'end_location', 'miles', 'trip_date']
        widgets = {
            'start_location': forms.Select(
                attrs={
                    'class': 'form-control',
                    'id': 'start_location'
                }
            ),
            'end_location': forms.Select(
                attrs={
                    'class': 'form-control',
                    'id': 'end_location'
                }
            ),
            'miles': forms.NumberInput(
                attrs={
                    'class': 'form-control',
                    'id': 'miles',
                    'readonly': 'readonly'
                }
            ),
            'trip_date': forms.TextInput(
                attrs={
                    'class': 'form-control monthpicker datepicker',
                    'id': 'trip_date'
                }
            ),
        }

在我看来,我是这样称呼它的 view.py:

# Create trip
def trip_create(request):
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        form = TripsForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            # Save the form -- will handle this all later
            trip.save()
            return HttpResponseRedirect('/thanks/')
    # if a GET (or any other method) we'll create a blank form
    else:
        form = TripsForm()
        # Return to trips with list of date
    return render(request, 'trips/create.html', {'form': form})

“start_locations”和“end_locations”选择应填充所有位置 - 目前选择完全为空。

我一直在查看文档:在这种情况下,modelformset_factory() 是否值得深入研究?

我只是不确定如何继续让它填充这些下拉列表。

【问题讨论】:

  • 只是为了确定,数据库中有一些位置,对吧?
  • 你能提供你的view.py吗
  • 是的@FamousJameous - 数据库中大约有 27 个位置。我会尽快更新 view.py
  • 您将CharField 用于Trip.start_locationTrip.end_location - 这意味着您必须编写代码来填充选项。为什么不像 Mileage 模型那样使用外键?
  • 哇-@Alasdair-这就是我所缺少的。我知道这会是一件如此简单的事情,我应该看到它。我几乎 100% 肯定这是缺失的环节。请张贴作为答案,我可以给你点:)

标签: python django django-models django-forms modelform


【解决方案1】:

目前,您正在为 Trip.start_locationTrip.end_location 使用 CharField。如果您使用选择小部件,则由您来创建选择来填充它。

如果您在 start_locationend_location 字段中使用 ForeignKey,那么 Django 将为您填充选项。

class Trip(models.Model):
    start_location = models.ForeignKey(Location, on_delete=models.PROTECT, related_name='trip_start_locations')
    end_location = models.ForeignKey(Location, on_delete=models.PROTECT, related_name='trip_end_locations')

对模型进行更改后,您必须进行迁移,然后再迁移。

请注意,我在related_name 中包含了trip,因为相关名称用于将您从Location 模型带回Trip。您可能希望为您的Mileage 模型更新related_name 以包含mileage

【讨论】:

  • 出于好奇 - 有没有办法可以指定下拉菜单显示位置 name 而不是位置 ID?
猜你喜欢
  • 2014-05-27
  • 1970-01-01
  • 2012-07-01
  • 2021-12-24
  • 1970-01-01
  • 2018-11-23
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多