Beispiel #1
0
def add_thought(request):
    if request.method == 'POST':
        thought = request.POST['thought']
        thought_validation = validate_thought(thought)
        if len(thought_validation) > 0:
            for key, value in thought_validation.items():
                messages.error(request, value)
            return redirect('/thoughts')
        user = get_user(request.session['id'])
        set_thought(thought, user)
    return redirect('/thoughts')
Beispiel #2
0
def question_delete(request, question_id):
    """
    pybo question delete
    """
    question = get_object_or_404(Question, pk=question_id)
    if request.user != question.author:
        messages.error(request, 'No permission')
        return redirect('pybo:detail', question_id=question.id)

    question.delete()
    return redirect('pybo:index')
Beispiel #3
0
def delete(request, pk):
    note = get_object_or_404(Note, pk=pk)
    if note.user != request.user:
        logger.warning("Attempt of deleting note")
        messages.error(request,
                       "You are not authenticated to perform this action")
    else:
        logger.info("Note was deleted successfully")
        note.delete()

    return redirect("index")
Beispiel #4
0
def comment_delete_question(request, comment_id):
    """
    Comment Delete
    """
    comment = get_object_or_404(Comment, pk=comment_id)
    if request.user != comment.author:
        messages.error(request, 'No Permission')
        return redirect('pybo:detail', question_id=comment.question_id)
    else:
        comment.delete()
    return redirect('pybo:detail', question_id=comment.question_id)
    def save_model(self, request, obj, form, change):
        """ """

        if request.user.is_superuser:
            if obj.user_id in [None, '']:
                obj.user_id = generate_user_id(prefix="USR")
            if change and ('password' in form.changed_data):
                obj.set_password(form.cleaned_data['password'])
            obj.save()
        else:
            messages.error(request,
                           "You are not authorized to create an entry")
        return
Beispiel #6
0
def register(request):
    if request.method == 'POST':
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            messages.success(request, f'Account created for {username}!')
            return redirect('/')
        else:
            messages.error(request, 'wrong parameters')
    else:
        form = UserRegisterForm()
    return render(request, 'registration/register.html', {'form': form})
Beispiel #7
0
def excluir_arquivo(documento):
    """
    Função que exclui o documento cadastrado e enviado para a pasta de
    mídias de documentos do projeto
    """

    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
    try:
        os.remove('{}/{}'.format(MEDIA_ROOT, documento))
    except:
        messages.error(request, 'o arquivo não existe!')

    return None
Beispiel #8
0
def change_password(request):
    if request.method == 'POST':
        form = PasswordChangeForm(request.user, request.POST)
        if form.is_valid():
            user = form.save()
            update_session_auth_hash(request, user)  # Important!
            messages.success(request,
                             'Your password was successfully updated!')
            return redirect('change_password')
        else:
            messages.error(request, 'Please correct the error below.')
    else:
        form = PasswordChangeForm(request.user)
    return render(request, 'accounts/change_password.html', {'form': form})
Beispiel #9
0
def activate(request, uidb64, token):
    try:
        uid = force_text(urlsafe_base64_decode(uidb64))
        user = User.objects.get(pk=uid)
    except(TypeError, ValueError, OverflowError, User.DoesNotExist):
        user = None
    if user is not None and account_activation_token.check_token(user, token):
        user.is_active = True
        user.save()
        login(request, user)
        messages.error(request, 'Dziękuję za potwierdzenie. Teraz możesz się zalogować')
        return redirect ('oddam:login')
    else:
        return HttpResponse('Activation link is invalid!')
Beispiel #10
0
def process_order(request):
    """ Process orders made via web form and verified by SMS PIN. """
    form = OrderForm(request.POST or None)

    if form.is_valid():
        otp = int(request.POST.get("pin", "0"))
        contact_number = request.POST.get("contact_number", "")

        if _verify_otp(contact_number, otp):
            form.save()
            return redirect('transaction_complete')
        else:
            messages.error(request, "Invalid OTP!")
    else:
        return render(request, 'register.html', {'form': form})
