Best Python code snippet using slash
views.py
Source:views.py
1from __future__ import print_function2from django.contrib.auth.models import User3from apiclient.discovery import build4from httplib2 import Http5import httplib26import os7from oauth2client import file8import json9from apiclient import discovery10import oauth2client11from oauth2client import client12from oauth2client import tools13import datetime14try:15 import argparse16 flags = tools.argparser.parse_args([])17except ImportError:18 flags = None19from django.shortcuts import render, redirect 20from django.views.decorators.http import require_POST21from django.views.generic.list import ListView22from django.views.generic.detail import DetailView23from django.views.generic.edit import CreateView, UpdateView, DeleteView, FormView24from django.urls import reverse_lazy25from django.contrib.auth.views import LoginView26from django.contrib.auth.mixins import LoginRequiredMixin27from django.contrib.auth.forms import UserCreationForm28from django.contrib.auth import login29from django.contrib.auth.decorators import login_required30from .models import Task, Grocery, Bill, Meal, Event31from .forms import TaskForm, MealForm, BillForm, GroceryForm, EventForm32from django.contrib import messages33from django.core import serializers34import bcrypt35class CustomLoginView(LoginView):36 template_name= 'ToDo_App/login.html'37 fields= '__all__'38 redirect_authenticated_user= True39 40 def get_success_url(self):41 return reverse_lazy('tasks')42class RegisterPage(FormView):43 template_name= 'ToDo_App/register.html'44 form_class= UserCreationForm45 redirect_authenticated_user= True46 success_url= reverse_lazy('tasks')47 def form_valid(self, form):48 user= form.save()49 if user is not None:50 login(self.request, user)51 return super(RegisterPage, self).form_valid(form)52 def get(self, *args, **kwargs):53 if self.request.user.is_authenticated:54 return redirect('tasks')55 return super(RegisterPage, self).get(*args, **kwargs)56@login_required57def tasks(request):58 tasks= Task.objects.filter(user=request.user)59 counts = Task.objects.filter(user=request.user, complete=False)60 form= TaskForm()61 context = {'tasks':tasks, 'form': form, 'counts': counts}62 return render(request, 'ToDo_App/task_list.html', context)63class TaskDetail(LoginRequiredMixin, DetailView):64 model= Task65 context_object_name= 'task'66 template_name= 'ToDo_App/task.html'67@login_required68@require_POST69def taskCreate(request):70 if request.method == "POST":71 form= TaskForm(request.POST)72 if form.is_valid():73 new_task= Task(user=request.user, title=request.POST['title'])74 new_task.save()75 return redirect('/')76class TaskUpdate(LoginRequiredMixin, UpdateView):77 model= Task78 fields= ['title', 'description', 'complete', 'category', 'due_date']79 success_url= reverse_lazy('tasks')80class TaskDelete(LoginRequiredMixin, DeleteView):81 model= Task82 context_object_name= 'task'83 success_url= reverse_lazy('tasks') 84@login_required85def groceries(request):86 groceries= Grocery.objects.filter(user=request.user)87 counts = Grocery.objects.filter(user=request.user, complete=False)88 form= GroceryForm()89 context = {'groceries':groceries, 'form': form, 'counts': counts}90 return render(request, 'ToDo_App/grocery_list.html', context)91@login_required92@require_POST93def groceryCreate(request):94 form= GroceryForm(request.POST)95 if form.is_valid():96 new_task= Grocery(user=request.user, item=request.POST['item'])97 new_task.save()98 return redirect('/groceries')99class GroceryList(LoginRequiredMixin, ListView):100 model = Grocery101 context_object_name= 'groceries'102 def get_context_data(self, **kwargs):103 context = super().get_context_data(**kwargs)104 context['groceries']= context['groceries'].filter(user=self.request.user)105 context['count']= context['groceries'].filter(complete=False).count()106 107 search_input = self.request.GET.get('search-area') or ''108 if search_input: 109 context['groceries'] = context['groceries'].filter(item__startswith=search_input)110 context['search_input'] = search_input111 return context112class GroceryUpdate(LoginRequiredMixin, UpdateView):113 model= Grocery114 fields= ['item', 'category', 'complete']115 success_url= reverse_lazy('groceries')116class GroceryDelete(LoginRequiredMixin, DeleteView):117 model= Grocery118 context_object_name= 'groceries'119 success_url= reverse_lazy('groceries')120@login_required121def grocery_complete(request, id):122 mark_complete = Grocery.objects.get(id=id)123 mark_complete.complete=True;124 mark_complete.save()125 return redirect('/groceries')126@login_required127def grocery_incomplete(request, id):128 mark_complete = Grocery.objects.get(id=id)129 mark_complete.complete=False;130 mark_complete.save()131 return redirect('/groceries')132@login_required133def delete_grocery(request, id):134 delete_grocery = Grocery.objects.get(id=id)135 delete_grocery.delete()136 return redirect('/groceries')137@login_required138def task_complete(request, id):139 mark_complete = Task.objects.get(id=id)140 mark_complete.complete=True;141 mark_complete.save()142 return redirect('/')143@login_required144def task_incomplete(request, id):145 mark_complete = Task.objects.get(id=id)146 mark_complete.complete=False;147 mark_complete.save()148 return redirect('/')149@login_required150def delete_task(request, id):151 delete_task = Task.objects.get(id=id)152 delete_task.delete()153 return redirect('/')154@login_required155def bills(request):156 bills= Bill.objects.filter(user=request.user)157 counts = Bill.objects.filter(user=request.user, paid=False)158 form= BillForm()159 context = {'bills':bills, 'form': form, 'counts': counts}160 return render(request, 'ToDo_App/bill_list.html', context)161# @login_required162# @require_POST163# def billCreate(request):164# form= BillForm(request.POST)165# if form.is_valid():166# new_bill= Bill(user=request.user, bill=request.POST['bill'], due_date=request.POST['due_date'])167# new_bill.save()168# return redirect('/bills')169class BillList(LoginRequiredMixin, ListView):170 model = Bill171 context_object_name= 'bills'172 def get_context_data(self, **kwargs):173 context = super().get_context_data(**kwargs)174 context['bills']= context['bills'].filter(user=self.request.user)175 context['count']= context['bills'].filter(paid=False).count()176 177 search_input = self.request.GET.get('search-area') or ''178 if search_input: 179 context['bills'] = context['bills'].filter(bill__startswith=search_input)180 context['search_input'] = search_input181 return context182class BillUpdate(LoginRequiredMixin, UpdateView):183 model= Bill184 fields= ['bill', 'category', 'due_date', 'paid']185 success_url= reverse_lazy('bills')186class BillDelete(LoginRequiredMixin, DeleteView):187 model= Bill188 context_object_name= 'bills'189 success_url= reverse_lazy('bills')190@login_required191def bill_paid(request, id):192 mark_paid = Bill.objects.get(id=id)193 mark_paid.paid=True;194 mark_paid.save()195 return redirect('/bills')196@login_required197def bill_notpaid(request, id):198 mark_notpaid = Bill.objects.get(id=id)199 mark_notpaid.paid=False;200 mark_notpaid.save()201 return redirect('/bills')202@login_required203def delete_bill(request, id):204 delete_bill = Bill.objects.get(id=id)205 delete_bill.delete()206 return redirect('/bills')207@login_required208def meals(request):209 meals= Meal.objects.filter(user=request.user)210 counts = Meal.objects.filter(user=request.user, complete=False)211 sunday = Meal.objects.all().filter(user=request.user, day="sunday")212 monday = Meal.objects.all().filter(user=request.user, day="monday")213 tuesday = Meal.objects.all().filter(user=request.user, day="tuesday")214 wednesday = Meal.objects.all().filter(user=request.user, day="wednesday")215 thursday = Meal.objects.all().filter(user=request.user, day="thursday")216 friday = Meal.objects.all().filter(user=request.user, day="friday")217 saturday = Meal.objects.all().filter(user=request.user, day="saturday")218 form= MealForm()219 context = {'meals':meals, 'form': form, 'counts': counts, 'sunday': sunday, 'monday': monday, 'tuesday': tuesday, 'wednesday': wednesday, 'thursday': thursday, 'friday': friday, 'saturday': saturday}220 return render(request, 'ToDo_App/meal_list.html', context)221@login_required222@require_POST223def mealCreate(request):224 form= MealForm(request.POST)225 if form.is_valid():226 new_task= Meal(user=request.user, meal=request.POST['meal'], day=request.POST['day'])227 new_task.save()228 return redirect('/meals')229class MealList(LoginRequiredMixin, ListView):230 model = Meal231 context_object_name= 'meals'232 def get_context_data(self, **kwargs):233 context = super().get_context_data(**kwargs)234 context['meals']= context['meals'].filter(user=self.request.user)235 context['count']= context['meals'].filter(complete=False).count()236 return context237class MealUpdate(LoginRequiredMixin, UpdateView):238 model= Meal239 fields= ['meal', 'day', 'complete']240 success_url= reverse_lazy('meals')241class MealDelete(LoginRequiredMixin, DeleteView):242 model= Meal243 context_object_name= 'meals'244 success_url= reverse_lazy('meals')245@login_required246def delete_meal(request, id):247 delete_meal = Meal.objects.get(id=id)248 delete_meal.delete()249 return redirect('/meals')250@login_required251def meal_complete(request, id):252 mark_complete = Meal.objects.get(id=id)253 mark_complete.complete=True;254 mark_complete.save()255 return redirect('/meals')256@login_required257def meal_incomplete(request, id):258 mark_incomplete = Meal.objects.get(id=id)259 mark_incomplete.complete=False;260 mark_incomplete.save()261 return redirect('/meals')262@login_required263def event_list(request):264 return render(request, 'ToDo_App/event_list.html')265# If modifying these scopes, delete your previously saved credentials266# at ~/.credentials/calendar-python-quickstart.json267SCOPES = 'https://www.googleapis.com/auth/calendar'268CLIENT_SECRET_FILE = 'credentials.json'269APPLICATION_NAME = 'Google Calendar API Python Quickstart'270def get_credentials():271 """Gets valid user credentials from storage.272 If nothing has been stored, or if the stored credentials are invalid,273 the OAuth2 flow is completed to obtain the new credentials.274 Returns:275 Credentials, the obtained credential.276 """277 home_dir = os.path.expanduser('~')278 credential_dir = os.path.join(home_dir, '.credentials')279 if not os.path.exists(credential_dir):280 os.makedirs(credential_dir)281 credential_path = os.path.join(credential_dir,'credentials.json')282 store = oauth2client.file.Storage(credential_path)283 credentials = store.get()284 if not credentials or credentials.invalid:285 flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)286 flow.user_agent = APPLICATION_NAME287 if flags:288 credentials = tools.run_flow(flow, store, flags)289 else: # Needed only for compatibility with Python 2.6290 credentials = tools.run(flow, store)291 print('Storing credentials to ' + credential_path)292 return credentials293def create_event(request):294 SCOPES = 'https://www.googleapis.com/auth/calendar'295 store = file.Storage('storage.json')296 creds = store.get()297 if not creds or creds.invalid:298 flow = client.flow_from_clientsecrets('credentials.json', SCOPES)299 creds = tools.run_flow(flow, store, flags) \300 if flags else tools.fun(flow,store)301 credentials = get_credentials()302 http = credentials.authorize(httplib2.Http())303 service = discovery.build('calendar', 'v3', http=http)304 event = {305 'summary': request.POST['summary'],306 'location': request.POST['location'],307 'description': request.POST['description'],308 'start': {309 'date': request.POST['start_date'],310 },311 'end': {312 'date': request.POST['end_date'],313 },314 }315 # json_event = json.dumps(event)316 event = service.events().insert(calendarId='bb3c6jev76jlkm8n43b1knkhco@group.calendar.google.com', body=event).execute()317 form= EventForm(request.POST)318 if form.is_valid():319 new_event= Event(summary=request.POST['summary'], location=request.POST['location'], description=request.POST['description'], start=request.POST['start_date'], end=request.POST['end_date'])320 new_event.save()321 return redirect('/ToDo_App/event-list')322@login_required323@require_POST324def billCreate(request):325 SCOPES = 'https://www.googleapis.com/auth/calendar'326 store = file.Storage('storage.json')327 creds = store.get()328 if not creds or creds.invalid:329 flow = client.flow_from_clientsecrets('credentials.json', SCOPES)330 creds = tools.run_flow(flow, store, flags) \331 if flags else tools.fun(flow,store)332 credentials = get_credentials()333 http = credentials.authorize(httplib2.Http())334 service = discovery.build('calendar', 'v3', http=http)335 event = {336 'summary': request.POST['bill'] + " Bill Due",337 'start': {338 'date': request.POST['due_date'],339 },340 'end': {341 'date': request.POST['due_date'],342 },343 }344 # json_event = json.dumps(event)345 event = service.events().insert(calendarId='bb3c6jev76jlkm8n43b1knkhco@group.calendar.google.com', body=event).execute()346 form= BillForm(request.POST)347 if form.is_valid():348 new_bill= Bill(user=request.user, bill=request.POST['bill'], due_date=request.POST['due_date'])349 new_bill.save()350 return redirect('/bills')351class EventCreate(LoginRequiredMixin, CreateView):352 model= Event353 fields = ['summary', 'location', 'description', 'start_date', 'end_date']354 success_url= reverse_lazy('/ToDo_App/event-list')355 def form_valid(self, form):356 form.instance.user = self.request.user...
urls.py
Source:urls.py
1from django.urls import path2from .views import delete_task, edit_task, home, login_view, logout_view, mark_complete, mark_incomplete,change_password, signup, add_task3urlpatterns = [4 path('home', home, name='home'),5 path('delete/<int:todo_id>', delete_task, name='delete'),6 path('mark_complete/<int:todo_id>', mark_complete, name="mark_complete"),7 path('mark_incomplete/<int:todo_id>', mark_incomplete, name="mark_incomplete"),8 path('edit/<int:todo_id>', edit_task, name="edit"),9 path('', login_view, name="login" ),10 path('logout', logout_view, name="logout"),11 path('password', change_password, name='change_password'),12 path('signup', signup, name='signup'),13 path('add_task', add_task, name='add_task'),14 ...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!