将前一个条目加 1
我正在尝试设置一个项目列表,当我设置项目时,它有一个项目编号(例如 10-1000)。我希望能够添加一个新项目并将其附加到项目编号中(例如,下一个项目编号为 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
任何建议将不胜感激。
谢谢大家!
I'm trying to set up a project listing where when I set up a project it has a project number (example 10-1000). I want to be able to add a new project and have it append 1 to the project number, (example, next project # will be 10-1001). I am having a bit of trouble figuring out the first step.
here is my 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
My views.py showing the add
@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))
and my 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
Any suggestions would be greatly appreciated.
Thanks everyone!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在我看来,你的“报价”是两件事:单调递增的“项目编号”和一年。因为它们就是这样,所以它们有一个规则的结构。将它们完全从表单和视图中排除,并创建两个新字段:“quote_year”和“quote_id”。
然后你的保存看起来像这样:
这基本上测试看看是否有当前年份的 quote_ids,如果没有,则初始化为 1,否则初始化为最高的 quote_id 加 1。
为了避免悲伤,渲染报价一次又一次 ID,也将其添加到您的模型中:
我的代码假设您希望每年的第一个项目的数字项目部分重置为零。
It looks to me that your "quote" is two things: a monotonically incrementing "project number", and a year. Since that's what they are, they have a regular structure. Exclude them from your form and view entirely, and create two new fields: "quote_year" and "quote_id."
Your save would then look something like this:
This basically tests to see if there are any quote_ids for the current year and, if not, initialize to 1, otherwise initialize to the highest quote_id plus 1.
In order to save yourself grief rendering the quote ID again and again, add this to your model as well:
My code assumes that you want the project part of the number to reset to zero for the first project of each year.