PUT方法不能在我的Django rest框架中工作。PUT方法在django REST中不起作用?
Models.py
class Profile(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30,blank=True)
相應視圖
class ProfileDetailsView(APIView):
"""
Get, udpate, a user's profile
"""
template_name = 'users/profile.html'
form_class = UserProfileForm
authentication_classes = (SessionAuthentication,)
def get_object(self, pk):
try:
return Profile.objects.get(pk=pk)
except Profile.DoesNotExist:
raise Http404
def get(self, request, pk, format=None):
print "111111111111111111"
profile = self.get_object(pk)
serializer = UserProfileSerializer(profile)
return render(request, self.template_name, context=serializer.data)
def put(self, request, pk):
print "2222222222222222222"
當我請求頁面(GET)時,它顯示相應的信息(配置文件信息)。但是當我提交頁面(PUT)時,它仍然會到get
部分而不是put
。 當我使用REST視圖時,它運行良好。問題出在Web視圖(html)。我錯過了什麼? 任何幫助表示讚賞
HTML頁面
<form class="form-profile" >{% csrf_token %}
<div class="form-horizontal">
<div class="form-group">
<label class="col-sm-2 control-label">First name</label>
<div class="col-sm-10">
<input value="{{first_name}}" class="form-control" id="first_name" maxlength="255" name="first_name" placeholder="First name" required="required" type="text" />
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Last name</label>
<div class="col-sm-10">
<input value="{{last_name}}" class="form-control" id="last_name" maxlength="255" name="last_name" placeholder="First name" type="text" />
</div>
</div>
</div>
</form>
這將是HTML的情況下是正確的。但我的問題是我怎樣才能使用Django?使用REST框架的django中的PUT請求,或者我如何更新配置文件的細節 –
取決於你想使用什麼,幾乎所有的HTTP客戶端都能夠做到。我在你的網頁中加入了jQuery的鏈接,並在你的網頁中加入了curl的鏈接 – bakkal
我想我現在看到你的問題好一點了,這是一些RESTful API(例如DRF中的標準ModelViewSet)使用POST之間的不匹配只是爲了創建和PUT來更新,而Django HTML沒有提供這樣的區別。所以通常如果你想保留HTML表單,你通常從表單中讀取提交對象的ID(主鍵),如果該表單中存在該ID,那麼這是一個更新。如果它是空白的,那麼它是一個創造。我希望這給你。否則,你的APIView可以自由地使用POST來進行這兩種操作,只需要讀取ID/PK參數。 – bakkal