def buyer_register(request): # user= request.user if request.method == 'POST': username = request.POST['username'] form = BuyerSignUpForm(request.POST) print(form) if form.is_valid(): new_form = form.save() # user = User.objects.filter(id=n) Buyer.objects.filter(user_ptr_id=new_form.id).update( phone_number=username, ) sweetify.success(request, 'Buyer Registered Successfully, Now Log In', persistent='Continue', timer=3000) return redirect('Shoppy:shoppy-login') else: form1 = BuyerSignUpForm(request.POST) sweetify.error(request, 'Error', text='Ensure you fill all fields correctly', persistent='Retry', timer=3000) return render(request, "shoppy/buyer-registration.html", {'form': form1}) else: form2 = BuyerSignUpForm() context = { 'form': form2, } return render(request, "shoppy/buyer-registration.html", context)
def form_invalid(self, form): sweetify.error(self.request, 'Algo salió mal', icon='error', buttons=False, text=" ") response = super().form_invalid(form) if self.request.is_ajax(): return JsonResponse(form.errors, status=400) else: return response
def profile(request): """Display the users profile""" profile = get_object_or_404(UserProfile, user=request.user) if request.method == "POST": form = UserProfileForm(request.POST, instance=profile) if form.is_valid(): form.save() sweetify.success(request, title='Success!', icon='success', text='Profile successfully updated', timer=4000) else: sweetify.error(request, title='Error!', icon='error', text='Failed to update profile, please try again', timer=4000) else: form = UserProfileForm(instance=profile) template = 'profiles/profile.html' context = { 'form': form, } return render(request, template, context)
def updateuserdetails(request): if request.method == 'POST': newsletter = request.POST.get('newsletter') blogger = Blogger.objects.filter(user_ptr_id=request.user.id).first() form = BloggerFormUpdate(request.POST, request.FILES, instance=blogger) # print(newsletter) if form.is_valid(): new_user = form.save() if newsletter is not None: if newsletter == 1: # print(newsletter) Newsletter.objects.create(email=new_user.email) elif newsletter == 0: # print(newsletter) n = Newsletter.objects.filter(email=new_user.email).first() n.delete() sweetify.success(request, 'Success', text='Updated', persistent='Ok') return redirect('BLOGBACK:userAccount') else: sweetify.error(request, 'Error', text=form.errors.as_json(), persistent='Ok') return redirect('BLOGBACK:userAccount')
def changepassword(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! sweetify.success(request, 'Success', text='Password Changed', persistent='Ok') return redirect(request.META['HTTP_REFERER']) else: print(form) l = [] y = json.loads(form.errors.as_json()) for k in y: l.append(k + ' ' + y[k][0]['message']) print(l) sweetify.error(request, 'Error', text=l, persistent='Ok') return redirect(request.META['HTTP_REFERER']) else: sweetify.error(request, 'Error', text='Error Changing Password', persistent='Ok') return redirect(request.META['HTTP_REFERER'])
def dashboard(request): all_school = User.objects.filter(is_school=True)[:10] total_sch_num = User.objects.filter(is_school=True).count() total_prof_num = User.objects.filter(is_professional=True).count() total_submited_index = Indexing.objects.filter(submitted=True).count() notification = Ticket.objects.filter( Q(ticket_status='School Reply') & Q(notification=False) | Q(ticket_status='Open') & Q(notification=False)).count() if 'admin/reset_notification' in request.path: try: notifications = Ticket.objects.filter( Q(ticket_status='School Reply') & Q(notification=False) & Q() | Q(ticket_status='Open') & Q(notification=False)) if notifications: reset = notifications.update(notification=True) return HttpResponseRedirect(reverse('adminPortal:all_ticket')) elif not notifications: sweetify.error(request, 'Notification is empty', button='Great!') return HttpResponseRedirect(reverse('adminPortal:all_ticket')) except: pass context = { 'all_school': all_school, 'total_sch_num': total_sch_num, 'total_submited_index': total_submited_index, 'notification': notification, 'total_prof_num': total_prof_num } return render(request, 'adminPortal/dashboard.html', context)
def form_invalid(self, form): response = super().form_invalid(form) return response errorResponse = "deu erro" sweetify.error(self.request, errorResponse, persistent='Ok') return response
def solicitacoes(request): mentor = mentor_auth.get(request) if mentor is not None: if mentor.aprovado: solicitacoes = Solicitacao.objects.filter(mentor=mentor, oculto=False) contexto = {'mentor': mentor, 'solicitacoes': solicitacoes} return render(request, 'mentor_solicitacoes.html', contexto) else: sweetify.error( request, 'Acesso restrito!', html= '<p>Seu cadastro ainda não foi aprovado!</p><p>Por favor aguarde o contato da nossa equipe!</p>', persistent=True) return redirect('app_auth_login') else: sweetify.error( request, 'Acesso restrito!', text='Você precisa estar autenticado para acessar esta página.', button='Ok', timer=3000) return redirect('app_auth_login')
def product_search(request): """ View allowing searching products using Product title or place""" query = request.GET.get('q') if query: query_group = Q(title__icontains=query) | Q(place__icontains=query) products = Product.objects.filter(query_group) if not products: sweetify.error( request, title="There is no photos matching your search criteria.", icon="warning") return redirect(reverse('all_products')) context = { 'products': products, 'query': query, 'title': "Photos search", } return render(request, "photos-search.html", context) sweetify.error(request, title="Search criteria is missing, please try again.", icon="warning") return redirect(reverse('all_products'))
def edit_car(request, car_id): """Edit an individual car details""" car = get_object_or_404(Car, pk=car_id) if request.method == 'POST': form = CarForm(request.POST, request.FILES, instance=car) if form.is_valid(): instance = form.save(commit=False) instance.user = request.user instance.save() sweetify.success(request, title='Success!', icon='success', text='Car successfully edited', timer=4000) return redirect(reverse('display_cars')) else: sweetify.error(request, title='Error!', icon='error', text='Failed to edit this car, please try again', timer=4000) else: form = CarForm(instance=car) template = 'cars/edit-car.html' context = { 'form': form, } return render(request, template, context)
def login(request): """ login user input: username and password """ # if request.user.is_authenticated: # return redirect("dashboard") # else: if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = auth.authenticate( username=username, password=password) # returns none or user object if user is not None: if user.is_active: # user_profile = Patient.objects.get(user=user) auth.login(request, user) # request.session['user'] = user_profile.user.username # request.session['uid'] = user_profile.user.pk return redirect('dashboard') else: return HttpResponse("Disabled account") else: messages.error(request, 'Invalid credentials') sweetify.error(request, 'Invalid credentials') return redirect('login') return render(request, 'accounts/login.html')
def add_car(request): """Add a car to the database""" if request.method == 'POST': form = CarForm(request.POST, request.FILES) if form.is_valid(): instance = form.save(commit=False) instance.user = request.user instance.save() sweetify.success(request, title='Success!', icon='success', text='Car successfully added', timer=4000) return redirect(reverse('add_car')) else: sweetify.error(request, title='Error!', icon='error', text='Failed to add this car, please try again', timer=4000) else: form = CarForm() template = 'cars/add-car.html' context = { 'form': form, } return render(request, template, context)
def registration(request): if request.method == "POST": fname = request.POST['firstname'] lname = request.POST['lastname'] email = request.POST['email'] pass1 = request.POST['password'] pass2 = request.POST['repassword'] if pass1 == pass2: if User.objects.filter(username=email).exists(): sweetify.error(request, "User Already exist", button='Ok', persistent=True) else: user = User.objects.create_user(username=email, first_name=fname, last_name=lname, email=email, password=pass1) user.save() return redirect('/auth/login') else: sweetify.error(request, 'Passwords are not same', button='Ok', persistent=True) return render(request, "registration.html", {'form': Register()})
def register(request): if request.method == 'POST': form = UserCreateForm(request.POST) if form.is_valid(): user = form.save(commit=False) username = request.POST['username'] email = request.POST['email'] password1 = request.POST['password1'] # send email verification now activation_key = helpers.generate_activation_key(username) subject = "Account Verification" # Split to one line to avoid header injection issues subject = ''.join(subject.splitlines()) # scheme = http/https, get_host = 127.0.0.1:8000 activate_url = "{0}://{1}/activate/account/?key={2}".format( request.scheme, request.get_host(), activation_key) message = render_to_string('ecoke/includes/acc_active_email.html', { 'user': user, 'activate_url': activate_url }) mail = EmailMultiAlternatives(subject, message, settings.EMAIL_HOST, [email]) mail.attach_alternative(message, "text/html") error = False try: mail.send() sweetify.success( request, 'Welcome', text= 'Account created! Click on the link sent to your email to activate the account', persistent='OK') # messages.add_message(request, messages.INFO, 'Account created! Click on the link sent to your email to activate the account') except: error = True sweetify.error( request, 'Oh! NO', text='Unable to send email verification. Please try again', persistent='OK') # messages.add_message(request, messages.INFO, 'Unable to send email verification. Please try again') if not error: user.username = username user.email = email user.password1 = password1 user.is_active = 0 user.save() user.profile.activation_key = activation_key user.save() return redirect(reverse('ecoke:login')) else: form = UserCreateForm() return render(request, 'ecoke/register.html', {'form': form})
def replymessages(request): if request.method == 'POST': email = request.POST['email'] subject = request.POST['subject'] message = request.POST['message'] email_from = settings.EMAIL_HOST_USER recipient_list = [ email, ] subject = subject body = message k = send_mail(subject=subject, message=body, from_email=email_from, recipient_list=recipient_list, auth_password=settings.EMAIL_HOST_PASSWORD) print(k) sweetify.success(request, 'Successfully sent', timer=3000) return redirect('VisitorsAdmin:messages') else: sweetify.error(request, title='Error' 'Error sending', button='ok', timer=5000) return redirect('VisitorsAdmin:messages')
def register(request): if request.user.is_authenticated(): return redirect(index) else: """A view that manages the registration form""" if request.method == 'POST': user_form = UserRegistrationForm(request.POST) if user_form.is_valid(): user_form.save() user = auth.authenticate(request.POST.get('email'), password=request.POST.get('password1')) if user: auth.login(request, user) messages.success(request, "You have successfully registered") return redirect(reverse('index')) else: messages.error(request, "unable to log you in at this time!") sweetify.error( request, 'Sorry, you couldn\'t be logged in at this time', timer=2000, toast=True) else: user_form = UserRegistrationForm() args = {'user_form': user_form} return render(request, 'register.html', args)
def update_password(request): """Updates password of the user using Django form.""" if request.method == 'POST': form = PasswordChangeForm(request.user, request.POST) if form.is_valid(): user = form.save() update_session_auth_hash(request, user) sweetify.success( request, "Password updated", icon='success', timer='3000', toast='true', position='bottom', background='#181818', ) return redirect('profile') else: sweetify.error( request, "Error, please correct", icon='success', timer='3000', toast='true', position='center', ) else: form = PasswordChangeForm(request.user) return render(request, 'password.html', {'form': form})
def edit_personal_secretaria(request, id): personal_secre = Personal_secretaria.objects.get(id=id) if request.method == 'POST': form = PersonalSecretariaForm(request.POST, request.FILES, instance=personal_secre) if form.is_valid(): save = form.save() sweetify.success(request, 'Se ha modificado los datos', timer=3000, icon='success') return HttpResponseRedirect( reverse('list', kwargs={'id': personal_secre.id})) else: sweetify.error(request, 'Ha ocurrido un error', persistent=':(', timer=3000, icon='error') print(str(form)) else: form = PersonalSecretariaForm(instance=personal_secre) return render(request, 'bookphone/editar_personal_secretaria.html', { 'personal': personal_secre, 'form': form, })
def reverse_submission(request, id): try: if 'admin/reverse_index_record' in request.path: school_instance = Indexing.objects.filter(institution_id=id, submitted=True) none_sch_instances = Indexing.objects.filter(institution_id=id, submitted=False) elif 'admin/reverse_exam_record/' in request.path: print(id) school_instance = ExamRegistration.objects.filter(institute_id=id, submitted=True) none_sch_instances = ExamRegistration.objects.filter( institute_id=id, submitted=False) if school_instance: school_instance.update(submitted=False, approved=False, declined=False) sweetify.success(request, 'Reversed Successfully', button='Great!') return HttpResponseRedirect(reverse('adminPortal:indexed_list')) elif none_sch_instances: sweetify.error(request, 'Record Hasn\'t been submitted', button='Great!') return HttpResponseRedirect(reverse('adminPortal:indexed_list')) except Indexing.DoesNotExist: sweetify.error(request, 'Record Not Found', button='Great!') return HttpResponseRedirect(reverse('adminPortal:indexed_list'))
def edit_unidad(request, id): unidad = Unidad.objects.get(id=id) if request.method == 'POST': form = UnidadForm(request.POST, request.FILES, instance=unidad) if form.is_valid(): save = form.save() sweetify.success(request, 'Se ha modificado una Unidad', timer=3000, icon='success') return HttpResponseRedirect( reverse('list', kwargs={'id': unidad.id})) else: sweetify.error(request, 'Ha ocurrido un error', persistent=':(', timer=3000, icon='error') print(str(form)) else: form = UnidadForm(instance=unidad) return render(request, 'bookphone/edit_unidad.html', { 'uni': unidad, 'form': form, })
def addposts(request): if request.method == 'POST': user = request.user blogger = Blogger.objects.filter(user_ptr_id=user.id).first() category = request.POST.get('category') category_list = request.POST.getlist('category[]') description = request.POST['description'] post_image = request.FILES.get('post_image') title = request.POST.get('title') # print(blogger,category, category_list,description,post_image,title) print(post_image) cat = Category.objects.filter(id=category).first() p = Post.objects.create(blogger=blogger, post_image=post_image, category=cat, description=description, title=title) if p and category_list: for cat in category_list: categ = Category.objects.filter(id=cat).first() PostTags.objects.create( category=categ, post=p, ) sweetify.success(request, 'Success', text='Post Added', persistent='Ok') else: sweetify.error(request, 'Error', text='Post not Deleted', persistent='Try Again') return redirect('BLOGBACK:posts')
def edit_secretaria(request, id): secretaria = Secretaria.objects.get(id=id) if request.method == 'POST': form = SecretariaForm(request.POST, request.FILES, instance=secretaria) if form.is_valid(): save = form.save() sweetify.success(request, 'Se ha modificado una Secretaria', timer=3000, icon='success') return HttpResponseRedirect( reverse('list', kwargs={'id': secretaria.id})) else: sweetify.error(request, 'Ha ocurrido un error', persistent=':(', timer=3000, icon='error') print(str(form)) else: form = SecretariaForm(instance=secretaria) return render(request, 'bookphone/edit_secretaria.html', { 'secre': secretaria, 'form': form, 'agency_obj': Secretaria })
def updatemainuserdetails(request): if request.method == 'POST': user = User.objects.filter(id=request.user.id).first() first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') username = request.POST.get('username') emailname = request.POST.get('email') if user: User.objects.filter(id=user.id).update(first_name=first_name, last_name=last_name, username=username, email=emailname) sweetify.success(request, 'Success', text='Updated', persistent='Ok') return redirect('BLOGBACK:userAccount') else: sweetify.error(request, 'Error', text='Error Updating User Account', persistent='Ok') return redirect('BLOGBACK:userAccount')
def user_profile(request): if request.method == "GET": # Form initial data initial = { 'nomor_peserta': request.user.username, 'nama_peserta': request.user.profiluser.nama_peserta, 'kecamatan': request.user.profiluser.kecamatan, 'desa': request.user.profiluser.desa, 'formasi': request.user.profiluser.formasi } context = {'form': FormProfil(initial=initial)} return render(request=request, template_name='profil.html', context=context) elif request.method == "POST": form = FormProfil(request.POST) if form.is_valid(): # Simpan data request.user.profiluser.nama_peserta = form.cleaned_data[ 'nama_peserta'] request.user.profiluser.kecamatan = form.cleaned_data['kecamatan'] request.user.profiluser.desa = form.cleaned_data['desa'] request.user.profiluser.formasi = form.cleaned_data['formasi'] request.user.profiluser.save() sweetify.success(request, 'Data profil berhasil disimpan') return HttpResponseRedirect(reverse('user_profile')) else: sweetify.error(request, 'Harap lengkapi borang yang ada') return HttpResponseRedirect(reverse('user_profile')) else: sweetify.error(request, 'Metode request tidak valid') return HttpResponseRedirect(reverse('user_profile'))
def sendemail(request): if request.method == 'POST': subject = request.POST.get('subject') message = request.POST.get('message') subscribers = request.POST.getlist('subscribers[]') print(subject, message, subscribers) if subject and message and subscribers: from django.core.mail import send_mail try: send_mail(subject, message, settings.EMAIL_HOST_USER, subscribers) sweetify.success(request, 'Success', text='Mails Sent', persistent='Ok') except Exception as ec: print(ec) sweetify.error(request, 'Error', text='Mails Not Sent', persistent='Ok') else: sweetify.error(request, 'Error', text='Mails Not Sent', persistent='Ok') return redirect(request.META['HTTP_REFERER'])
def materia(request, id_materia): estudante = estudante_auth.get(request) if estudante is not None: materias = Materia.objects.order_by('nome').all() if id_materia is not 0: mentores = Mentor.objects.order_by('nome').filter( materia=id_materia, aprovado=True) else: mentores = Mentor.objects.order_by('nome').filter(aprovado=True) contexto = { "materias": materias, "materia_atual": id_materia, "mentores": mentores, "estudante": estudante } return render(request, 'estudante_materia.html', contexto) else: sweetify.error( request, 'Acesso restrito!', text='Você precisa estar autenticado para acessar esta página.', button='Ok', timer=3000) return redirect('app_auth_login')
def registration(request): """Return the registration.html file""" if request.user.is_authenticated: return redirect(reverse('index')) if request.method == "POST": registration_form = UserRegistrationForm(request.POST) if registration_form.is_valid(): registration_form.save() user = auth.authenticate(username=request.POST['username'], password=request.POST['password1']) if user: auth.login(user=user, request=request) sweetify.success(request, "You have successfully registered!", icon="success") return redirect(reverse('index')) else: sweetify.error(request, """We're truly sorry. We are unable to register your account at this time.""", icon="error") else: registration_form = UserRegistrationForm() return render(request, 'registration.html', {"registration_form": registration_form})
def contato(request, id_mentor, id_materia): estudante = estudante_auth.get(request) if estudante is not None: try: mentor = Mentor.objects.get(pk=id_mentor) solicitacao = Solicitacao.objects.filter( mentor=mentor, estudante=estudante).get_or_create(mentor=mentor, estudante=estudante, oculto=False) sweetify.success( request, 'Tudo certo!', html= '<p>Solicitação de contato enviada para o mentor!</p><p>Favor aguardar que o mentor entrará em contato.</p>', button='Ok', timer=5000) except Mentor.DoesNotExist: pass return redirect('app_estudante_materia', id_materia) else: sweetify.error( request, 'Acesso restrito!', text='Você precisa estar autenticado para acessar esta página.', button='Ok', timer=3000) return redirect('app_auth_login')
def ticket_detail(request, t_id): ''' Get ticket information and comments relating to a specific ID ''' try: ticket = Ticket.objects.get(id=t_id) except Ticket.DoesNotExist: sweetify.error( request, 'No ticket found for id {}'.format(t_id), icon='error', timer='5000', button='Ok', toast='true', position='top-end', ) return redirect('dashboard') user_profile = MyUser.objects.get(user_id=request.user.id) if user_profile.role == 'USR': related_comments = Comment.objects.filter(related_ticket=t_id).exclude( is_internal_comment=True) else: related_comments = Comment.objects.filter(related_ticket=t_id) return render(request, 'ticket.html', { 'ticket': ticket, 'relatedcomments': related_comments })
def create_a_product(request): if request.method == "POST": form = ProductCreationForm(request.POST, request.FILES) if form.is_valid(): form.save() sweetify.success(request, "Thank you {}, BootShop has been updated." .format(request.user)) return redirect('profile') else: form = ProductCreationForm() sweetify.error(request, '{} sorry, your product cannot be added.' .format(request.user)) else: form = ProductCreationForm() context = { 'form': form, } return render(request, 'create_product.html', context)