Beispiel #11
0
 def wrap(request, *args, **kwargs):
     request.recaptcha_is_valid = None
     if request.method == 'POST':
         recaptcha_response = request.POST.get('g-recaptcha-response')
         data = {
             'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY,
             'response': recaptcha_response
         }
         r = requests.post('https://www.google.com/recaptcha/api/siteverify', data=data)
         result = r.json()
         if result['success']:
             request.recaptcha_is_valid = True
         else:
             request.recaptcha_is_valid = False
             messages.error(request, 'Invalid reCAPTCHA. Please try again.')
     return function(request, *args, **kwargs)
Beispiel #12
0
 def post(self, request, *args, **kwargs):
     pass
     form = SignUpForm(request.POST)
     #import ipdb
     #ipdb.set_trace()
     if form.is_valid():
         user = User.objects.create_user(**form.cleaned_data)
         user.save()
         user = authenticate(request,
                             username=form.cleaned_data['username'],
                             password=form.cleaned_data['password'])
         if user is not None:
             #login(request,user)
             return redirect('/colleges/')
         else:
             messages.error(request, "Invalid Credentials")
Beispiel #13
0
 def post(self, request):
     pass
     form = LoginForm(request.POST)
     # import ipdb
     # ipdb.set_trace()
     username = request.POST['username']
     password = request.POST['password']
     if form.is_valid():
         #user = User.objects.create_user(**form.cleaned_data)
         #user.save()
         user = authenticate(request, username=username, password=password)
         if user is not None:
             login(request, user)
             return redirect('/my_account/questions/')
         else:
             messages.error(request, "Invalid Credentials")
