Skip to content

Instantly share code, notes, and snippets.

@thebookworm101
Last active December 10, 2015 13:08
Show Gist options
  • Save thebookworm101/4438956 to your computer and use it in GitHub Desktop.
Save thebookworm101/4438956 to your computer and use it in GitHub Desktop.
having access to last (if any) end_time in every new entry of a model.
################entering some data the first time to my form doesnt work, it gives this error:
IntegrityError at /job/add/article/
(1048, "Column 'author_id' cannot be null")
Request Method: POST
Request URL: http://localhost:8000/job/add/article/
Django Version: 1.4.3
Exception Type: IntegrityError
Exception Value:
(1048, "Column 'author_id' cannot be null")
#########################Problem im solving: im trying to set the begin_time to be the same as the end_time of the previous entry of this model by the same user if any (only the very first time wont have a previous end_time).
###Here is my solution i have so far:
#######################The view #########
@login_required
def add_job(request):
form = JobForm(request.POST or None)
if form.is_valid():
article = form.save(commit=False)
article.author = request.user
article.save()
msg = "Job saved successfully"
messages.success(request, msg, fail_silently=True)
return redirect(article)
return render_to_response('job/job_form.html',
{ 'form': form },
context_instance=RequestContext(request))
######################the JobForm #########
class JobForm(forms.ModelForm):
""" this handles the start_time and end_time defaults"""
class Meta:
exclude = ['slug','author',]
model = Job
def __init__(self,*args, **kw):
super(JobForm,self).__init__( *args, **kw)
def save(self, *args, **kw):
instance = super(JobForm,self).save()
#last_entry = Job.objects.filter(author__id=user.id).order_by('-id')[0]
last_entry = Job.objects.filter(author=self.request.user).aggregate(max_end_time=Max('end_time'))['max_end_time']
if last_entry:
instance.start_time = last_entry.end_time
else:
# this is the very first record do nothing
pass
instance.save()
return instance
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment