我正在尝试设置项目列表,当我设置项目时,它有一个项目编号(例如10-1000)。我希望能够添加一个新项目并将其附加到项目编号1(例如,下一个项目#将是10-1001)。我在搞清楚第一步时遇到了一些麻烦。
这是我的models.py
class Project(models.Model):
client = models.ForeignKey(Clients, related_name='projects')
created_by = models.ForeignKey(User, related_name='created_by')
#general information
proj_name = models.CharField(max_length=255, verbose_name='Project Name')
quote = models.CharField(max_length=10, verbose_name='Quote #', unique=True)
desc = models.TextField(verbose_name='Description')
starts_on = models.DateField(verbose_name='Start Date')
completed_on = models.DateField(verbose_name='Finished On')
def __unicode__(self):
return u'%s' % (self.proj_name)
#get the current status of the projectget_value_display
def current_status(self):
try:
return self.status.all().order_by('-id')[:1][0]
except:
return None
我的views.py显示了添加
@login_required
def addProject(request):
if request.method == 'POST':
form = AddSingleProjectForm(request.POST)
if form.is_valid():
project = form.save(commit=False)
project.created_by = request.user
today = datetime.date.today()
project.quote = "%s-%s" % (str(today.year)[2:4], project.quote)
project.save()
project.status.create(
value = form.cleaned_data.get('status', None)
)
return HttpResponseRedirect('/project/')
else:
form = AddSingleProjectForm()
return render_to_response('project/addProject.html', {
'form': form, 'user':request.user}, context_instance=RequestContext(request))
和我的forms.py
class AddSingleProjectForm(ModelForm):
status = forms.ChoiceField(choices=STATUS_CHOICES)
def __init__(self, *args, **kwargs):
super(AddSingleProjectForm, self).__init__(*args, **kwargs)
self.fields['status'].initial = self.instance.current_status()
class Meta:
model = Project
exclude = ('pre_quote', 'created_by')
def save(self, force_insert=False, force_update=False, commit=True):
f = super(AddSingleProjectForm, self).save(commit=False)
if commit:
f.save()
print "form save method was called with commit TRUE"
return f
任何建议都将不胜感激。
谢谢大家!
答案 0 :(得分:0)
在我看来,你的“报价”是两件事:一个单调递增的“项目编号”和一年。由于它们就是这样,它们具有规则的结构。从表单中排除它们并完全查看,并创建两个新字段:“quote_year”和“quote_id”。
您的保存看起来像这样:
def save(self, *args, **kwargs):
if not self.quote_year and not self.quote_id:
self.quote_year = datetime.date.today().year % 100
quote_ids = self.objects.filter(quote_year = self.quote_year).order_by('-quote_id')
self.quote_id = 1
if quote_ids.exists():
self.quote_id = quote_ids[0].quote_id + 1
super(Project, self).save(*args, **kwargs)
这基本上测试当前年份是否有任何quote_ids,如果没有,则初始化为1,否则初始化为最高quote_id加1。
为了避免一次又一次地渲染引用ID,请将此添加到您的模型中:
@property
def quote(self):
return '%02d-%05d' % (self.quote_year, self.quote_id)
我的代码假定您希望每年的第一个项目将数字的项目部分重置为零。