Django初学者表单,无法获得循环表单

时间:2018-01-19 09:34:41

标签: python django forms django-templates django-contenttypes

我有一个型号名称Fightmma和一个名为Fightmmacard的模型。 Commentform适用于Fightcard,但不适用于Fightmma。

每张战斗卡都是由战斗组成的。当我评论任何战斗时,卡片上的最后一次战斗都会得到评论。

我的Commentform查找内容类型和ID。我无法正确地将正确的战斗ID传递给Commentform。在我的视图中,它通过战斗循环,但id仅存储为最后一次战斗。

我的python并不是那么棒,但我已经尝试了12个小时

所有帮助表示赞赏。

使用Django1.11

models.py

from __future__ import unicode_literals
from django.db import models
from django.core.urlresolvers import reverse
from datetime import date
from django.contrib.auth.models import User #Blog author or commenter
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericRelation


class CommentManager(models.Manager):
    def filter_by_instance(self, instance):
        content_type = ContentType.objects.get_for_model(instance.__class__)
        obj_id = instance.id
        qs = super(CommentManager, self).filter(content_type=content_type, object_id= obj_id)
        return qs



class Comment(models.Model):
    author = models.ForeignKey(User)
    body = models.TextField(blank=True)
    post_date = models.DateTimeField(auto_now_add=True)
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey()

    objects = CommentManager()


    class Meta:
        ordering = ["-post_date"]

    def __str__(self):
        """
        String for representing the Model object.
        """
        len_title=75
        if len(self.body)>len_title:
            titlestring=self.body[:len_title] + '...'
        else:
            titlestring=self.body
        return titlestring     





#mmmmmmmmmmm
class Fightmma(models.Model):
    Custom_Number = models.CharField(max_length=200, blank=True)
    Wiki_Event_Number_Fight = models.IntegerField(null=True, blank=True)
    Event_Number_2 = models.IntegerField(null=True, blank=True)
    Left_Names_Natural_Spaces = models.CharField(max_length=200, blank=True)
    Right_Names_Natural_Spaces = models.CharField(max_length=200, blank=True)
    Custom_Number_Decimal = models.DecimalField(max_digits=8, decimal_places=3, null=True, blank=True)
    Event_Number = models.ForeignKey('Fightcardmma', on_delete=models.CASCADE, blank= True, null= True)
    comments = GenericRelation('Comment')

    def __str__(self):              # __unicode__ on Python 2
        return str(self.Custom_Number_Decimal)

    class Meta:
        ordering = ('Custom_Number_Decimal',)

    @property
    def comments(self):
        instance = self
        qs = Comment.objects.filter_by_instance(instance)
        return qs

    @property
    def get_content_type(self):
        instance = self
        content_type = ContentType.objects.get_for_model(instance.__class__)
        return content_type






class Fightcardmma(models.Model):
    Event_Number = models.IntegerField(null=True, blank=True)
    Event_Wiki_Name = models.CharField(max_length=200, null=True, blank=True)
    Event_Wiki_Link = models.CharField(max_length=200, null=True, blank=True)
    Event_Date = models.CharField(max_length=200, null=True, blank=True)
    Event_Stadium = models.CharField(max_length=200, null=True, blank=True)
    Event_Location = models.CharField(max_length=200, null=True, blank=True)
    Event_Attendance = models.CharField(max_length=200, null=True, blank=True)
    Event_Date_2 = models.CharField(max_length=200, null=True, blank=True)
    comments = GenericRelation('Comment')

    def __str__(self):              # __unicode__ on Python 2
        return str(self.Event_Number)

    class Meta:
        ordering = ('Event_Number',)

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

    @property
    def comments(self):
        instance = self
        qs = Comment.objects.filter_by_instance(instance)
        return qs

    @property
    def get_content_type(self):
        instance = self
        content_type = ContentType.objects.get_for_model(instance.__class__)
        return content_type

views.py

from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.template.defaulttags import register
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic.edit import CreateView
from django.urls import reverse
from django.contrib.auth.models import User
from django.views import generic
from django.contrib.contenttypes.models import ContentType


from .forms import FightcardmmaForm, CommentForm
from .models import Fighter, Fight, Fightcard, Result, Fightermma, Fightmma, Fightcardmma, Resultmma, FightcardmmaComment, FightmmaComment, Comment



