我正在开发一个宠物商店应用程序。
该应用程序显示所有宠物商店,当您点击宠物商店时,您会看到他们的宠物。
我创建了一个表单,允许用户毫无问题地添加商店。:D
现在问题就在这里。当我为宠物主人创建一个表格以将他们的宠物添加到他们的商店时。我得到这个错误。
我试图让用户创建他们的宠物并将其添加到他们的商店中,而不是使用管理页面。
Cannot assign "[<Store: John Pet Store>]": "Pet.owner" must be a "Store" instance.
Traceback Switch to copy-and-paste view
C:\djcode\mysite\pet\views.py in fan
if form.is_valid():
我的模型.py
from django.db import models
class Store(models.Model):
name = models.CharField(max_length = 20)
number = models.BigIntegerField()
address =models.CharField(max_length = 20)
def __unicode__(self):
return self.name
class Pet(models.Model):
animal = models.CharField(max_length =20)
description = models.TextField()
owner = models.ForeignKey(Store)
image = models.FileField(upload_to="images/")
def __unicode__(self):
return self.animal
我的表格.py
from django import forms
from pet.models import Store
from pet.models import Pet
class StoreForm(forms.ModelForm):
name = forms.CharField(max_length =20,widget =forms.Textarea)
number = forms.CharField(max_length =20,widget =forms.Textarea)
address = forms.CharField(max_length = 20,widget = forms.Textarea)
class Meta:
model = Store
fields = ('name','number','address')
class PetForm(forms.ModelForm):
animal =forms.CharField(max_length = 20,widget = forms.Textarea)
description =forms.CharField(max_length =20, widget = forms.Textarea)
owner = forms.ModelMultipleChoiceField(queryset=Store.objects.all())
image = forms.FileField()
class Meta:
model = Pet
fields = ('animal','description','owner','image')
我的观点.py
from pet.models import Store , Pet
from django.shortcuts import render_to_response ,get_object_or_404
from pet.forms import StoreForm
from django.template import RequestContext
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from pet.forms import PetForm
def index(request):
store = Store.objects.all()
return render_to_response ('store.html',{'store':store})
def brazil(request , animal_id):
pets = Pet.objects.filter(owner_id=animal_id)
return render_to_response ('animal.html',{'pets':pets})
def create(request):
form = StoreForm(request.POST or None)
if form.is_valid():
store = form.save(commit=False)
store.save()
if 'dog' in request.POST:
dog = request.POST['next']
else:
dog = reverse('world:index')
return HttpResponseRedirect(dog)
return render_to_response(
'creates.html',
{'form':form},
context_instance = RequestContext(request)
)
def fan(request):
form = PetForm(request.POST or None)
if form.is_valid():
dad = form.save(commit=False)
dad.save()
if 'cat' in request.POST:
cat = request.POST['next']
else:
cat = reverse('world:index')
return HttpResponseRedirect(cat)
return render_to_response(
'fan.html',
{'form':form},
context_instance = RequestContext(request)
)
我的粉丝.html
<form method="POST" "action">{% csrf_token %}
<ul>
{{ form.as_ul }}
</ul>
<input type = "submit" value= "Add Pets to Store" />
</form>