如何在Django模型表单中包含外键的所有字段

huangapple go评论62阅读模式
英文:

How to include all fields from foreign key in django model form

问题

我正在尝试从模型表单中访问与外键相关的字段。我已经阅读了文档,似乎我应该能够使用点表示法访问这些字段。我正在尝试的方式是否有意义?是否有更好的方法来做同样的事情。

HTML表单:

<form action="" method="post">
{% csrf_token %}
{{ form.room.room_available }}
{{ form.renter }}
<input type="submit" value="Submit">
</form>

Models.py:

class Room(models.Model):
    roomNum = models.CharField(max_length=20)
    room_is_premium = models.BooleanField(default=False)
    room_available = models.BooleanField(default=False)

class BookedRoom(models.Model):
    room = models.ForeignKey(Room, on_delete=models.CASCADE, null=True, blank=True)
    renter = models.CharField(max_length=200)
    start = models.BooleanField(default=True)
    end = models.BooleanField(default=True)

Views.py:

def bookRoomNow(request, pk):
    room = get_object_or_404(Room, pk=pk)

    if request.method == "POST":
        form = BookingForm(request.POST or None)
        if form.is_valid():
            form = form.save(commit=False)
            form.room = room
            form.save()

            return redirect('room_details', pk=room.pk)

    else:
        form = BookingForm()

    context = {"form": form}
    return render(request, 'booker/booking_form.html', context)

请注意,上述内容已经被翻译为中文,只提供代码部分的翻译。

英文:

I am trying to access the fields related to a foreign key from a model form. I have read the docs and it seems I should be able to access these fields with dot notation. Does what I am attempting make sense? Is there a better way to do this same thing.

html form

{% csrf_token %}
{{ form.room.room_available }}
{{ form.renter }}
&lt;input type=&quot;submit&quot; value=&quot;Submit&quot;&gt;
&lt;/form&gt;

Models.py

class Room(models.Model):
    roomNum = models.CharField(max_length=20)
    room_is_premium = models.BooleanField(default=False)
    room_available = models.BooleanField(default=False)

class BookedRoom(models.Model):
    room = models.ForeignKey(Room, on_delete=models.CASCADE, null=True, blank=True)
    renter = models.CharField(max_length=200)
    start = models.BooleanField(default=True)
    end  = models.BooleanField(default=True)
   

Views.py


def bookRoomNow(request, pk):
   room = get_object_or_404(Room, pk=pk)

   if request.method == &quot;POST&quot;:
      form = BookingForm(request.POST or None)
      if form.is_valid():
         form = form.save(commit=False)
         #this room.instance
         form.room = room
         form.save()
      
         return redirect(&#39;room_details&#39;, pk=room.pk)
   
   else:
      form = BookingForm()
   
   context= {&quot;form&quot;:form}
   return render(request, &#39;booker/booking_form.html&#39;, context) 

答案1

得分: 1

The context variable form you are passing is largely concerned with the form itself - fields, errors etc.

You can pass the Room model instance itself as a separate context variable:

context = {"form": form, "room": room}

And then refer to its fields via dot notation

{{ room.room_available }}

However, if you want to display the form field itself (eg a HTML input with the current value set if there is one), and the field is included in your form definition, you can use

{{ form.renter }}

You can't follow directly from bookingform to room field to another field of the model room because the 'room field' can't be both a literal HTML form field in the booking form and also a model instance of a Room. The use of field in both cases is a little confusing perhaps (and also the bookedroom won't actually exist until after the form is submitted as your view is creating bookings, not editing them!)

英文:

The context variable form you are passing is largely concerned with the form itself - fields, errors etc.

You can pass the Room model instance itself as a separate context variable:

 context= {&quot;form&quot;:form, &quot;room&quot;:room}

And then refer to its fields via dot notation

{{ room.room_available }}

However, if you want to display the form field itself (eg a HTML input with the current value set if there is one), and the field is included in your form definition, you can use

{{ form.renter }}

You can't follow directly from bookingform to room field to another field of the model room because the 'room field' can't be both a literal HTML form field in the booking form and also a model instance of a Room. The use of field in both cases is a little confusing perhaps (and also the bookedroom won't actually exist until after the form is submitted as your view is creating bookings, not editing them!)

huangapple
  • 本文由 发表于 2023年7月14日 06:53:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/76683732.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定