我的模型上有一个保存方法,我想用它来验证字段(我之前在我的视图中做了这个,但它只是凌乱!)。我保存对象而不是表单,因为我在表单验证方面遇到了一些困难。
之前我还没有使用过save方法,但是我假设你在使用.save()命令时会触发它们?我根本没有触发...另外根据我的理解,当你使用is_valid()时,表格会运行一个clean()方法,所以这对我有用吗?
以下是我使用ajax保存对象的视图
@login_required
def createtimesheet(request):
if request.method == "POST":
print "creating timesheet"
# Get the person from the previous view
person_object = request.session.get('person')
person = Person.objects.get(id=person_object)
# get the POST data
start_date = request.POST.get('datestart')
end_date = request.POST.get('dateend')
start_date_formatted = datetime.strptime(start_date, "%m/%d/%Y")
end_date_formatted = datetime.strptime(end_date, "%m/%d/%Y")
start_date_print = start_date_formatted.strftime("%B")[0:3] + ". " + start_date_formatted.strftime("%d") + ", " + start_date_formatted.strftime("%Y")
end_date_print = end_date_formatted.strftime("%B")[0:3] + ". " + end_date_formatted.strftime("%d") + ", " + end_date_formatted.strftime("%Y")
response_data = {}
# create our messages
message = ""
error = ""
todays_date = datetime.now()
print_date = todays_date.strftime("%A")
# now we can create the timesheet!
peach = TimeSheet(start_date=start_date_formatted, end_date=end_date_formatted, person_id=person)
# need an if valid.....?
peach.save()
message = "Created new timesheet"
response_data['startdate'] = start_date_print
response_data['enddate'] = end_date_print
response_data['status'] = peach.status
print response_data
context = {
"person": person,
"message": message,
"error": error,
"print_date": print_date,
"todays_date": todays_date,
}
return JsonResponse(response_data)
这是我尝试编写保存方法的地方......我计划使用更长的验证功能来检查日期是否在特定日期,但是现在我只想得到这个工作。
class TimeSheet(models.Model):
O = "Open"
S = "Submitted"
A = "Approved"
R = "Needs review"
STATUS_CHOICES = (
(O, "Open"),
(S, "Submitted"),
(A, "Approved"),
(R, "Needs Reviewing"),
)
start_date = models.DateField()
end_date = models.DateField()
person_id = models.ForeignKey(Person)
status = models.CharField(max_length= 50, default="Open", choices=STATUS_CHOICES)
submitted_id = models.IntegerField(default=0)
approved_id = models.IntegerField(default=0)
submitted_date = models.DateTimeField(auto_now_add=True, blank=True)
approved_date = models.DateTimeField(auto_now_add=True, blank=True)
# def __str__(self):
# return self.id
def get_absolute_url(self):
return reverse('tande:timesheet', kwargs={'id': self.id})
def __init__(self, *args, **kwargs):
print "initiating a timesheet"
super(TimeSheet, self).__init__(*args, **kwargs)
def save(self, *args, **kwargs):
print "something is trying to save!"
ok_to_continue = True
start_date = self.start_date
end_date = self.end_date
if ok_to_continue:
if end_date < start_date:
error = "Start date must be before end date"
ok_to_continue = False
if ok_to_continue:
super(TimeSheet, self).save(*args, **kwargs)
else:
print "def save did not work"
谢谢!
编辑:这是ajax调用
$( document ).ready(function() {
$('#timesheet-form').on('submit', function(event){
event.preventDefault();
console.log("add a timesheet");
createtimesheet();
});
function createtimesheet() {
console.log("create timesheet is working!")
$.ajax({
url : "{% url 'tande:createtimesheet' %}",
type: "POST",
data: { datestart : $('#start').val(), dateend : $('#end').val()},
success : function(json) {
$('#start').val('');
$('#end').val('');
console.log(json);
var html = '<tr><td>'+json.startdate+'</td><td>'+json.enddate+'</td><td>'+json.status+'</td><</tr>';
console.log("success");
// $('div#talk').html(html);
$('#timesheet-list').append(html);
console.log(html)
overlay();
},
error : function(xhr,errmsg,err) {
// $('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+
// " <a href='#' class='close'>×</a></div>"); // add the error to the dom
console.log("uh oh");
}
});
};
})
网址:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^people/$', views.people, name='people'),
url(r'^people/create_person/$', views.create_person, name='create_person'),
url(r'^(?P<person_id>[0-9]+)/person/$', views.person, name='person' ),
url(r'^person/createtimesheet/$', views.createtimesheet, name='createtimesheet' ),
url(r'^(?P<timesheet_id>[0-9]+)/person/timesheet/$', views.timesheet, name='timesheet' ),
]
答案 0 :(得分:0)
表单ID没有匹配ajax调用中的id ...
html中的id是&#39;创建时间表格式&#39;而ajax正在调用&#39; timesheet-form&#39;
-.-