【发布时间】:2017-06-08 17:01:38
【问题描述】:
我的视图函数变得相当混乱,那么是否可以从视图文件中的单独函数调用我的 ajax 请求?
这是我的观点
def article(request, category, id):
name = resolve(request.path).kwargs['category']
for a, b in CATEGORY_CHOICES:
if b == name:
name = a
instance = get_object_or_404(Post, id=id, category=name)
allauth_login = LoginForm(request.POST or None)
allauth_signup = SignupForm(request.POST or None)
#comments
comment = CommentForm(request.POST or None)
ajax_comment = request.POST.get('text')
comment_length = len(str(ajax_comment))
comment_list = Comment.objects.filter(destination=id)
score = CommentScore.objects.filter(comment=comment_list)
if request.is_ajax():
username_clicked = request.GET.get('username_clicked')
profile = Profile.objects.get(username=username_clicked)
if username_clicked:
print(profile.age)
if comment.is_valid():
comment = Comment.objects.create(comment_text=ajax_comment, author=str(request.user), destination=id)
comment.save()
score = CommentScore.objects.create(comment=comment)
score.save()
username = str(request.user)
return JsonResponse({'text': ajax_comment, 'text_length': comment_length, 'username': username})
else:
print(comment.errors)
context = {
'score': score,
'comment_list': comment_list,
'comment': comment,
'instance': instance,
'allauth_login': allauth_login,
'allauth_signup': allauth_signup
}
return render(request, 'article.html', context)
例如,对于username_clicked,我想将其取出并在同一个视图文件中使其成为类似这样的函数:
def raise_profile(request):
if request.is_ajax():
username_clicked = request.GET.get('username_clicked')
profile = Profile.objects.get(username=username_clicked)
if username_clicked:
print(profile.age)
return HttpResponse()
这可能吗?请记住,这些都在同一个 URL url(r'^(?P<category>\w+)/(?P<id>\d+)/', article, name='article')
这可能吗?
更新功能:
def raise_profile(request):
if request.is_ajax():
username_clicked = request.GET.get('username_clicked')
profile = Profile.objects.get(username=username_clicked)
if username_clicked:
print(profile.age)
response_data = json.dumps({username_clicked})
return HttpResponse(response_data, content_type='application/json')
【问题讨论】:
标签: jquery python ajax django django-views