def fightcardmma_detail(request, id=None): #retrieve
    instance = get_object_or_404(Fightcardmma, id=id)
    fightqueryset = Fight.objects.all()
    fighterqueryset = Fighter.objects.all()
    fightcardqueryset = Fightcard.objects.all()
    resultqueryset = Result.objects.all()
    fightmmaqueryset = Fightmma.objects.all()
    fightermmaqueryset = Fightermma.objects.all()
    fightcardmmaqueryset = Fightcardmma.objects.all()
    resultmmaqueryset = Resultmma.objects.all()



    bu = Fightcardmma.objects.filter(Event_Number=instance.Event_Number) 
    bu2 = Fightcardmma.objects.all().count()


    for a in bu:  #for each fight a in event bu 
        iu =a.fightmma_set.all() #curiousty all the fights in event a
        fighterfights = {} 
        fighterdetails = {}
        for c in iu:   # for each fight c in event iu


            initial_data = {
                "content_type": c.get_content_type,
                "object_id": c.id
            } 

############## looping though fights ########              
            form = CommentForm()
            form = CommentForm(request.POST or None, initial=initial_data,)
            if form.is_valid():
                c_type = form.cleaned_data.get("content_type")
                content_type = ContentType.objects.get(model=c_type)
                obj_id = form.cleaned_data.get('object_id')
                content_data = form.cleaned_data.get("body")
                new_comment, created = Comment.objects.get_or_create(
                                    author = request.user,
                                    content_type= content_type,
                                    object_id = obj_id,
                                    body = content_data,
                                )
                refresh1 = "/aland/fightcardmma/"+str(instance.id)
                return HttpResponseRedirect(refresh1)          



##### end of loop below if comment for fightcard ##################                

    initial_data2 = {
            "content_type": instance.get_content_type,
            "object_id": instance.id
    }

    formunique = CommentForm()
    formunique = CommentForm(request.POST or None, initial=initial_data2)
    if formunique.is_valid():
        c_type = formunique.cleaned_data.get("content_type")
        content_type = ContentType.objects.get(model=c_type)
        obj_id = formunique.cleaned_data.get('object_id')
        content_data = formunique.cleaned_data.get("body")
        new_comment, created = Comment.objects.get_or_create(
                            author = request.user,
                            content_type= content_type,
                            object_id = obj_id,
                            body = content_data
                        )
        refresh1= "/aland/fightcardmma/"+str(instance.id)
        return HttpResponseRedirect(refresh1)

    comments = instance.comments


    context = {
            "fight_list": fightqueryset,
            "fighter_list": fighterqueryset,
            "fightcard_list": fightcardqueryset,
            "result_list": resultqueryset,
            "fightmma_list": fightmmaqueryset,
            "fightermma_list": fightermmaqueryset,
            "fightcardmma_list": fightcardmmaqueryset,
            "resultmma_list": resultmmaqueryset,
            "title": "List" ,                
            "bu": bu ,
            "iu": iu ,
            "instance": instance,
            "fighterfights": fighterfights,
            "fighterdetails" : fighterdetails,
            "comments": comments,        
            "formunique": formunique,
            "form": form,

    }
    return render(request, "fightcardmma_detail.html", context)


######

forms.py代码段

from django import forms

from .models import Fightcardmma, Fightmma, Comment


class CommentForm(forms.Form):
    content_type = forms.CharField(widget=forms.HiddenInput)
    object_id = forms.IntegerField(widget=forms.HiddenInput)
    body = forms.CharField(label='', widget=forms.Textarea)

fightcardmma_detail.html片段

<!-- Bootstrap core CSS -->
{% extends 'base.html' %}
{% load staticfiles %}
{% load get %}

              {{ a.Custom_Number_Decimal}}
              <form method="POST" action="."> {% csrf_token %}
                  {{ form}}
                  <input type='submit' value='Post fight comment' class='btn btn-default'>

urls.py片段

from django.conf.urls import  url
from django.contrib import admin
from . import views
from .views import (
    fightcardmma_detail,
    )
urlpatterns = [
    url(r'^fightcardmma/(?P<id>\d+)/$', fightcardmma_detail, name='detail'),
    ]

1 个答案:

答案 0 :(得分:0)

将此添加到views.py

fightform = []
for fight in fightcard
    initial_data = {
        "content_type": fight.get_content_type,
        "object_id": fight.id
    } 


    Form[fight] = CommentForm(request.POST or None, initial=initial_data,)
        if form.is_valid(): ### same as before

fightform.append(Form[fight])
fightset = instance.fightmma_set.all()
fightset_and_fightform = zip(fightset, fightform)

context{
"fightset_and_fightform":fightset_and_fightform, ### added to context
}

然后按照answer我可以通过模板传递它。