Beispiel #14
0
def question_modify(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    if request.user != question.author:
        messages.error(request, '수정권한이 없습니다.')
        return redirect('pybo:detail', question_id=question.id)

    if request.method == "POST":
        form = QuestionForm(request.POST, instance=question)
        question = form.save(commit=False)
        question.author = request.user
        question.modify_date = timezone.now()
        question.save()
        return redirect('pybo:detail', question_id=question.id)
    else:
        form = QuestionForm(instance=question)
    context = {'form': form}
    return render(request, 'pybo/question_form.html', context)
Beispiel #15
0
def comment_modify_answer(request, comment_id):
    comment = get_object_or_404(Comment, pk=comment_id)
    if request.user != comment.author:
        messages.error(request, '댓글수정권한이 없습니다.')
        return redirect('pybo:detail', question_id=comment.answer.question.id)

    if request.method == "POST":
        form = CommentForm(request.POST, instance=comment)
        comment = form.save(commit=False)
        comment.author = request.user
        comment.modify_date = timezone.now()
        comment.save()
        return redirect('pybo:detail', question_id=comment.answer.question.id)
    else:
        form = CommentForm(instance=comment)
    context = {'form': form}
    return render(request, 'pybo/answer_form.html', context)
Beispiel #16
0
def answer_modify(request, answer_id):
    answer = get_object_or_404(Answer, pk=answer_id)
    if request.user != answer.author:
        messages.error(request, '수정권한이 없습니다.')
        return redirect('pybo:detail', question_id=answer.question.id)

    if request.method == "POST":
        form = AnswerForm(request.POST, instance=answer)
        answer = form.save(commit=False)
        answer.author = request.user
        answer.modify_date = timezone.now()
        answer.save()
        return redirect('pybo:detail', question_id=answer.question.id)
    else:
        form = AnswerForm(instance=answer)
    context = {'answer': answer, 'form': form}
    return render(request, 'pybo/answer_form.html', context)
 def update_profile(request):
     if request.method == 'POST':
         # user_form = UserForm(request.POST, instance=request.user)
         profile_form = ProfileForm(request.POST,
                                    instance=request.user.profile)
         if profile_form.is_valid():
             profile_form.save()
             messages.success(request,
                              _('Your profile was successfully updated!'))
             return redirect('directory:home')
         else:
             messages.error(request, _('Please correct the error below.'))
     else:
         # user_form = UserForm(instance=request.user)
         profile_form = ProfileForm(instance=request.user.profile)
     return render(request, 'profiles/profile.html',
                   {'profile_form': profile_form})
Beispiel #18
0
def updateTvShow(request, tvShowId):
    if request.method == "POST":
        title = request.POST['title']
        network = request.POST['network']
        releaseDate = request.POST['release_date']
        description = request.POST['description']

        errors = validate_set_tv_show(request.POST)
        if len(errors) > 0:
            for key, value in errors.items():
                messages.error(request, value)
            return redirect('/shows/'+str(tvShowId)+'/edit')
        else:
            models.updateTvShow(tvShowId, title, network, releaseDate, description)
            messages.success(request, "row updated successfully")
            return redirect('/shows/'+str(tvShowId))
    return redirect('/shows/'+str(tvShowId)+'/edit')
Beispiel #19
0
def delete(request, audioFileType, audioFileID):
    if audioFileType == 'song':
        song_item = Song.objects.get(id=audioFileID)
        song_item.delete()
        messages.success(request, f'{audioFileType} is deleted.')
    elif audioFileType == 'podcast':
        pod_item = Podcast.objects.get(id=audioFileID)
        pod_item.delete()
        messages.success(request, f'{audioFileType} is deleted.')
    elif audioFileType == 'audiobook':
        aud_item = Audiobook.objects.get(id=audioFileID)
        aud_item.delete()
        messages.success(request, f'{audioFileType} is deleted.')
    else:
        messages.error(request, f'Can not delete {audioFileType}.')

    return redirect('home')
Beispiel #20
0
def user_signup(request):
    if request.user.is_authenticated:
        return render(request, 'home.html')
    if request.method == 'POST':
        username = request.POST.get('username')
        useremail = request.POST.get('useremail')
        password = request.POST.get('password')
        if username_exists(username) == False and usermail_exists(
                useremail) == False:
            user = User.objects.create_user(username, useremail, password)
            login(request, user)
            return redirect("index")
        else:
            messages.error(request, 'User Name or email already exist.')
            return render(request, 'signup.html')
    else:
        return render(request, 'signup.html')
def answer_delete(request, comment_id):
    comment = get_object_or_404(Comment, pk=comment_id)
    user_id = request.session.get('user')
    member = User.objects.get(pk=user_id)
    if member == comment.writer:
        print("2")
        comment.delete()
    elif member == comment.board.writer:
        print("3")
        comment.delete()
    elif member.n_name == '관리자':
        print("4")
        comment.delete()
    else:
        print("1")
        messages.error(request, '삭제권한이 없습니다')

    return redirect('board:detail', pk=comment.board.id)
Beispiel #22
0
def registerUser(request):
    if request.method == 'POST':
        user = Users(name=request.POST['name'],
                     prenom=request.POST['prenom'],
                     email=request.POST['email'],
                     city=request.POST['city'])
        try:
            user.email = validate_email(request.POST.get('email'))
            user.email = request.POST.get('email')
            user.save()
            messages.success(request,
                             'Vous avez Ajouter un utilisateur avec succés')
            return redirect('/')
        except EmailNotValidError:
            messages.error(request, 'email est pas valide')
            return render(request, 'users/form.html')
    else:
        return render(request, 'users/form.html')
Beispiel #23
0
def order(requests):

    if requests.method == 'POST':
        form = OrderForm(requests.POST)
        if form.is_valid():
            form.save()
            if form.save().id:
                messages.success(
                    requests,
                    f"You have ordered {form.save().quantity} {form.save().stock_item.product}(s)!"
                )
            else:
                messages.error(requests, 'No Stock!')
            return redirect("order")

    else:
        form = OrderForm()

    return render(requests, 'items/order.html', {'form': form})
Beispiel #24
0
def user_login(request):
    if request.user.is_authenticated:
        return render(request, 'home.html')
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(username=username, password=password)
        if user:
            if user.is_active:
                login(request, user)
                return HttpResponseRedirect(reverse('index'))
            else:
                messages.error(request, 'Your account was inactive.')
                return render(request, 'login.html')
        else:
            messages.error(request, 'Invalid login details given.')
            return render(request, 'login.html')
    else:
        return render(request, 'login.html')
class OnlyStaffMixin(object):
    def dispatch(self. request, *args, **kwargs):

        if not request.user.is_staff:
            messages.error(request, "Only Staff members can do this.")

            try:
                return HttpResponseRedirect(request.META['HTTP_REFERER'])
            except keyError:
                return HttpResponseRedirect('/')
        return super(OnlyStaffMixin, self).dispatch(request, *args, **kwargs)
Beispiel #26
0
def user_profile_view(request):
    if request.method == 'POST':
        user_form = UserForm(request.POST, instance=request.user)
        usuario_form = UsuarioForm(request.POST, instance=request.user.usuario)
        context = {
            "user_form": user_form,
            "usuario_form": usuario_form,
        }
        if user_form.is_valid() and usuario_form.is_valid():
            user_form.save()
            usuario_form.save()
            messages.success(request, 'Your profile was successfully updated!')
            return render(request, "profile.html", context)
        else:
            messages.error(request, 'Please correct the error below.')
    else:
        user_form = UserForm(instance=request.user)
        profile_form = UsuarioForm(instance=request.user.profile)

    return render(request, "profile.html", context)
Beispiel #27
0
def login(request):
    if request.method == 'POST':
        form = AuthenticationForm(request=request, data=request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            user = authenticate(username=username, password=password)
            if user is not None:
                login(request, user)
                messages.info(request, f"You are now logged in as {username}")
                return redirect('/')
            else:
                messages.error(request, "Invalid username or password")
        else:
            messages.error(request, "Invalid username or password")

    form = AuthenticationForm()
    return render(request=request,
                  template_name='login.html',
                  context={"form": form})
Beispiel #28
0
def login_page(request):
    if request.method == 'GET':
        if request.user.is_authenticated:
            render(request, 'dialogs.html')
        return render(request, 'login.html')
    if request.method == 'POST':
        username = request.POST.get('login', '')
        password = request.POST.get('password', '')

        if username == '' or password == '':
            return HttpResponse("Заполните все поля")

        # проверяем правильность логина и пароля
        user = authenticate(username=username, password=password)
        if user is not None:
            login(request, user)
            return redirect('/dialogs')
        else:
            messages.error(request, 'Неправильный логин или пароль!')
            return render(request, 'login.html')
Beispiel #29
0
def change_password(request):
    if request.method == 'POST':
        password_form = PasswordChangeForm(data=request.POST,
                                           user=request.user)
        if password_form.is_valid():
            password_form.save()
            update_session_auth_hash(request, password_form.user)
            messages.success(request, 'Your account has been updated')
            return redirect(request.path_info)
        else:
            messages.error(request, password_form.errors)

    else:
        password_form = PasswordChangeForm(data=request.POST,
                                           user=request.user)
    context = {
        'password_form': password_form,
    }

    return render(request, 'profiles/change_password.html', context)
Beispiel #30
0
def clientes_upload(request):
    template_name = "clientes/upload.html"
    prompt = {"Ordem": "first_name, last_name, age, salary, bio"}
    if request.method == "GET":
        return render(request, template_name, prompt)
    csv_file = request.FILES["file"]
    if not csv_file.name.endswith(".csv"):
        messages.error(request, "Esta file não é csv")
    data_set = csv_file.read().decode("UTF-8")
    io_string = io.StringIO(data_set)
    next(io_string)
    for column in csv.reader(io_string, delimiter=",", quotechar="|"):
        _, created = Person.objects.update_or_create(
            first_name=column[0],
            last_name=column[1],
            age=column[2],
            salary=column[3],
            bio=column[4],
        )
    context = {}
    return render(request, template_name, context)