gpt4 book ai didi

jquery - Django 使用 datepicker 按月动态搜索项目

转载 作者:行者123 更新时间:2023-12-01 05:08:59 31 4
gpt4 key购买 nike

我是 Django 新手。我正在使用 Django 开发一个项目。我的项目与图像相关。在我的项目中,我想添加一个日期选择器,用户可以按月搜索他上传的图像。

举个例子,如果用户从日期选择器中选择任何一年的一月来查看他上传的图像,他将提供那些在当年一月上传的图像。现在我该如何使用 Django 。为了方便起见,我提供了与上传图像相关的模型、表单和 View 。

这里是 models.py

class Photo(models.Model):
name = models.CharField(max_length = 100)
photo = models.ImageField(upload_to = 'photos', blank=False,null=True)
approved = models.BooleanField(default = False)
approved_by = models.CharField(max_length = 100)
user = models.ForeignKey(User)
uploaded_time = models.DateTimeField('date downloaded',auto_now=True)

View .py

def UserImageUpload(request):


if request.method == 'POST':
form = DocumentForm(request.POST,request.FILES)
if form.is_valid():
messages.add_message(request, messages.SUCCESS, 'Your Image upload is waiting for Admin approval')

newdoc = Photo(photo = request.FILES['photo'],user = request.user,name = request.POST['name'],uploaded_time=datetime.datetime.now())
newdoc.save()
else:
messages.add_message(request, messages.ERROR, 'Something is Missing!')

else:
form = DocumentForm()

uploaded_image = Photo.objects.all()

return render_to_response('myprofile/user_image_upload.html',{'uploaded_image':uploaded_image,'form':form},context_instance = RequestContext(request))

和form.py

class DocumentForm(forms.Form):
name = forms.CharField(label='Name Of Your Image',widget=forms.TextInput(attrs={'class' : 'form-control',}))
photo = forms.ImageField(
label='Select a file',)

您可以使用任何示例模板来使用日期选择器并显示搜索结果。

最佳答案

这是一个示例。

验证日期输入的表单:

class PickDateForm(forms.Form):
date = forms.DateField(widget=forms.DateInput(attrs={'class': 'any_custom_class_name'}))

查看:

def query_by_month(request):
if request.method == 'POST':
form = PickDateForm(request.POST)
if form.is_valid():
selected_date= form.cleaned_data['date'] # 'selected_date' is a datetime.date object
photos = Photo.objects.filter(uploaded_time__year=selected_date.year,
uploaded_time__month=selected_date.month)
return HttpResponse('Photos: ' + repr(photos))
else:
return HttpResponse('Invalid form')
else:
form = PickDateForm()
return render(request, 'pickdate.html', {'form': form})

HTML(使用 jQuery datepicker ):

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
<script>
$(function() {
$( ".any_custom_class_name" ).datepicker();
});
</script>
</head>
<body>
<form action="/pick_date/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit" />
</form>
</body>
</html>

关于jquery - Django 使用 datepicker 按月动态搜索项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24544957/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com