def monster_piece_edit(request, profile_name, instance_id): try: summoner = Summoner.objects.select_related('user').get( user__username=profile_name) except Summoner.DoesNotExist: return HttpResponseBadRequest() pieces = get_object_or_404(MonsterPiece, pk=instance_id) is_owner = (request.user.is_authenticated and summoner.user == request.user) template = loader.get_template( 'herders/profile/monster_inventory/monster_piece_form.html') if is_owner: form = MonsterPieceForm(request.POST or None, instance=pieces) form.helper.form_action = request.path if request.method == 'POST' and form.is_valid(): new_piece = form.save() template = loader.get_template( 'herders/profile/monster_inventory/monster_piece_snippet.html') context = { 'piece': new_piece, 'is_owner': is_owner, } response_data = { 'code': 'success', 'instance_id': new_piece.pk.hex, 'html': template.render(context), } else: # Return form filled in and errors shown context = {'form': form} context.update(csrf(request)) response_data = { 'code': 'error', 'html': template.render(context), } return JsonResponse(response_data) else: raise PermissionDenied()
def monster_piece_add(request, profile_name): try: summoner = Summoner.objects.select_related('user').get( user__username=profile_name) except Summoner.DoesNotExist: return HttpResponseBadRequest() is_owner = (request.user.is_authenticated and summoner.user == request.user) if is_owner: if request.method == 'POST': form = MonsterPieceForm(request.POST or None) else: form = MonsterPieceForm() form.helper.form_action = reverse( 'herders:monster_piece_add', kwargs={'profile_name': profile_name}) template = loader.get_template( 'herders/profile/monster_inventory/monster_piece_form.html') if request.method == 'POST' and form.is_valid(): # Create the monster instance new_pieces = form.save(commit=False) new_pieces.owner = request.user.summoner new_pieces.save() messages.success(request, 'Added %s to your collection.' % new_pieces) response_data = {'code': 'success'} else: # Return form filled in and errors shown context = {'form': form} context.update(csrf(request)) response_data = { 'code': 'error', 'html': template.render(context), } return JsonResponse(response_data) else: return HttpResponseForbidden()