问题
when i try to add a post method in my app it shows this message :
Method not allowed (Post): HTTP/1.1 405 0
Views.py:
class AddTeamView(View):
def get(self, request):
form = TeamForm()
context = {'form': form}
return render(request, 'add_team.html', context)
add_team.html :
{% extends 'base.html' %}
{% block title %}
Add a Team
{% endblock %}
{% block content %}
<form action="/add_team/" method="post">
{% csrf_token %}
<!-- this form content is called from the view.py/context-->
{{ form }}
<input type="submit" value="اضافة "/>
</form>
{% endblock %}
urls.py:
urlpatterns =[
url(r'^admin/', admin.site.urls),
url(r'add_team/$', AddTeamView.as_view(), name='add-team-view'),
]
settings.py:
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
forms.py :
from django import forms
class TeamForm(forms.Form):
name = forms.CharField(label='اسم الفريق')
details = forms.CharField(label='تفاصيل الفريق')
can anyone help plz?
回答1:
Like Daniel Roseman's comment says, you need to add a post method to your view. When you submit the filled form the HTTP request from your browser is a POST, not a GET.
Check out the the Django documentation for an example of how to organize a basic class view like you are trying to use with a post and get method.
Here is the documentation example modified for your case:
class AddTeamView(View):
form_class = TeamForm
template_name = 'add_team.html'
# Handle GET HTTP requests
def get(self, request, *args, **kwargs):
form = self.form_class(initial=self.initial)
return render(request, self.template_name, {'form': form})
# Handle POST GTTP requests
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
if form.is_valid():
# <process form cleaned data>
return HttpResponseRedirect('/success/')
return render(request, self.template_name, {'form': form})
来源:https://stackoverflow.com/questions/52244156/method-not-allowed-post-in-django