如何将对象从子模型转换为django模板?

时间:2016-07-22 14:15:14

标签: django django-models django-forms django-views

我在Django项目中创建了与父(Post)模型相关的子模型(' Bid')。我还在B_Bid.view中添加了一个BidForm,以便第2类用户可以对第1类用户创建的特定帖子出价。为特定帖子创建出价时,我想在模板中显示所有与该帖子相同的出价。所以,我在下面的代码中做了。但是在我的页面中,我无法获得特定帖子的出价列表。我很乐意帮助我解决这个问题。

Models.py:

class Post(models.Model):

    post_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
    from1 = models.CharField(max_length=20)
    timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)

    def __str__(self):
        return self.post_id

class Bid(models.Model):

    bid_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    post = models.ForeignKey(Post, default=1, related_name='bids' )
    user = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, blank=True, unique=False)
    amount = models.IntegerField()

    def get_absolute_url(self):
        return reverse("accept_bid", kwargs={"bid_id": self.id})

    def __unicode__(self):
        return self.amount

    def __str__(self):
        return self.amount

Views.py:

def place_bid(request):

    form = BidForm(request.POST or None)

    if  form.is_valid():
        instance = form.save(commit=False)

        print(form.cleaned_data.get("amount"))
        instance.user = request.user
        instance.save()

        queryset = Post.objects.all()

    context = {
        "object_list": queryset, 
        "title": "List",
        "form": form,
    }
    return render(request, 'loggedin_truck/live_bid_truck.html', context)

def live_bids(request):
    post_queryset = Post.objects.all().prefetch_related('bids')

    context = {
        "post_queryset": post_queryset,
        "title": "List",
    }
    return render(request, 'loggedin_load/live_bids.html', context)

form.py:

class BidForm(forms.ModelForm):

    class Meta:
        model = Bid
        fields = ["amount"]

live_bids.html:

{% for post in post_queryset %}
{{post.post_id}}
{% for bid in post.bids.all %}
{{bid.bid_id}}
{{bid.amount}}
{% endfor %}
{% endfor %}

0 个答案:

没有答案