【发布时间】:2018-06-28 12:13:44
【问题描述】:
我有一个名为 Fightmma 的模型和一个名为 Fightmmacard 的模型。评论表适用于 Fightcard,但不适用于 Fightmma。
每张战斗卡都是由战斗组成的。当我对任何战斗发表评论时,卡片上的最后一场战斗会获得评论。
我的评论表单会查找内容类型和 ID。我无法正确地将正确的战斗 ID 传递给评论表。在我看来,它会循环战斗,但 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 sn-p
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 sn-p
<!-- 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 sn-p
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'),
]
【问题讨论】:
标签: python django forms django-templates django-contenttypes