Django clean()方法引发';投标';对象没有属性';kwargs';
我试图限制通过表单对特定项目进行投标的投标人的投标不得低于项目发布者指定的最低预算,也不得高于最高预算。在检查了类似的问题之后,我发现重写clean方法是最合适的,但是我遇到了“'Bid'对象没有属性'kwargs'”错误 这是清洁方法:Django clean()方法引发';投标';对象没有属性';kwargs';,django,django-models,django-validation,Django,Django Models,Django Validation,我试图限制通过表单对特定项目进行投标的投标人的投标不得低于项目发布者指定的最低预算,也不得高于最高预算。在检查了类似的问题之后,我发现重写clean方法是最合适的,但是我遇到了“'Bid'对象没有属性'kwargs'”错误 这是清洁方法: def clean(self): if Project.objects.get(pk=self.kwargs['pk']).budget_min >= self.bid_amount or self.bid_amount >
def clean(self):
if Project.objects.get(pk=self.kwargs['pk']).budget_min >= self.bid_amount or self.bid_amount >= Project.objects.get(pk=self.kwargs['pk']).budget_max:
raise ValidationError('the bid amount should be between the minimum and maximum project budget')
这是我的模特
# projects/models.py
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from django.db import models
from django.urls import reverse
from django.core.validators import MaxValueValidator, MinLengthValidator, MinValueValidator
from upload_validator import FileTypeValidator
from .validators import user_directory_path, validate_file_size
from multiselectfield import MultiSelectField
class Project(models.Model):
title = models.CharField(
'Choose a title for your project',
max_length=255,
validators=[
MinLengthValidator(
15, 'Title must be descriptive and greater than 15 characters')
]
)
body = models.TextField('Tell us more about your project',
max_length=3000,
validators=[
MinLengthValidator(
10, 'Must be descriptive and greater than 10 characters')
]
)
upload_file = models.FileField(
upload_to=user_directory_path,
verbose_name="upload file:(Max file size: 2.5 MB)",
validators=[
validate_file_size,
FileTypeValidator(
allowed_types=[
'application/msword',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/pdf',
'application/vnd.ms-powerpoint',
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'application/vnd.ms-excel',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'image/tiff',
'image/jpeg',
'image/png'
],
allowed_extensions=['.doc', '.docx',
'.jpg', '.jpeg', '.png', '.pdf', '.zip']
)
],
null=True, blank=True
)
POSSIBLE_SKILLS = (
('Bash Scripting', 'Bash Scripting'), ('CSS', 'CSS'), ('Django', 'Django'),
('HTML', 'HTML'), ('JavaScript', 'JavaScript'), ('React', 'React'),
('Linux', 'Linux'), ('MongoDB', 'MongoDB'), ('NoSQL', 'NoSQL'),
('Powershell', 'Powershell'), ('Python', 'Python'),
('Shell Script', 'Shell Script')
)
skills = MultiSelectField(choices=POSSIBLE_SKILLS, default='')
PAYMENT_TYPE = (
('Fixed', 'Fixed'),
('Hourly', 'Hourly'),
)
payments = models.CharField(
'How do you want to pay?',
max_length=20, choices=PAYMENT_TYPE, default="Fixed")
budget_min = models.PositiveIntegerField(
'What is your estimated Minimum budget?',
default=10, validators=[MinValueValidator(1), MaxValueValidator(100000)])
budget_max = models.PositiveIntegerField(
'What is your estimated Maximum budget? :',
default=100, validators=[MinValueValidator(1), MaxValueValidator(100000)])
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
# author is a FOREIGN KEY field in Project table, that refers to the PRIMARY KEY in CustomUser table
# the on_delete method used to tell django when deleting the author delete he's projects
author = models.ForeignKey(
get_user_model(),
on_delete=models.CASCADE,
)
# Shows up in the admin list
def __str__(self):
return self.title
def get_absolute_url(self):
"""[summary: where to go when a Project object is created.
]
Returns:
[description: this method should appear to return a string that can be used to refer
to the object over HTTP.]
"""
return reverse('project_detail', args=[str(self.id)])
class Bid(models.Model):
bid_amount = models.PositiveIntegerField(
default=10, validators=[MinValueValidator(1), MaxValueValidator(1000000)]
)
delivery_in = models.PositiveIntegerField(
default=1, validators=[MinValueValidator(1), MaxValueValidator(10000)]
)
describe_your_proposal = models.TextField(
max_length=144,
validators=[
MinLengthValidator(
20, "bid must be descriptive and greater than 20 characters")
]
)
STATUS_TYPE = (
('Approved', 'Approved'),
('Closed', 'Closed'),
('Pending', 'Pending'),
)
status = models.CharField(
'How do you want to pay?',
max_length=20, choices=STATUS_TYPE, default="Pending")
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
# project is a FOREIGN KEY field in Bid table, that refers to
# the PRIMARY KEY in Project table using related name project.bids
# in templates to access bids of the project
# the on_delete method used to tell django when deleting the project delete it's bids
project = models.ForeignKey(
Project,
on_delete=models.CASCADE,
related_name='bids',
)
# author is a FOREIGN KEY field in Bid table, that refers to
# the PRIMARY KEY in CustomUser table
author = models.ForeignKey(
get_user_model(),
on_delete=models.CASCADE,
)
#
def clean(self):
if Project.objects.get(pk=self.kwargs['pk']).budget_min >= self.bid_amount or self.bid_amount >= Project.objects.get(pk=self.kwargs['pk']).budget_max:
raise ValidationError('the bid amount should be between the minimum and maximum project budget')
# Shows up in the admin list
def __str__(self):
return self.describe_your_proposal
def get_absolute_url(self):
"""[summary: where to go when a Bid object is created.
]
Returns:
[description: this method should appear to return a string that can be used
to refer to the object over HTTP.]
"""
return reverse('bid_detail', args=[str(self.id)])
如果clean方法中引用的项目是
bid.project
对象,那么您可以直接调用它
def clean(self):
if not self.project.budget_min <= self.bid_amount <= self.project.budget_max:
raise ValidationError('The bid amount should be between the minimum and maximum project budget.')
def清洁(自清洁):
如果不是self.project.budget,请尝试将self.kwargs['pk']
更改为self.pk
。如果这不起作用,那么您用来调用clean的代码是什么?您可以包含堆栈跟踪吗?谢谢您的回答,但这并不能解决问题,反而会引发这个问题。RelatedObjects没有在/projects/bid/3/new/bid上列出任何项目。