def edit_hardware(request, uuid=None): title = 'Edit Hardware' if uuid: thisObj = get_object_or_404(hardware, hwID=uuid) if request.POST: if request.POST.get("_cancel"): return redirect(reverse('hardware_list')) else: form = hardwareForm(request.POST, instance=thisObj) if form.is_valid(): form.save() if request.POST.get("_stay"): context = {"title": title, "form": form} return render(request, "hardware/hardware.html", context) else: return redirect(reverse('hardware_list')) else: context = {"title": title, "form": form} return render(request, "hardware/hardware.html", context) else: form = hardwareForm(instance=thisObj) context = {"title": title, "form": form} return render(request, "hardware/hardware.html", context)
def post(self, request, *args, **kwargs): diccionario= {} fase_actual= Fase.objects.get(id=request.POST['fase']) usuario_logueado= Usuario.objects.get(id= request.POST['login']) proyecto_actual= Proyecto.objects.get(id= request.POST['proyecto']) diccionario['logueado']= usuario_logueado diccionario['fase']= fase_actual diccionario['proyecto']= proyecto_actual new_nombre= request.POST['nombre_linea_base'] existe= LineaBase.objects.filter(nombre= new_nombre, fase=fase_actual, activo= True) if existe: diccionario['error']= 'Nombre de Linea base ya existe' diccionario['lista_de_items']= (Item.objects.filter(fase= fase_actual, activo=True, estado='A')).order_by('nombre') return render(request, super(CrearLineaBaseConfirm, self).template_name, diccionario) else: items_en_linea_base=request.POST.getlist('items_en_linea_base[]') #comprobar si sus padres estan en LB for item_hijo in items_en_linea_base: relacion_padre_de_item_hijo=Relacion.objects.filter(item2=item_hijo, tipo='P/H', activo=True) if len(relacion_padre_de_item_hijo) and (not relacion_padre_de_item_hijo[0].item1.estado =='B' and not relacion_padre_de_item_hijo[0].item1.estado =='R'): diccionario['error']= 'Padre/s de item/s debe/n de estar en Linea Base.' diccionario['lista_de_items']= Item.objects.filter(fase= fase_actual, activo=True, estado='A') return render(request, super(CrearLineaBaseConfirm, self).template_name, diccionario) nueva_lienea_base=LineaBase() nueva_lienea_base.nombre= new_nombre nueva_lienea_base.fase=fase_actual nueva_lienea_base.estado='C' nueva_lienea_base.save() for item in items_en_linea_base: item_actual= Item.objects.get(id=item) item_actual.lineaBase=nueva_lienea_base item_actual.estado='B' item_actual.save() return render(request, self.template_name, diccionario)
def login_user(request): state = "Por favor ingrese a continuacion" username = password = '' if request.POST: username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) state = "Conectado con exito" usuario = User.objects.get(username=username) fotourl = usuario.estudiante.foto.url cedula = usuario.estudiante.cedula telefono = usuario.estudiante.telefono fecha = datetime.datetime.today() programa = usuario.estudiante.programa.nombre_del_programa duracion = usuario.estudiante.fecha_de_expiracion startdate = datetime.date.today() enddate = startdate + datetime.timedelta(days=6) talleres = Taller.objects.filter(fecha__range=[startdate, enddate]) # .filter(hora_inicio__gt=time.strftime("%H:%M:%S")) return render(request,'contenido.html',{'username':username,'fecha':fecha,'fotourl':fotourl,'cedula':cedula,'telefono':telefono,'programa':programa,'duracion':duracion,'talleres':talleres}) else: state = "Tu cuenta esta desactivada por favor acercarce a oficinas." else: state = "Usuario o contrasena incorrecta" return render(request,'signin.html',{'state':state}, context_instance=RequestContext(request))
def new_contact(request): title = 'New Contact' form = contactForm(request.POST or None) if request.POST: if request.POST.get("_cancel"): return redirect(reverse('contact_list')) else: form = contactForm(request.POST) if form.is_valid(): form.save() obj = form.instance if request.POST.get("_stay"): return redirect(reverse('contact_edit', kwargs={'uuid': obj.pk} )) else: return redirect(reverse('contact_list')) else: context = {"title": title, "form": form} return render(request, "contact/contact.html", context) context = { "title": title, "form": form } return render(request, "contact/contact.html", context)
def addRecord(request, patient): if request.method == 'POST': form = AddRecordForm(request.POST) if form.is_valid(): patient_instance = Patient.objects.get(pk=patient) record = Record.objects.create( date_created=datetime.datetime.now(), patient=patient_instance, doctor=request.user, health_condition=HealthCondition.objects.get(pk = request.POST.get("health_condition", "")), notes = form.cleaned_data['notes'], resolved = form.cleaned_data['resolved'] ) return HttpResponseRedirect('/records/' + str(record.pk) ) else: return render(request, 'records/add_record_form.html', { 'form': form,}) data = {'patient': Patient.objects.get(pk=patient), 'doctor': request.user, 'date_created': datetime.datetime.now(), 'resolved': False} form = AddRecordForm(initial=data) return render(request, 'records/add_record_form.html', { 'form': form, 'patient': Patient.objects.get(pk=patient) })
def signup(request): if request.method == 'GET': return render(request, 'sign-up.html', {'form': SignupForm()}) # elif request.method == 'POST' form = SignupForm(request.POST) if form.is_valid(): user = User.objects.create_user(username=form.cleaned_data['username'], password=form.cleaned_data['password']) p = Person() p.user = user user.save() p.save() s = Studentity() s.person = p s.student_id = form.cleaned_data['student_id'] s.department = Department.objects.get(name='unknown') s.save() return HttpResponseRedirect(reverse('registration_select_initial_tags', args=[user.username, p.id])) else: return render(request, 'sign-up.html', {'form': form, 'status': 'Notice errors below:'})
def add_payment_method(request: HttpRequest) -> HttpResponse: user = request.user ctx = { "publishable_key": STRIPE_PUBLISHABLE_KEY, "email": user.email, } # type: Dict[str, Any] if not user.is_realm_admin: ctx["error_message"] = ( _("You should be an administrator of the organization %s to view this page.") % (user.realm.name,)) return render(request, 'zilencer/billing.html', context=ctx) try: if request.method == "GET": ctx["num_cards"] = count_stripe_cards(user.realm) return render(request, 'zilencer/billing.html', context=ctx) if request.method == "POST": token = request.POST.get("stripeToken", "") ctx["num_cards"] = save_stripe_token(user, token) ctx["payment_method_added"] = True return render(request, 'zilencer/billing.html', context=ctx) except StripeError as e: ctx["error_message"] = e.msg return render(request, 'zilencer/billing.html', context=ctx)
def register(request): if request.method == 'POST': form = UserForm(data=request.POST) form2 = UserProfileForm(data=request.POST) if form.is_valid() and form2.is_valid() : user = form.save() user.set_password(user.password) user.save() userprofile=form2.save(commit=False) userprofile.user = user if 'picture' in request.FILES: profile.picture = request.FILES['picture'] userprofile.save() return render(request, 'accounts/login.html', {'registered':True} ) else: # print (user_form.errors, profile_form.errors) return render(request, 'accounts/register.html', {'form':form}) else: form = UserForm() form2 = UserProfileForm() return render(request, 'accounts/register.html', {'form': form })
def post(self, request, *args, **kwargs): template_name = "boozinvite.html" http_method_names = ['get', 'post'] userTemp = self.request.user models = boozProfiles form = forms.boozProfilesForm(request.POST) if form.is_valid(): # The form is valid and can be saved to the database # by calling the 'save()' method of the ModelForm instance. print form.cleaned_data['datetime'] print form.cleaned_data latitude = form.cleaned_data['Booz_shop_location'][0] longitude = form.cleaned_data['Booz_shop_location'][1] print latitude,longitude address = getAddress(latitude,longitude) print "User name is ::", userTemp tempAddress = form.save(commit=False) tempAddress.boozshopaddress = address tempAddress.user = userTemp tempAddress.save() # Render the success page. return render(request, "boozinvite.html") # This means that the request is a GET request. So we need to # create an instance of the TShirtRegistrationForm class and render it in # the template else: form = forms.boozProfilesForm(request.POST) return render(request, "boozinvite.html", { 'form' : form })
def view_zone_records(request, dns_server, zone_name): """Display the list of records for a particular zone.""" zone_array = {} this_server = get_object_or_404(models.BindServer, hostname=dns_server) try: zone_array = this_server.list_zone_records(zone_name) except exceptions.TransferException as exc: messages.error(request, "TransferException: %s." % exc) return render(request, "bcommon/list_zone.html", {"zone_name": zone_name, "dns_server": this_server}) except exceptions.KeyringException: messages.error(request, "Unable to get zone list. A problem was encountered " "decrypting your TSIG key. Ensure the key is correctly " "specified in the Binder Database.") return render(request, "bcommon/list_zone.html", { "dns_server": this_server, "zone_name" :zone_name }) except dns.query.TransferError as err: messages.error(request, "TransferError: %s." % err) return render(request, "bcommon/list_zone.html", {"zone_name": zone_name, "dns_server": this_server}) return render(request, "bcommon/list_zone.html", {"zone_array": zone_array, "dns_server": this_server, "zone_name": zone_name, # NOTE: A hack because NSD doesn't support dynamic updates # so merely display the zone. "dynamic_dns_available": this_server.server_type in ['BIND']})
def home(request): articles = Article.objects.all() if len(articles) > 0: return render(request, 'publisher/home.html', {'articles':articles, 'no_content':False}) else: return render(request, 'publisher/home.html', {'no_content':True})
def favorite_add(request): objs = Stock.objects.all() if request.POST: search_word=request.POST['stock_code'] if search_word: if len(search_word)>6: stock_code = search_word[:6] user_error = stock_error = False user = request.user if user: user_error = False else: user_error = True stock = Stock.objects.filter(stock_code=stock_code) if stock is None: stock_error = True if user_error or stock_error: return render(request,'stock/favorite_add.html') else: favorite, created = Favorite.objects.get_or_create(stock_user=user, stock_code=stock[0]) return HttpResponseRedirect('/stock/favorite') else: return render(request,'stock/favorite_add.html',{'stocks' : objs})
def index(request, page=1): page = int(page) posts_per_page = 5 all_posts = Post.objects.all().order_by('-pub_at') categories = Category.objects.all().order_by('name') if not all_posts: return render(request, 'index.html', { 'categories': categories, 'page_is_first': True, 'page_is_last': True, 'page': page }) posts_on_page = all_posts[(page - 1) * posts_per_page:page * posts_per_page] try: page_is_last = is_page_last(posts_on_page, all_posts) page_is_first = is_page_first(posts_on_page, all_posts) except IndexError: raise Http404() return render(request, 'index.html', { 'posts': posts_on_page, 'categories': categories, 'page_is_first': page_is_first, 'page_is_last': page_is_last, 'page': page })
def like_post(request, id): context = {} context = pirvate_view_post(request, id) template_current_status = set_template_current_status(request) context['template_current_status'] = template_current_status try: post = Design_Request.objects.get(id=id) users = post.liked.all() if request.method == 'GET': if request.user in users: context['liked'] = 1 else: context['liked'] = 0 return render(request, 'CoDEX/post.html', context) if request.user not in users: post.liked.add(request.user) context['liked'] = 1 else: context['liked'] = 1 except ObjectDoesNotExist: raise Http404 return render(request, 'CoDEX/post.html', context)
def answer(request): ans = "" if request.method == 'POST': ans = request.POST.get('ans') player = models.player.objects.get(user_id=request.user.pk) try: level = models.level.objects.get(l_number=player.max_level) except: return render(request, 'finish.html', {'player': player}) # print answer # print level.answer if ans == level.answer: #print level.answer player.max_level = player.max_level + 1 player.score = player.score + 10 player.timestamp = datetime.datetime.now() level.numuser = level.numuser + 1 level.save() #print level.numuser # print player.max_level global m_level global f_user # print f_user # print m_level if m_level < player.max_level: m_level = player.max_level f_user = player.name player.save() try: level = models.level.objects.get(l_number=player.max_level) return render(request, 'level.html', {'player': player, 'level': level}) except: return render(request, 'finish.html', {'player': player}) messages.error(request, "Wrong Answer!, Try Again") return render(request, 'level.html', {'player': player, 'level': level})
def dashboard(request): if request.user.is_authenticated(): try: me = UserProfile.objects.get(user=request.user) except UserProfile.DoesNotExist: display_name = request.user return redirect('/register/') neos = Neo.objects.all().extra( select={ 'display_name': 'SELECT display_name FROM neo_userprofile WHERE neo_userprofile.id = neo_neo.user_id' }, ) paginator = Paginator(neos, 50) # Make sure page request is an int. If not, deliver first page. try: page = int(request.GET.get('page', '1')) except ValueError: page = 1 # If page request (9999) is out of range, deliver last page of results. try: neo_list = paginator.page(page) except (EmptyPage, InvalidPage): neo_list = paginator.page(paginator.num_pages) if request.user.is_authenticated(): return render(request, 'dashboard.html', {'neo_list': neo_list, 'page': page, 'me': me}) return render(request, 'dashboard.html', {'neo_list': neo_list, 'page': page})
def neo_view(request, no): neo = get_object_or_404(Neo, no=no) f = None if request.user.is_authenticated(): try: f = Feedback.objects.get(user=request.user, neo=neo) except Feedback.DoesNotExist: pass if request.method == 'POST' and request.user.is_authenticated(): form = FeedbackForm(request.POST) if form.is_valid(): vote = form.cleaned_data['vote'] if f: f.vote = vote f.save() else: f = Feedback(user=request.user, vote=vote, neo=neo) f.save() else: form = FeedbackForm() if request.user.is_authenticated(): me = UserProfile.objects.get(user=request.user) return render(request, 'neo_view.html', {'neo': neo, 'feedback': form, 'me': me}) return render(request, 'neo_view.html', {'neo': neo, 'feedback': form})
def my_timetable(request): if 'user' not in request.session.keys(): return render(request,'index.html',{'msg':False}) days={1:'Monday',2:'Tuesday',3:'Wednesday',4:'Thursday',5:'Friday',6:'Saturday',7:'Sunday'} slots={1:'8:00-9:00',2:'9:00-10:00',3:'10:00-11:00',4:'11:00-12:00',5:'12:00-1:00',6:'1:00-2:00',7:'2:00-3:00',8:'3:00-4:00',9:'4:00-5:00',10:'5:00-6:00',11:'6:00-7:00',12:'7:00-8:00',13:'8:00-9:00',14:'9:00-10:00',15:'10:00-11:00',16:'11:00-12:00'} usernm=request.session['user'] user=Professor.objects.get(Username=usernm) t1=tt1.objects.exclude(Course=None) t2=tt2.objects.exclude(Course=None) t3=tt3.objects.exclude(Course=None) t4=tt4.objects.exclude(Course=None) all_t=[] for c in t1: all_t.append(c) for c in t2: all_t.append(c) for c in t3: all_t.append(c) for c in t4: all_t.append(c) all_tt=[] for a in all_t: prof=a.Course.Teaching.all()[0] if prof.Username == usernm: all_tt.append(a) delDateObj(request) return render(request, 'timetable.html',{'user':user, 'days':days,'slots':slots,'table':all_tt})
def userlogin(request): if request.user.is_authenticated(): return redirect('IndexViewWeb') else: if request.method == "POST": if 'login_form' in request.POST: login_form = userLoginForm(request.POST) if login_form.is_valid(): user = authenticate(username=login_form.cleaned_data[ 'username'], password=login_form.cleaned_data['password']) if user is not None: if user.is_active: try: login(request, user) return redirect('indexDashboard') except: errors = ''' <div class="card-panel teal lighten-2">User Activo</div> ''' return render(request, 'login.html', {'login_form': login_form, 'errors': errors}) else: errors = ''' <div class="card-panel red lighten-2"><span class="white-text">Usuario y/o contraseña incorrecta.</span></div> ''' return render(request, 'login.html', {'login_form': login_form, 'errors': errors}) else: raise Exception('Error Login : Form incomplete') else: errors = '' login_form = userLoginForm() return render(request, 'login.html', {'login_form': login_form, 'errors': errors})
def passet(request): """ Set credentials for new users registered with social auth. """ ctx = { 'title': _("Set your password"), } if request.method == 'POST': f = SocialAuthPassetForm(request.POST) if f.is_valid(): user = User(request.user.id) user.username = f.cleaned_data['username'] user.set_password(f.cleaned_data['password']) # Re-fetch user object from DB user = User.objects.get(pk=request.user.id) # Create user profile if not exists try: prof = UserProfile.objects.get(user=request.user.id) except: prof = UserProfile() prof.user = user prof.save() return redirect('user:index') ctx['form'] = SocialAuthPassetForm(request.POST) return render(request, 'userspace/pass.html', ctx) ctx['form'] = SocialAuthPassetForm() return render(request, 'userspace/pass.html', ctx)
def process(request, server_id, process_name): try: server = Server.objects.get(id=server_id) process = server.process_set.get(name=process_name) return render(request, 'monitcollector/process.html',{'enable_buttons': enable_buttons, 'process_found': True, 'server': server, 'process': process, 'monit_update_period': monit_update_period}) except ObjectDoesNotExist: return render(request, 'monitcollector/process.html',{'process_found': False})
def teacher_register(request): if request.method == 'POST': post_req_data = request.POST data = {} register_form = TeacherRegistrationForm(data=post_req_data) teacher_model = TeacherModel(data=post_req_data) if register_form.is_valid(): try: teacher_model = TeacherModel(data=post_req_data) if teacher_model.is_valid(): address_model = AddressModel(data=post_req_data) if address_model.is_valid(): try: city = City.objects.get(city_name=post_req_data.get('city', '')) address = address_model.save(commit=False) address.city_obj = city address.street1 = post_req_data.get('street1', '') address.street2 = post_req_data.get('street2', '') address.pincode = post_req_data.get('pincode', '') address.save() except Exception as e: print e.args try: import uuid teacher = teacher_model.save(commit=False) teacher.address = address teacher.uuid_key = uuid.uuid4() teacher_pass = post_req_data.get('password') teacher.set_password(teacher_pass) teacher.gender = post_req_data.get('gender',None) p_date = post_req_data.get('d_o_b',None) if p_date: import datetime d_o_b = datetime.datetime.strptime(p_date, '%m/%d/%Y').date() teacher.d_o_b = d_o_b else: pass teacher.higher_education = post_req_data.get('higher_education',None) teacher.is_active = False teacher.save() kawrgs = {'teacher_pass' : teacher_pass,'teacher_uname' : teacher.username} messages.success(request,'Teacher created. Please ask the server administrator to activate your account.') return HttpResponseRedirect('/teacher/login/') except Exception as e: print e.args else: data = {'form': address_model,'register_error':True} else: data = {'form': teacher_model,'register_error':True} except Exception as e: print e.args else: data = {'form': register_form,'register_error':True} return render(request, 'teacher/register_teacher.html', data) else: teacher_form = TeacherModel() return render(request, 'teacher/register_teacher.html', {'form':teacher_form})
def results(req): text = req.session.get('text', '') url_lst = req.session.get('url_lst', []) method = req.session.get('method') pic_lst = req.session.get('pic_lst') if method == '1': top_pics = (pic_lst[8*i:8*(i+1)] for i in range(9)) return render(req, 'box/1.html', {'query': text, 'url_pic': zip(url_lst, *top_pics), 'method': method, 'range': range(len(url_lst))}) elif method == '2': return render(req, 'box/2.html', {'query': text, 'url': url_lst[0], 'retrieved': pic_lst, 'method': method, 'range': range(len(url_lst))}) elif method == '3': return render(req, 'box/2.html', {'query': text, 'url': url_lst[0], 'retrieved': pic_lst, 'method': method, 'range': range(len(url_lst))}) # return render(req, 'box/3.html', {'query': text, # 'url_pic': zip(url_lst, pic_lst), # 'method': method, # 'range' : range(len(url_lst))}) elif method == '4': return render(req, 'box/4.html', {'query': text, 'url_pic': zip(url_lst, pic_lst), 'method': method, 'range': range(len(url_lst))})
def home( request ): offset = ( int( request.GET.get( "page", 1 )) - 1 ) * settings.PAGE_SIZE articles = Article.objects.filter( status = "live", is_duplicate = False ).order_by( "-date_published" )[offset:offset+settings.PAGE_SIZE] if not request.is_ajax(): return render( request, "full_list.html", dictionary = { "article_list": articles, } ) else: return render( request, "ajax_list.html", dictionary = { "article_list": articles, } )
def start_viz(request,decomposition_id): decomposition = Decomposition.objects.get(id = decomposition_id) experiment = decomposition.experiment context_dict = {} context_dict['decomposition'] = decomposition context_dict['experiment'] = experiment ready, _ = EXPERIMENT_STATUS_CODE[1] choices = [(analysis.id, analysis.name + '(' + analysis.description + ')') for analysis in DecompositionAnalysis.objects.filter(decomposition=decomposition, status=ready)] # add form stuff here! if request.method == 'POST': # form = DecompVizForm(request.POST) viz_form = VizForm(choices,request.POST) if viz_form.is_valid(): min_degree = viz_form.cleaned_data['min_degree'] if len(viz_form.cleaned_data['ms1_analysis']) == 0 or viz_form.cleaned_data['ms1_analysis'][0] == '': ms1_analysis_id = None else: ms1_analysis_id = viz_form.cleaned_data['ms1_analysis'][0] vo = VizOptions.objects.get_or_create(experiment=experiment, min_degree=min_degree, ms1_analysis_id=ms1_analysis_id)[0] context_dict['vo'] = vo return render(request,'decomposition/graph.html',context_dict) else: # context_dict['viz_form'] = DecompVizForm() context_dict['viz_form'] = VizForm(choices) return render(request,'decomposition/viz_form.html',context_dict)
def new_pool(request): title = 'New Pool' form = poolForm(request.POST or None) if request.POST: if request.POST.get("_cancel"): return redirect(reverse('pool_list')) else: form = poolForm(request.POST) if form.is_valid(): form.save() obj = form.instance if request.POST.get("_stay"): return redirect(reverse('pool_edit', kwargs={'uuid': obj.pk} )) else: return redirect(reverse('pool_list')) else: context = {"title": title, "form": form} return render(request, "pool/pool.html", context) else: context = {"title": title, "form": form} return render(request, "pool/pool.html", context)
def edit_pool(request, uuid=None): title = 'Edit Pool' if uuid: thisObj = get_object_or_404(pool, poolID=uuid) if request.POST: if request.POST.get("_cancel"): return redirect(reverse('pool_list')) else: form = poolForm(request.POST, instance=thisObj) if form.is_valid(): form.save() if request.POST.get("_stay"): context = {"title": title, "form": form} return render(request, "pool/pool.html", context) else: return redirect(reverse('pool_list')) else: context = {"title": title, "form": form} return render(request, "pool/pool.html", context) else: form = poolForm(instance=thisObj) context = {"title": title, "form": form} return render(request, "pool/pool.html", context)
def profile(request): if request.session['email']: if request.method=='POST': a=Register.objects.get(email=request.session['email']) try: b=UserEditPro.objects.get(user=a) except: b=UserEditPro(user=a) b.save() b=UserEditPro.objects.get(user=a) form=UserForm(request.POST,instance=b) if form.is_valid(): f=form.save(commit=False) f.user=a f.save() return HttpResponseRedirect('/blog/login/') else: return render(request,'blog/profile.html',{'form':form}) else: a=Register.objects.get(email=request.session['email']) try: b=UserEditPro.objects.get(user=a) except: b = UserEditPro(user=a) b.save() b=UserEditPro.objects.get(user=a) form=UserForm(instance=b) return render(request,'blog/profile.html',{'form':form}) else: return HttpResponseRedirect('blog/login/')
def edit_contact(request, uuid=None): title = 'Edit Contact' if uuid: thisObj = get_object_or_404(contact, ctID=uuid) if request.POST: if request.POST.get("_cancel"): return redirect(reverse('contact_list')) else: form = contactForm(request.POST, instance=thisObj) if form.is_valid(): form.save() if request.POST.get("_stay"): context = {"title": title, "form": form} return render(request, "contact/contact.html", context) else: return redirect(reverse('contact_list')) else: context = {"title": title, "form": form} return render(request, "contact/contact.html", context) else: form = contactForm(instance=thisObj) context = { "title": title, "form": form } return render(request, "contact/contact.html", context)
def teacher_login(request): if request.user.is_authenticated(): messages.info(request,'Please logout first and then re-login with a different account.') return HttpResponseRedirect('/home/') if request.method == 'POST': t_username = request.POST.get('username') t_password = request.POST.get('password') try: t_user = authenticate(username=t_username, password=t_password) teacher = Teacher.objects.get(pk=t_user.id) except Exception as e: t_user = None teacher = None if teacher is not None: if t_user.is_active: login(request, t_user) messages.success(request,'You logged in successfully.') return HttpResponseRedirect('/teacher/') else: messages.warning(request,'Your account is not yet active.') return render(request, 'teacher/login_teacher.html', {'t_not_active': True, 'next': request.POST.get('next')}) else: course_list = CourseDetail.objects.all() course_list = pagination.get_paginated_list(obj_list=course_list,page = request.GET.get('page')) messages.error(request,'Please enter valid credentials.') return render(request, 'teacher/login_teacher.html', {'t_login_error': True, 'next': request.POST.get('next')}) else: return render(request,'teacher/login_teacher.html',{})
def home(request): fables = Published.objects.all() return render(request, 'home.html', { 'title': 'FABLOPICASSO', 'fables': fables, })
def index(request): posts = Post.objects.order_by('-created_date') print(posts) return render(request, 'blog/post_list.html', {'posts': posts})
def show(request, post_id): post = get_object_or_404(Post, pk=post_id) return render(request, 'blog/post_detail.html', {'post': post})
def modelfrm(request): form = modelform() return render(request, 'home.html', {'form': form})
def contact(request): form=DataForm() return render(request,'home.html',{'form':form})
def first(reqeust): res=student.objects.all().filter(sid=100) return render(reqeust,'home.html',context={'result':res})
def home(request): return render(request,'django_home.html')
def fabl_publish(request, id): id = Published.objects.get(id=id) return render(request, 'fabl_publish.html', { 'fabl': id, })
def employee_list(request): context = {'employee_list': Employee.objects.all()} return render(request, "emp_reg/emp_list.html", context)
def fabl_create(request): sahne_form = SahneForm() baglam_formset = BaglamFormset() baglamlist = [] basliklist = [] girizgahlist = [] serimlist = [] dugumlist = [] cozumlist = [] if request.method == 'POST': sahne_form = SahneForm(request.POST) baglam_formset = BaglamFormset(request.POST) if sahne_form.is_valid() and baglam_formset.is_valid(): baslik = sahne_form.cleaned_data['baslik'] girizgah = sahne_form.cleaned_data['girizgah'] serim = sahne_form.cleaned_data['serim'] dugum = sahne_form.cleaned_data['dugum'] cozum = sahne_form.cleaned_data['cozum'] for form in baglam_formset: baglamlist.append((form.cleaned_data.get('anahtar'), form.cleaned_data.get('deger'), form.cleaned_data.get('extra'), )) # Variable exchange with deger for baglam in baglamlist: for word in baslik.split(): if word.lower().startswith(baglam[1].lower()): word = word.lower().replace(baglam[1].lower(), "{"+baglam[0].lower()+"}") basliklist.append(word) baslik = " ".join(basliklist) basliklist = [] for word in girizgah.split(): if word.lower().startswith(baglam[1].lower()): word = word.lower().replace(baglam[1].lower(), "{"+baglam[0].lower()+"}") girizgahlist.append(word) girizgah = " ".join(girizgahlist) girizgahlist = [] for word in serim.split(): if word.lower().startswith(baglam[1].lower()): word = word.lower().replace(baglam[1].lower(), "{"+baglam[0].lower()+"}") serimlist.append(word) serim = " ".join(serimlist) serimlist = [] for word in dugum.split(): if word.lower().startswith(baglam[1].lower()): word = word.lower().replace(baglam[1].lower(), "{"+baglam[0].lower()+"}") dugumlist.append(word) dugum = " ".join(dugumlist) dugumlist = [] for word in cozum.split(): if word.lower().startswith(baglam[1].lower()): word = word.lower().replace(baglam[1].lower(), "{"+baglam[0].lower()+"}") cozumlist.append(word) cozum = " ".join(cozumlist) cozumlist = [] tempbaslik = baslik baslik = Fabl.objects.create(baslik=baslik, user=request.user) Sahne.objects.create(anahtar='B', deger=baslik, secenek='I', fabl_id=baslik) Sahne.objects.create(anahtar='G', deger=girizgah, secenek='I', fabl_id=baslik) Sahne.objects.create(anahtar='S', deger=serim, secenek='I', fabl_id=baslik) Sahne.objects.create(anahtar='D', deger=dugum, secenek='I', fabl_id=baslik) Sahne.objects.create( anahtar='C', deger=cozum, secenek=sahne_form.cleaned_data['cozum_secenek'], fabl_id=baslik, ) for baglam in baglamlist: tempbaslik = tempbaslik.replace("{"+baglam[0]+"}", baglam[2]) girizgah = girizgah.replace("{"+baglam[0]+"}", baglam[2]) serim = serim.replace("{"+baglam[0]+"}", baglam[2]) dugum = dugum.replace("{"+baglam[0]+"}", baglam[2]) cozum = cozum.replace("{"+baglam[0]+"}", baglam[2]) published = Published.objects.create( title=tempbaslik, content=girizgah+" "+serim+" "+dugum+" "+cozum, user=request.user, ) for form in baglam_formset: anahtar = form.cleaned_data.get('anahtar') deger = form.cleaned_data.get('deger') if anahtar and deger: Baglam(anahtar=anahtar, deger=deger, fabl_id=baslik).save() return redirect(reverse("publish", args=[published.id])) return render(request, 'fabl_create.html', { 'title': 'FABLE-CREATE', 'sahne_form': sahne_form, 'baglam_formset': baglam_formset, })
def assets_config(request): return render(request, 'assets/assets_config.html', { "user": request.user, "baseAssets": getBaseAssets() })
def get(self, request): return render(request, 'user-profile.html')
def post(self, request): form = self.form_class(request.POST) """ # NOTE: this is only enabled with js and it copies the previous provided data if 'submit_refresh_captcha' in request.POST: print("REFRESH") copy = request.POST.copy() delete_elements = ['captcha_0', 'captcha_1', 'csrfmiddlewaretoken'] for el in delete_elements: try: copy[el] = "" except: pass form = self.form_class(copy) return render(request, 'registration/sign_up.html', {'form': form}) """ if form.is_valid(): # the user is not active until the activation url has been requested new_user = form.save(commit=False) new_user.is_active = False # create the user that can be authenticated later on new_user.save() # TODO in case the email address is not verified within the next seven days the user shall be removed # content of the email that includes the activation url email = EmailMessage( # subject _('Verify your email address for ' + settings.PLATFORM), # body render_to_string( 'registration/activate_account_email_template.htm', { 'user': new_user, 'platform': settings.PLATFORM, # url-elements 'domain': get_current_site(request).domain, 'uid': urlsafe_base64_encode(force_bytes( new_user.pk)).decode(), 'token': account_activation_token.make_token(new_user), }), # TODO as soon as there is a parameter in the settings to provide the from field it shall be used here # to to=[form.cleaned_data.get('email')], ) email.send() return render(request, 'registration/email_confirmation.html') # remove errors for email and username if captcha failed so it is only possible # to leak registered usernames and email addresses if the captcha was provided correctly # otherwise this would result in a more harmful privacy leak if form.errors and 'captcha' in form.errors: non_critical_user_err_msg = _( "@ is not allowed in username. Username is required as 150 characters or " + "fewer. Letters, digits and ./+/-/_ only.") if "username" in form.errors and non_critical_user_err_msg not in form.errors[ 'username']: del form.errors['username'] if "email" in form.errors: del form.errors['email'] return render(request, 'registration/sign_up.html', {'form': form})
def assets_add(request): if request.method == "GET": return render(request, 'assets/assets_add.html', { "user": request.user, "baseAssets": getBaseAssets() })
def results(request): return render(request, 'department/results.html')
def get(self, request): return render(request, 'registration/sign_up.html', {'form': self.form_class()})
def index(request): return render(request, 'main/index.html')
def index(request): all_departments = Department.objects.all() context = { 'all_departments' : all_departments } return render(request, 'department/index.html', context)
def remove_all_notifications(request): if request.user.is_authenticated: inbox = request.user.notifications inbox.all().delete() return redirect('accounts:view_profile', request.user.userprofile.slug) return render(request, 'community/inbox_read_view.html')
def products(request): return render(request, 'main/products.html')
def article_list(request): articles = Article.objects.all().order_by('date') return render(request, 'articles/article_list.html', {'articles': articles})
def client_company_name(request): client_name = Clients.objects.all() return render(request, 'timesheet/add_timesheet.html', {"client_names": client_name})
def list_product(request): products = Product.objects.all() return render(request, 'simple_CRUD/products.html', {'products': products})
def mark_all_as_read(request): if request.user.is_authenticated: inbox = request.user.notifications inbox.mark_all_as_read() return redirect('community:all_items') return render(request, 'community/inbox_read_view.html')
def cart(request): # 获取登录用户的cookie(user_id) user_id = request.COOKIES.get('user_id') # 如果值不存在,则证明没登录 if not user_id: return HttpResponseRedirect('/Buyer/cart_hint/') else: # 通过user_id 将Cart购物车中的数据提取出来 goods_list = Cart.objects.filter(user_id=user_id) if request.method == 'POST': # 获取POST请求来的数据 post_data = request.POST # 定义一个列表,用于存储前端传递来的商品 cart_data = [] # <-----------------------普通查询-------------------> # # 循环遍历post_data,查询出里面的key和value # for k,v in post_data.items(): # # 判断,如果key值中的前面是以good_ 开头的,则获取 # if k.startswith('good_'): # cart_data.append(Cart.objects.get(id=int(v))) # # 获取提交过来的数据的总数据 # good_count = len(cart_data) # # 订单的总价 先查询出每一个商品的总价格,然后在通过循环,查出所有人的,最后求和 # good_total = sum([int(i.good_total) for i in cart_data]) #<-----------------------聚类查询---------------------> # 1、查询到购物车中的商品的id号 for k, v in post_data.items(): # 筛选post_data的数据key值是以good_ 开头的数据 if k.startswith('good_'): cart_data.append(int(v)) # 2、使用in方法进行范围的规定,然后使用Sum方法进行计算 # 查询cart_data的长度 good_count = len(cart_data) # 通过id 将数据中的good_total提取出来并求和 获取到的值为{'good_total__sum': 求的和的数值} good_total = Cart.objects.filter(id__in=cart_data).aggregate( Sum('good_total')) # 保存订单 先保存订单表,在保存订单详情表,因为订单详情表有外键为订单表 order = Order() order.order_id = setOrderId(user_id, good_count, 1) order.good_count = good_count order.order_user = Buyer.objects.get(id=user_id) order.order_price = good_total['good_total__sum'] order.order_status = 1 order.save() # 保存订单详情表 因为订单详情表的数据不是一条,而是一个序列,所以需要通过循环遍历,挨个添加 # 前面已经将所有数据放入到cart_data 中了,所以现在只需要循环遍历即可 for detail in cart_data: d = Cart.objects.filter(id=detail).first() orderDetail = OrderDetail() orderDetail.order_id = order # 这是一条订单数据 orderDetail.good_id = d.good_id orderDetail.good_name = d.good_name orderDetail.good_price = d.good_price orderDetail.good_number = d.good_number orderDetail.good_total = d.good_total orderDetail.good_store = d.good_store orderDetail.good_image = d.good_image orderDetail.save() # order 是一条支付页 也就是成功保存完数据会跳转到支付界面 url = '/Buyer/place_order/?order_id=%s' % order.id return HttpResponseRedirect(url) return render(request, 'buyer/cart.html', locals())
def article_detail(request, slug): article = Article.objects.get(slug=slug) return render(request, 'articles/article_detail.html', {'article':article})
def dashboard(request): param={'edu_level':EducationLevel.objects.all()} print (request.session.get('edu_id')) return render(request,'index.html',param)
def cart_hint(request): return render(request, 'buyer/cart_hint.html')
def index(request): return render(request, 'index.html', {'depts_list':depts_list})
def base(request): return render(request, 'buyer/base.html')