我尝试在django的外键字段中插入值。但这表明我犯了这样的错误:- 无法分配“'95'”:“Catalog.author\u id”必须是“author”实例。 但是,当我尝试使用django shell插入时,它没有显示任何错误,可以正常工作。请帮帮我 我已附上我的代码,你可以很好地理解
型号.py
class Author(models.Model):
author_id = models.CharField(max_length=50, primary_key=True)
name = models.CharField(max_length=50)
city = models.CharField(max_length=50)
country = models.CharField(max_length=50)
def __str__(self):
return str(self.author_id)
class Catalog(models.Model):
book_id = models.IntegerField(primary_key=True)
title = models.CharField(max_length=100)
year_of_publish = models.CharField(max_length=5)
price = models.IntegerField()
author_id = models.ForeignKey('Author', on_delete=models.CASCADE, null=True)
def __str__(self):
return str(self.book_id)
Forms.py
class Catalog_Details(forms.ModelForm):
book_id = forms.CharField(widget=forms.TextInput(
attrs={'class': 'form-control',
'placeholder': 'Enter book id'}
), required=True, max_length=50)
title = forms.CharField(widget=forms.TextInput(
attrs={'class': 'form-control',
'placeholder': 'Enter title'}
), required=True, max_length=50)
year_of_publish = forms.CharField(widget=forms.TextInput(
attrs={'class': 'form-control',
'placeholder': 'Enter Published Year'}
), required=True, max_length=5)
author_id = forms.ModelChoiceField(queryset=Author.objects.values_list(
'author_id', flat=True))
price = forms.CharField(widget=forms.TextInput(
attrs={'class': 'form-control',
'placeholder': 'Enter Price'}
), required=True, max_length=50)
class Meta():
model = Catalog
fields = ['book_id', 'title', 'year_of_publish', 'price', 'author_id']
视图.py
@login_required
def catalog(request):
if request.user.is_authenticated:
if request.method == 'POST':
form = Catalog_Details(request.POST)
if form.is_valid():
author_id = form.cleaned_data['author_id']
m = Author.objects.get(author_id=author_id)
c1 = Catalog(book_id=form.cleaned_data['book_id'], title=form.cleaned_data['title'],
year_of_publish=form.cleaned_data['year_of_publish'],price=form.cleaned_data['price'], author_id=m)
c1.save()
form = Catalog_Details()
else:
form = Catalog_Details()
return render(request, 'catalog.html', {'form': form})
我认为甚至没有必要重写表单中的
author_id
字段。您可以从Catalog_Details
中删除author_id
。您可以如下方式更新视图:FYI,您不应该用后缀
_id
命名ForeignKey
字段,因为django为您创建了后缀。例如:在本例中,您将在Catalog
模型中找到一个字段author_id_id
,该字段将返回一个整数值(Author表列的主键)相关问题 更多 >
编程相关推荐