def add_product(request): if request.method == 'POST': if request.user.is_staff: form = ProductAddForm(request.POST, request.FILES) if form.is_valid(): name = form.cleaned_data['name'] category = form.cleaned_data['category'] brand = form.cleaned_data['brand'] count = form.cleaned_data['count'] discount = form.cleaned_data['discount'] description = form.cleaned_data['description'] price = form.cleaned_data['price'] product = Product.objects.create(name=name, category=category, brand=brand, description=description, count=count, discount=discount, price=price) product.imgpath = product.id product.save() photo = request.FILES['photo'] handle_uploaded_product(photo, product.imgpath) return HRR('/add') else: return render( request, 'add_error.html', { 'header': 'Проверьте правильность введенных данных и попробуйте еще раз' }) else: return HRR('/permission_deny/')
def delete_product(request): if request.user.is_staff: product_id = default_include_undefined_for_get_request( request, 'id', -1) if len(Product.objects.filter(id=product_id)): Product.objects.get(id=product_id).delete() return HRR('/') else: return HRR('/args_error/') else: return HRR('/permission_deny/')
def add_account(request, user_id): title = request.POST['title'] username = request.POST['user'] password = request.POST['pass'] user = User.objects.get(pk=user_id) if title and username and password: user.account_set.create(title=title, username=username, password=password) return HRR(reverse('pm:index', args=(user.id, ))) return HRR(reverse('pm:index', args=(user.id, )))
def add_category(request): if request.method == 'POST': if request.user.is_staff: form = CategoryAddForm(request.POST) if form.is_valid(): name = form.cleaned_data['name_category'] Category.objects.create(name=name) return HRR('/add') else: return render( request, 'add_error.html', { 'header': 'Проверьте правильность введенных данных и попробуйте еще раз' }) else: return HRR('/permission_deny/')
def authorization(request): if request.method == 'GET': return render(request, 'signin.html', {'auth_form': UserAuthForm}) elif request.method == 'POST': form = UserAuthForm(request.POST) if form.is_valid(): user = authenticate(request, email=form.cleaned_data['email'], password=form.cleaned_data['password']) if user is not None: login(request, user) return HRR('/') else: return render( request, 'signin.html', { 'auth_form': form, 'header': 'Введенный вами email или пароль неверны' }) else: return render( request, 'signin.html', { 'auth_form': form, 'header': 'Проверьте введенные вами данные и попробуйте еще раз' })
def edit_product(request): if request.user.is_staff: if request.method == 'GET': product_id = default_include_undefined_for_get_request( request, 'id', -1) if len(Product.objects.filter(id=product_id)): product = Product.objects.get(id=product_id) form = ProductEditForm(instance=product) return render(request, 'product_edit.html', { 'edit_form': form, 'id': product_id }) else: return HRR('/args_error/') elif request.method == 'POST': form = ProductEditForm(request.POST, request.FILES) if form.is_valid(): product_id = form.cleaned_data['id'] try: product = Product.objects.get(id=product_id) product.name = form.cleaned_data['name'] product.category = form.cleaned_data['category'] product.brand = form.cleaned_data['brand'] product.count = form.cleaned_data['count'] product.discount = form.cleaned_data['discount'] product.description = form.cleaned_data['description'] product.price = form.cleaned_data['price'] product.save() try: if request.FILES['photo'] is not None: photo = request.FILES['photo'] handle_uploaded_product(photo, product.imgpath) print('ok------------') except MultiValueDictKeyError: pass return HRR(f'/product/{product_id}') except exceptions.ObjectDoesNotExist: return HRR('/args_error/') else: return render( request, 'add_error.html', { 'header': 'Проверьте правильность введенных данных и попробуйте еще раз' }) else: return HRR('/permission_deny/')
def my_cart_change_count(request): if request.method == 'GET': cart_id = default_include_undefined_for_get_request(request, 'id', -1) if cart_id != -1: count = int( default_include_undefined_for_get_request( request, 'count', -1)) if count != 0: try: cart = Carts.objects.get(id=cart_id) if cart.user == request.user or cart.ip == get_client_ip( request): cart.count = count cart.save() return HRR('/mycart/') else: return HRR('/permission_deny/') except exceptions.ObjectDoesNotExist: return HRR('/args_error/') else: try: cart = Carts.objects.get(id=cart_id) if cart.user == request.user or cart.ip == get_client_ip( request): cart.delete() return HRR('/mycart/') else: return HRR('/permission_deny/') except exceptions.ObjectDoesNotExist: return HRR('/args_error/') else: return HRR('/args_error/')
def remove_account(request, user_id, account_id): user = get_object_or_404(User, pk=user_id) try: account = user.account_set.get(pk=account_id) except Account.DoesNotExist: pass else: account.delete() return HRR(reverse('pm:index', args=(user.id, )))
def pass_change(request): if request.method == 'GET': return render(request, 'password_change.html', {'change_form': UserPasswordChange}) else: form = UserPasswordChange(request.POST) if form.is_valid(): if request.user.is_authenticated: last_password = form.cleaned_data['password1'] if authenticate(request, email=request.user.email, password=last_password) is not None: new_password1 = form.cleaned_data['password2'] new_password2 = form.cleaned_data['password3'] if new_password1 == new_password2: request.user.set_password(new_password1) request.user.save() return HRR(f'/users/user/{request.user.id}') else: return render( request, 'password_change.html', { 'change_form': UserPasswordChange, 'header': 'Введенные вами новые пароли не совпадают' }) else: return render( request, 'password_change.html', { 'change_form': UserPasswordChange, 'header': 'Введенный прошлый пароль неверен' }) else: return HRR('/permission_deny') else: return render( request, 'password_change.html', { 'change_form': UserPasswordChange, 'header': 'Пожалуйста, проверьте правильность введенных данных и попробуйте еще раз' })
def add(request): if request.method == 'GET': if request.user.is_staff: return render( request, 'add.html', { 'category_add_form': CategoryAddForm, 'brand_add_form': BrandAddForm, 'product_add_form': ProductAddForm }) else: return HRR('/permission_deny/')
def new_topic(request): if request.method != 'POST': form = TopicForm() else: form = TopicForm(request.POST) if form.is_valid(): new_topic = form.save(commit=False) new_topic.owner = request.user new_topic.save() return HRR(reverse('learning_logs:topics')) context = {'form': form} return render(request, 'learning_logs/new_topic.html', context)
def delete_from_favorites(request): if request.method == 'GET': favorite_id = int( default_include_undefined_for_get_request(request, 'id', -1)) if favorite_id > -1: if request.user.is_authenticated: try: Favorites.objects.get(id=favorite_id, user=request.user).delete() except exceptions.ObjectDoesNotExist: return HRR('/args_error/') else: try: Favorites.objects.get(id=favorite_id, ip=get_client_ip(request)).delete() except exceptions.ObjectDoesNotExist: return HRR('/args_error/') return HRR('/myfavorites/') else: return HRR('/args_error/')
def rate_product(request): if request.user.is_authenticated: try: product = Product.objects.get(id=request.GET['product']) except exceptions.ObjectDoesNotExist: return HRR('/') try: last_rate = Rates.objects.get(user=request.user, product=product) if last_rate.rate == int(request.GET['rate']): last_rate.delete() else: last_rate.rate = int(request.GET['rate']) last_rate.save() except exceptions.ObjectDoesNotExist: Rates.objects.create(user=request.user, rate=request.GET['rate'], product=product) return HRR(f'/product/{product.id}') else: return HRR('/users/auth/')
def register(request): if request.method != 'POST': form = UserCreationForm() else: form = UserCreationForm(data=request.POST) if form.is_valid(): new_user = form.save() authenticated_user = authenticate( username=new_user.username, password=request.POST['password1']) login(request, authenticated_user) return HRR(reverse('learning_logs:index')) context = {'form': form} return render(request, 'users/register.html', context)
def edit_entry(request, entry_id): entry = Entry.objects.get(id=entry_id) topic = entry.topic if topic.owner != request.user: raise Http404 if request != 'POST': form = EntryForm(instance=entry) else: form = EntryForm(instance=entry, data=request.POST) if form.is_valid(): form.save() return HRR(reverse('learning_logs:topic', args=[topic.id])) context = {'entry': entry, 'topic': topic, 'form': form} return render(request, 'learning_logs/edit_entry.html', context)
def restore(request): if request.method == 'GET': return render(request, 'restore.html', {'rest_form': UserRestoreForm}) elif request.method == 'POST': form = UserRestoreForm(request.POST) if form.is_valid(): if captcha_check(): # TODO on deploy try: user = CustomUser.objects.get( email=form.cleaned_data['email']) except ObjectDoesNotExist: user = None if user is not None: new_pass = ''.join([ 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890'[ random.randint(0, 61)] for _ in range(8) ]) user.set_password(new_pass) user.save() send_mail( f'Ваш новый пароль на сайте {settings.SITE_NAME} !', f'Ваш новый пароль:{new_pass}\n' f'Ссылка на авторизацию: http://{request.META["HTTP_HOST"]}/users/auth/\n' f'Пожалуйста, свяжитесь с нами, если это были не вы.', '*****@*****.**', [form.cleaned_data['email']], fail_silently=False) return HRR('/users/auth/') else: return render( request, 'restore.html', { 'rest_form': form, 'header': 'Аккаунта с данным адресом почты не существует' }) else: return render( request, 'signup.html', { 'reg_form': form, 'header': 'Капча неверна, попробуйте еще раз' }) else: return render( request, 'restore.html', { 'rest_form': form, 'header': 'Проверьте правильность введнных данных и попробуйте еще раз' })
def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): return render(request, './detail.html', { 'question': question, 'error_message': "You didn`t select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() return HRR(reverse('polls:results', args=(question.id, )))
def make_admin(request): if request.method == 'POST': if request.user.is_authenticated: if request.user.is_staff: form = UserUpToAdminForm(request.POST) if form.is_valid(): some_user_id = int(form.cleaned_data['sid']) some_user = CustomUser.objects.get(id=some_user_id) some_user.is_staff = True some_user.save() return HRR(f'/users/user/{some_user_id}/') else: return render(request, 'permission_deny_error.html') else: return render(request, 'log_must_error.html')
def new_entry(request, topic_id): topic = Topic.objects.get(id=topic_id) if topic.owner != request.user: raise Http404 if request.method != 'POST': form = EntryForm() else: form = EntryForm(data=request.POST) if form.is_valid(): new_entry = form.save(commit=False) new_entry.topic = topic new_entry.save() return HRR(reverse('learning_logs:topic', args=[topic_id])) context = {'topic': topic, 'form': form} return render(request, 'learning_logs/new_entry.html', context)
def validate_login(request): username = request.POST['username'] password = request.POST['password'] if not username or not password: return render(request, 'passwordmanager/login.html', {'error_message': 'Please fill the required fields'}) else: try: user = User.objects.get(username=username, password=password) except User.DoesNotExist: return render(request, 'passwordmanager/login.html', {'error_message': 'Incorrect username or password'}) else: return HRR(reverse('pm:index', args=(user.id, )))
def add_task(request): now = timezone.now() if request.POST['new_task']: new_task = Todo(task=request.POST['new_task'], task_date=now) new_task.save() else: index_template = 'todo/index.html' return render( request, index_template, { 'tasks': Todo.objects.filter( task_date__lte=timezone.now()).order_by('task_date'), 'error_message': 'Please input some task.' }) return HRR(reverse('todo:index'))
def validate_registration(request): username = request.POST['username'] password = request.POST['password'] confirm_pass = request.POST['confirm-pass'] if not username or not password or not confirm_pass: # Renders an error message return render(request, 'passwordmanager/register.html', {'error_message': 'Please fill the missing fields'}) elif password != confirm_pass: # Renders an error message return render(request, 'passwordmanager/register.html', {'error_message': "Password doesn't match"}) else: try: User.objects.get(username=username, password=password) except User.DoesNotExist: User.objects.create(username=username, password=password) return HRR(reverse('pm:login')) else: return render( request, 'passwordmanager/register.html', {'error_message': 'Username or Password already exist'})
def user_change(request): if request.method == 'GET': if request.user.is_authenticated: return render(request, 'user_change.html', {'edit_form': UserEditForm}) else: return render(request, 'log_must_error.html') elif request.method == 'POST': if request.user.is_authenticated: form = UserEditForm(request.POST) if form.is_valid(): status = user_edit_form_valid(form.cleaned_data) if type(status) is bool: user = request.user user.entity = form.cleaned_data['entity'] user.phone = form.cleaned_data['phone'] user.name = form.cleaned_data['name'] user.soname = form.cleaned_data['soname'] user.save() return HRR(f'/users/user/{user.id}') else: return render(request, 'user_change.html', { 'edit_form': form, 'header': status }) else: return render( request, 'user_change.html', { 'edit_form': form, 'header': 'Пожалуйста, проверьте правильность введенных данных и попробуйте еще раз' }) else: return render(request, 'log_must_error.html')
def registration(request): if request.method == 'GET': return render(request, 'signup.html', {'reg_form': UserCreationForm}) elif request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): if captcha_check(): # TODO on deploy status = user_creation_form_valid(form.cleaned_data) if type(status) is bool: CustomUser.objects.create_user( email=form.cleaned_data['email'], password=form.cleaned_data['password1'], phone=form.cleaned_data['phone'], name=form.cleaned_data['name'], soname=form.cleaned_data['soname'], entity=form.cleaned_data['entity']) return HRR('/users/auth/') else: return render(request, 'signup.html', { 'reg_form': form, 'header': status }) else: return render( request, 'signup.html', { 'reg_form': form, 'header': 'Капча неверна, попробуйте еще раз' }) else: return render( request, 'signup.html', { 'reg_form': form, 'header': 'Проверьте введенную вами информацию и попробуйте еще раз' })
def logout_view(request): logout(request) return HRR(reverse('learning_logs:index'))
def add_in_cart_or_favorite(request): """ Here, I use many times filter() instead the get() method, because in get, if object does not exist it returns exception.""" if request.method == 'GET': where = default_include_undefined_for_get_request(request, 'in', None) if where is not None: product_id = default_include_undefined_for_get_request( request, 'id', None) if product_id is not None: if len(Product.objects.filter(id=product_id)): product = Product.objects.filter(id=product_id)[0] if request.user.is_authenticated: if where == 'cart': if len( Carts.objects.filter(product=product, user=request.user)): cart = Carts.objects.get(product=product, user=request.user) cart.count += 1 cart.save() else: Carts.objects.create(product=product, count=1, user=request.user) if where == 'star': if len( Favorites.objects.filter( product=product, user=request.user)): favorite = Favorites.objects.get( product=product, user=request.user) favorite.count += 1 favorite.save() else: Favorites.objects.create(product=product, user=request.user, count=1) else: ip = get_client_ip(request) anonym = CustomUser.objects.get(id=3) if where == 'cart': if len( Carts.objects.filter(product=product, user=anonym, ip=ip)): cart = Carts.objects.get(product=product, user=anonym, ip=ip) cart.count += 1 cart.save() else: Carts.objects.create(product=product, count=1, user=anonym, ip=ip) if where == 'star': if len( Favorites.objects.filter(product=product, user=anonym, ip=ip)): favorite = Favorites.objects.get( product=product, user=anonym, ip=ip) favorite.count += 1 favorite.save() else: Favorites.objects.create(product=product, user=anonym, ip=ip, count=1) url = default_include_undefined_for_get_request( request, 'from', '/') return HRR(url.replace('~', '?').replace('№', '&')) else: return HRR('/args_error/') return HRR('/args_error/')
def delete_task(request, task_id): task = get_object_or_404(Todo, pk=task_id) task.delete() return HRR(reverse('todo:index'))
def log_out(request): logout(request) return HRR('/')