我想通过单击按钮在单个HTML页面中执行2个以上的操作。在菜单栏中有5个选项。即,当我单击“主页”时,它将执行某些操作,而当我单击“配置文件”时,它将执行特定操作。我为每个操作编写了单独的函数。如何对单个页面执行多种功能。
views.py
def home(request):
return render(request, 'index.html', {})
def profile(request):
if request.method == 'POST':
form = ProfileForm(request.POST)
if form.is_valid():
first_name = request.session['username']
print(first_name)
test = Profile.objects.filter(first_name=first_name).values()
for i in test:
dict1 = i
return render(request, 'index.html',
{'first_name': first_name, 'last_name': dict1['last_name'],
'phone_number': dict1['phone_number'], 'email': dict1['email'],
'address': dict1['address'], 'image': dict1['image']})
else:
form = ProfileForm()
return render(request, 'profile.html', {'form': form})
def friends(request):
friends_obj = Friends.objects.all()
return render(request, 'index.html', {'friends_obj': friends_obj})
urls.py
urlpatterns = [
path('home/', views.home, name="home"),
path('profile/', views.profile, name="profile"),
path('friends/', views.friends, name="friends"),
]
menu bar look like this我想通过单击菜单选项来执行所有操作。
答案 0 :(得分:0)
def friends(request):
和def home(request):
使用Get
方法,而def profile(request):
使用Post
方法。因此,第一步我们可以使用if request.method == "POST"
为它们添加锯齿。对于使用相同方法的单独进程,我们需要在发送到django view之前,从前端(HTML-javascript等)的进程中附加一些标志,如下所示:
template.html:
<form action="/navbar_aggregation" method="get">
<input type="text" name="type" value="friends" hidden>
<!-- other input tag will be here as you need-->
<input type="submit" value="Submit">
</form>
然后您可以访问以这种方式输入视图。 view.py:
def navbar_aggregation(request):
type = request.get.Get("type") # name of hidden input
if (type == "friends"):
# do same thing like 'def freinds(request)'
elif(type == "family"):
# do process for family form
else :
# do process for 'def home(request)'
所以现在我们知道如何分隔method =“ Get”或method =“ POST”。因此您的视图将如下所示:
view.py:
def navbar_aggregation(request):
if request.method == "POST":
form = ProfileForm(request.POST)
if form.is_valid():
first_name = request.session['username']
print(first_name)
test = Profile.objects.filter(first_name=first_name).values()
for i in test:
dict1 = i
return render(request, 'index.html',
{'first_name': first_name, 'last_name': dict1['last_name'],
'phone_number': dict1['phone_number'], 'email':
dict1['email'],
'address': dict1['address'], 'image': dict1['image']})
else : # we are in method="GET"
type = request.get.Get("type") # name of hidden input
if(type == "friends"):
friends_obj = Friends.objects.all()
return render(request, 'index.html', {'friends_obj': friends_obj})
elif(type == "form"):
form = ProfileForm()
return render(request, 'profile.html', {'form': form})
elif(type == "foo"):
# do something for foo's form
return something
else: # for sure it should be home's request because haven't any tag for "type"
return render(request, 'index.html', {})
亲爱的朋友,我也是django的新手,所以我认为我的答案代码中有一些bug,但也许会对您有所帮助。我回答了您的问题,因为我没有看到任何专业开发人员没有回答您的问题。