Example #1
0
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)
Example #2
0
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)
Example #3
0
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)
	})
Example #4
0
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})
Example #5
0
    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 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})
Example #7
0
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 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))})
Example #9
0
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/')
Example #10
0
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, } )
Example #11
0
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)
Example #12
0
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)
Example #13
0
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)
Example #14
0
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)
Example #15
0
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})
Example #16
0
File: views.py Project: grv07/clat
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 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)
Example #18
0
File: views.py Project: grv07/clat
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',{})
Example #19
0
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})
Example #20
0
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)
Example #21
0
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']})
Example #22
0
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})
Example #23
0
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 })
Example #24
0
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})
Example #25
0
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:'})
Example #26
0
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 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))
Example #28
0
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})
Example #29
0
 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)
Example #30
0
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)