--- Title: 'モデルの追加・更新・削除 #django' Keywords: - django Author: junshimo2 Web: https://mimemo.io/m/mqLXOlJANVozQ19 --- # モデルの追加・更新・削除 #### testapp/urls.py ```python urlpatterns = [ # ... path('insert/', UserView.insert, name='insert'), path('update//', UserView.update, name='update'), path('delete//', UserView.delete, name='delete'), ] ``` ### template #### testapp/templates/users.html ``` html {% for user in users %}
{% csrf_token %} {{ user.id }} {{ user.created_at }} {{ user.updated_at }}
{% endfor %}
{% csrf_token %} 名前
``` ## 追加のview #### testapp/views/user_view.py ``` python def insert(request): user=AppUser() user.name = request.POST.get('username', None) user.created_at = datetime.now() user.updated_at = datetime.now() user.save() return HttpResponseRedirect('/') ``` ## 更新・削除・一括削除の振り分け #### testapp/views/user_view.py ``` python if not request.POST.get('delete', None) == None: user = AppUser.objects.filter(id=userid).first() if not user == None: user.delete() if not request.POST.get('batch_delete', None) == None: ids_list = request.POST.getlist('batch_ids[]') print(ids_list) UserView.batch_delete(ids_list) return HttpResponseRedirect('/batch_delete') else: user = AppUser.objects.filter(id=userid).first() if not user == None: user.name = request.POST.get('name', None) user.updated_at = datetime.now() user.save() ``` ## 更新のview #### testapp/views/user_view.py ``` python user = AppUser.objects.filter(id=userid).first() if not user == None: user.name = request.POST.get('name', None) user.updated_at = datetime.now() user.save() ``` ## 削除のview #### testapp/views/user_view.py ``` python user = AppUser.objects.filter(id=userid).first() if not user == None: user.delete() ```