def index(request): if request.method == "GET": return render_to_response( "index.html", {"error": False, "token_field_name": TOKEN_FIELD_NAME}, context_instance=RequestContext(request), ) else: formkey = urlparser.get_formkey(request.POST["formurl"]) if not formkey: return render_to_response( "index.html", {"error": True, "formurl": request.POST["formurl"], "token_field_name": TOKEN_FIELD_NAME}, context_instance=RequestContext(request), ) form = Form(formkey=formkey) form.fill_entry_id() if not form.entry_id: return render_to_response( "index.html", {"error": True, "formurl": request.POST["formurl"], "token_field_name": TOKEN_FIELD_NAME}, context_instance=RequestContext(request), ) form.save() return render_to_response("created.html", {"form": form})
def favorites_videos_list(request): videos_list = Pod.objects.filter( id__in=request.user.favorites_set.all().values_list('video', flat=True)) per_page = request.COOKIES.get('perpage') if request.COOKIES.get( 'perpage') and request.COOKIES.get('perpage').isdigit() else DEFAULT_PER_PAGE order_by = request.COOKIES.get('orderby') if request.COOKIES.get( 'orderby') else "order_by_-date_added" videos_list = videos_list.order_by( "%s" % replace(order_by, "order_by_", "")) paginator = Paginator(videos_list, per_page) page = request.GET.get('page') videos = get_pagination(page, paginator) if request.is_ajax(): return render_to_response("videos/videos_list.html", {"videos": videos}, context_instance=RequestContext(request)) return render_to_response("favorites/my_favorites.html", {"videos": videos}, context_instance=RequestContext(request))
def user_add(request): if request.method=="GET": user_list=user_manage.UserGet().get_user_list('') return render_to_response('user_add.html',{"user_list":user_list},context_instance=RequestContext(request)) else: result,msg=user_manage.UserManage(request.POST).user_add() return render_to_response('user_add.html',{"msg":msg},context_instance=RequestContext(request))
def profile_page(request, view_user): if not request.user.is_authenticated(): return HttpResponseRedirect(reverse('forum.views.main_index',)) else: if request.user.username == view_user: if request.method == 'POST': #print request.FILES form_profile = ProfileUpdate(request.POST, request.FILES) if form_profile.is_valid(): # process data cd = form_profile.cleaned_data user_update = ForumUser.objects.get(user=request.user) success_reply = [] if request.FILES: f = request.FILES['avatar_img'] destination = open('%s/avatars/%s' % (settings.MEDIA_ROOT, f.name), 'wb+') for chunk in f.chunks(): destination.write(chunk) destination.close() user_update.avatar_img = "avatars/%s" % f.name user_update.save() # uploadedImage = cd['avatar_img'] # user_update = (request.FILES) if(cd['password1']): user_update.user.set_password(cd['password1']) user_update.user.save() success_reply.append('Password') if(cd['email1'] != user_update.user.email and cd['email1'] != ''): user_update.user.email = cd['email1'] user_update.user.save() success_reply.append('Email') return render_to_response('profile_page.html', {'form_profile' : form_profile, 'success_reply': success_reply, 'forum_user': user_update, 'site_root': reverse('forum.views.main_index'), }, context_instance=RequestContext(request)) else: default_data = { 'email1': request.user.email, 'email2': request.user.email, } form_profile = ProfileUpdate(default_data) try: forum_user = ForumUser.objects.get(user=request.user) except: forum_user = ForumUser(user=request.user) forum_user.save() return render_to_response('profile_page.html', {'form_profile' : form_profile, 'forum_user' : forum_user, 'site_root': reverse('forum.views.main_index',),}, context_instance=RequestContext(request)) else: return HttpResponseRedirect(reverse('forum.views.main_index',))
def protocolos_descricao(request, pdf=False): """ Relatório Administrativo - Relatório de Protocolos por descrição. """ if request.GET.get('termo'): termo_id = request.GET.get('termo') termo = get_object_or_404(Termo, pk=termo_id) retorno = [] for d in Descricao.objects.all(): desc = {'descricao': d.__unicode__(), 'protocolos': Protocolo.objects.filter(descricao2=d, termo=termo) .order_by('-termo__ano', 'referente')} retorno.append(desc) if pdf: return render_to_pdf_weasy('protocolo/descricoes.pdf', {'protocolos': retorno}, request=request, filename='protocolos.pdf') else: return render_to_response('protocolo/descricoes.html', {'protocolos': retorno, 'termo': termo}, context_instance=RequestContext(request)) else: return render_to_response('financeiro/relatorios_termo.html', {'termos': Termo.objects.all(), 'view': 'protocolos_descricao'}, context_instance=RequestContext(request))
def show_aloj_id(request,ide): pathf=request.path+"/xmlfrances" pathi=request.path+"/xmlingles" try: hotel=Hotel.objects.get(id=ide) print hotel.stars print hotel.tipo except Hotel.DoesNotExist: context={'name': ""} return render_to_response('alojid.html',context); listimages=Image.objects.filter(hid=hotel.id) listcoms="" if request.method =='POST': value = request.POST.get('comentarios', "") n= hotel.numbercom+1; hotel.numbercom=n hotel.save() comment=Comment(hid=hotel.id,com=hotel,text=value) comment.save() listcoms=Comment.objects.filter(hid=hotel.id) try: us=PagUser.objects.get(user=request.user.username) except PagUser.DoesNotExist: context = {'lista':listimages[0:5],'condicion':"",'url':hotel.url,'name':hotel.name,'address':hotel.address,'body':hotel.body,'comentarios':listcoms,'type':hotel.tipo,'stars':hotel.stars,'pathf':pathf,'pathi':pathi,'id':ide,'email':hotel.email, 'phone':hotel.phone} return render_to_response('alojid.html', context,context_instance = RequestContext(request)) context = {'lista':listimages[0:5],'condicion':"",'url':hotel.url,'name':hotel.name,'address':hotel.address,'body':hotel.body,'comentarios':listcoms,'type':hotel.tipo,'stars':hotel.stars,'pathf':pathf,'pathi':pathi,'id':ide,'email':hotel.email, 'phone':hotel.phone,'color':us.color,'size':us.size} return render_to_response('alojid.html', context,context_instance = RequestContext(request))
def get_view(request, topic_id): try: topic = Topic.objects.get(pk=topic_id) except Topic.DoesNotExist: raise Http404 user = request.user if user.is_authenticated(): counter = { 'topics' : user.topic_author.all().count(), 'replies': user.reply_author.all().count(), 'favorites': user.fav_user.all().count() } notifications_count = user.notify_user.filter(status=0).count() topic_favorited = Favorite.objects.filter(involved_topic=topic, owner_user=user).exists() reply_num = 106 reply_count = topic.reply_count print 'reply_count,',reply_count reply_last_page = (reply_count // reply_num + (reply_count % reply_num and 1)) or 1 try: current_page = int(request.GET.get('p', reply_last_page)) except ValueError: current_page = reply_last_page replies, reply_page = Reply.objects.get_all_replies_by_topic_id(topic_id=topic_id, current_page=current_page, num=reply_num) active_page = 'topic' floor = reply_num * (current_page - 1) topic.reply_count = reply_page.total topic.hits = (topic.hits or 0) + 1 topic.save() render_to_response('topic.view.html',locals(), context_instance=RequestContext(request))
def search(request): """ Search for blog posts. This template will allow you to setup a simple search form that will try to return results based on given search strings. The queries will be put through a stop words filter to remove words like 'the', 'a', or 'have' to help imporve the result set. Template: ``blog/post_search.html`` Context: object_list List of blog posts that match given search term(s). search_term Given search term. """ if request.GET: stop_word_list = re.compile(STOP_WORDS, re.IGNORECASE) search_term = '%s' % request.GET['q'] cleaned_search_term = stop_word_list.sub('', search_term) cleaned_search_term = cleaned_search_term.strip() if len(cleaned_search_term) != 0: post_list = Post.objects.filter(body__icontains=cleaned_search_term, status__gte=2, publish__lte=datetime.datetime.now()) context = {'object_list': post_list, 'search_term':search_term} return render_to_response('blog/post_search.html', context, context_instance=RequestContext(request)) else: message = 'Search term was too vague. Please try again.' context = {'message':message} return render_to_response('blog/post_search.html', context, context_instance=RequestContext(request)) else: return render_to_response('blog/post_search.html', {}, context_instance=RequestContext(request))
def upload(request): try: uid=request.COOKIES['me_uid'] except KeyError: return HttpResponseRedirect('http://www.me.uestc.edu.cn/stu/index.php/Login/') auth= UserAuth(uid).is_auth() if not auth: return HttpResponseRedirect('http://www.me.uestc.edu.cn/stu/index.php/Login/') if request.method == "POST": form = UploadFileForm(request.POST,request.FILES) typ=request.FILES['files'].name.split('.')[1] if not (typ=='xls' or typ=='xlsx'): return HttpResponse("<h1>上传失败 只能上传excel文件</h1></br><a href='upload'>返回重新上传</a>") if form.is_valid(): files = open('static/excel.xls','w+') for chunk in request.FILES['files'].chunks(): files.write(chunk) files.close() up_suc=handle_upload_file() if up_suc : q=u"上传失败,请以学号为第一列!" else: q=u"上传成功!" return render_to_response('success.html',{'q':q}) else : form = UploadFileForm() return render_to_response('upload.html', {'form': form})
def usage_morereset(request): quota_update_fail = False try: refresh_all_quota_usage() except: quota_update_fail = True current_event = get_current_event() if current_event == None: return render_to_response('frontend/event-not-active.html', context_instance=RequestContext(request)) attendances = EventAttendance.objects.filter( event__exact=current_event ).order_by('-quota_multiplier') total = 0L for a in attendances: total += a.quota_used return render_to_response('frontend/usage.html', { 'attendances': attendances, 'total': bytes_str(total), 'mode': _('most resets'), 'quota_update_fail': quota_update_fail }, context_instance=RequestContext(request))
def usage_speed(request): quota_update_fail = False try: refresh_all_quota_usage() except: quota_update_fail = True current_event = get_current_event() if current_event == None: return render_to_response('frontend/event-not-active.html', context_instance=RequestContext(request)) attendances = list(EventAttendance.objects.filter( event__exact=current_event )) attendances.sort( key=(lambda o: o.last_datapoint().average_speed() if o.last_datapoint() else 0 ), reverse=True ) total = 0L for a in attendances: total += a.quota_used return render_to_response('frontend/usage.html', { 'attendances': attendances, 'total': bytes_str(total), 'mode': _('highest speed'), 'quota_update_fail': quota_update_fail }, context_instance=RequestContext(request))
def quota_user_reset(request): user = request.user profile = get_userprofile(user) current_event = get_current_event() if current_event == None: return render_to_response('frontend/event-not-active.html', context_instance=RequestContext(request)) attendance = get_userprofile_attendance(current_event, profile) if attendance == None: return render_to_response('frontend/not-signed-in.html', dict( event=current_event ), context_instance=RequestContext(request)) # TODO: Make it check you have used at least 70% of your quota before # continuing. if request.method == "POST": reset_form = ResetLectureForm(request.POST) if reset_form.check_answers(): try: # reset the quota if allowed. # we do ==1 here instead of < 2 because otherwise someone could use # this to regain internet access after having it revoked forcefully. if attendance.quota_multiplier == 1: # create a log of this event if settings.RESET_EXCUSE_REQUIRED: excuse = reset_form.cleaned_data['excuse'] else: # clear out the reset excuse if one was provided but not # allowed. excuse = '' QuotaResetEvent.objects.create( event_attendance=attendance, performer=profile, excuse=excuse ) attendance.quota_multiplier = 2 attendance.save() enable_user_quota(attendance) sync_user_connections(profile) except: return controller_error(request) return redirect('quota') else: # some answers were incorrect return render_to_response('frontend/reset-lecture.html', { 'reset_form': reset_form, 'incorrect': True }, context_instance=RequestContext(request)) else: reset_form = ResetLectureForm() return render_to_response('frontend/reset-lecture.html', { 'reset_form': reset_form, 'incorrect': False }, context_instance=RequestContext(request))
def regions(request, id=None): if id: catalog_items = RegionDirectory.objects.filter(parent=id).order_by('name') else: catalog_items = RegionDirectory.objects.filter(parent=None).order_by('name') id = "" if request.POST: data_dict = request.POST form = RegionDirectoryForm(data=data_dict) if (form.is_valid()): entity = form.save(commit=True) if id: entity.setParent(RegionDirectory.objects.get(pk=id)) else: return render_to_response('ratings/simple_catalogs_management.html', dict(form=form, title="Регионы голосований", link="/ratings/admin/catalogs/", link_text="Вернуться в список каталогов", catalog_items=catalog_items, parent=id), context_instance=RequestContext(request)) form = RegionDirectoryForm() return render_to_response('ratings/simple_catalogs_management.html', dict(form=form, title="Регионы голосований", link="/ratings/admin/catalogs/", link_text="Вернуться в список каталогов", catalog_items=catalog_items, parent=id), context_instance=RequestContext(request))
def search1(request): empty = False list_search =[] errors=[] s_name= request.GET["selection"] if 'q' in request.GET and request.GET['q']: message = request.GET['q'] if s_name=="author_name": list_search = Book.objects.filter(author__icontains=message) if s_name=="book_name": list_search = Book.objects.filter(name__icontains=message) final_list=[] if str(list_search) == "[]": empty = True errors.append("not found") return render_to_response('base2.html',{'errors':errors}) else: final_list = [] for i in list_search: mylist =[] mylist.append(i.id_book) mylist.append(i.name) mylist.append(i.author) mylist.append(i.price) final_list.append(mylist) return render_to_response('proffer.html', {'endlist':final_list})
def nginx_configuration_editor(request): config_rw = FileRW() if request.method == "POST": text = request.POST.get("nginx_config_text", "unknown"); if text != "unknown": response = {} try: config_rw.write(constant.DEFAULT_NGINX_LOCATION, text) except RigeryError as rigery_error: response["error_message"] = rigery_error.message response["nginx_config_text"] = text response["nginx_conf_location"] = constant.DEFAULT_NGINX_LOCATION return render_to_response( "nginx_manager/nginx_configuration_editor.html", response, context_instance=RequestContext(request), ) else: return render_to_response( "nginx_manager/nginx_configuration_editor.html", {"error_message", "Wrong type of request"}, context_instance=RequestContext(request), ) else: response = {} response["nginx_config_text"] = config_rw.read(constant.DEFAULT_NGINX_LOCATION) response["nginx_conf_location"] = constant.DEFAULT_NGINX_LOCATION return render_to_response( "nginx_manager/nginx_configuration_editor.html", response, context_instance=RequestContext(request), )
def new(request): if request.method == 'POST': # We're accepting form data for save to DB if not request.user.is_authenticated(): return render_to_response('registration/pleaselogin.html') form = NewItemForm(request.POST) if not form.is_valid(): # throw error return HttpResponse("Error! Form invalid. Form: %s" % form) else: new_item = form.save(commit=False) # grab the user id from the current user #new_item.seller = request.user.id new_item.seller = request.user #cd = form.cleaned_data new_item.save() #send_mail( # cd['subject'], # cd['message'], # cd.get('email', '*****@*****.**'), # ['*****@*****.**'], #) #return HttpResponseRedirect('/contact/thanks/') return HttpResponseRedirect('/listings/') else: # user GET if not request.user.is_authenticated(): # not logged in return render_to_response('registration/pleaselogin.html') else: # we are logged in form = NewItemForm() return render_to_response('listings/item_form.html', {'form': form}, context_instance=RequestContext(request))
def addQuest(request): """ create a default quest for the user """ try: name = request.GET['name'] latitude = float(request.GET['latitude']) longitude = float(request.GET['longitude']) description = request.GET['description'] b1_lon = request.GET['b1_lon'] b1_lat = request.GET['b1_lat'] b2_lon = request.GET['b2_lon'] b2_lat = request.GET['b2_lat'] b3_lon = request.GET['b3_lon'] b3_lat = request.GET['b3_lat'] b4_lon = request.GET['b4_lon'] b4_lat = request.GET['b4_lat'] id = request.GET['username'] pw = request.GET['password'] except: return render_to_response('addquest.xml', {'result' : False,'reason': "parsing error"}) try: user = returnUser(id,pw) q=quest(owner=user,name=name,latitude=latitude,longitude=longitude,description=description,b1_lon=b1_lon,b1_lat=b1_lat, b2_lon=b2_lon,b2_lat=b2_lat, b3_lon=b3_lon,b3_lat=b3_lat,b4_lon=b4_lon,b4_lat=b4_lat) q.save() except: return render_to_response('addquest.xml', {'result' : False, 'reason': "transaction error"}) return render_to_response('addquest.xml', {'result' : True, 'questid' : q.id})
def create_peg(request): if request.method == 'POST': form = PegCreateForm(request.POST) if form.is_valid(): print "VALID" # Create Peg peg, dummy = Peg.objects.get_or_create( url = form.cleaned_data['url'], name = form.cleaned_data['name'], peg_des = form.cleaned_data['desc'] ) myboard = Board.objects.get(id = 1) #boardname = request.POST['boardname'] myboard.peg_set.add(peg) myboard.save() return HttpResponse("Peg Saved") else: print "INVALID" form = PegCreateForm() variables = RequestContext(request, {'form': form}) return render_to_response('CRUD_Peg.html', variables) else: print "VALID LOad" form = PegCreateForm() variables = RequestContext(request, {'form': form}) return render_to_response('CRUD_Peg.html', variables)
def create_board(request): if request.method == 'POST': form = BoardCreateForm(request.POST) if form.is_valid(): print "VALID" # Create Board board, dummy = Board.objects.get_or_create( Board_name = form.cleaned_data['bname'], user_id = "1", Board_des = form.cleaned_data['bdesc'] ) mmboard= Board.objects.get(id = 1) mmboard.save() #boardname = request.POST['boardname'] return HttpResponse("Board Saved") else: print "INVALID" form = BoardCreateForm() variables = RequestContext(request, {'form': form}) return render_to_response('CRUD_Board.html', variables) else: print "VALID Load" form = BoardCreateForm() variables = RequestContext(request, {'form': form}) return render_to_response('CRUD_Board.html', variables)
def process_application(request, status): context = RequestContext(request) if request.method == 'GET': # process request if both IDs are available in the request if 'intern_id' in request.GET and 'job_id' in request.GET: try: recruiter = Recruiter.objects.get(user=request.user) intern = Intern.objects.get(id=request.GET['intern_id']) job = Job.objects.get(id=request.GET['job_id']) application = Application.objects.get(intern=intern,job=job) # restrict access to that user, who is offering the internship if job.company != recruiter: return render_to_response('error.html', {'error': "You don't have the permission to accept interns for this job"}, context) application.status = status application.save() return render_to_response('company/process_application_feedback.html', {'status': status, 'intern': intern, 'user_type': 1}, context) # Invalid data except (Intern.DoesNotExist, Job.DoesNotExist, Application.DoesNotExist, Recruiter.DoesNotExist): return render_to_response('error.html', {'error': "Could not process your request"}, context) else: # Missing data return render_to_response('error.html', {'error': "Missing dictionary key"}, context) else: return render_to_response('error.html', {'error': "Something is wrong"}, context)
def register_req(request): state = "Something wrong happened. Please reload this page" username = password1 = password2 = '' if request.POST: username = request.POST.get('username') password1 = request.POST.get('password1') password2 = request.POST.get('password2') # Check username is blank if not username: state = "Please type your username in the field" return render_to_response('register.html',{'state':state}) # Check password is same if password1 == password2: pass else: state = "Passwords are not same" return render_to_response('intg_search.html',{'state':state}) # Check ID is not exist & Register User try: find = User.objects.get(username=username) except User.DoesNotExist: user = User.objects.create_user(username,'',password1) user.save() state = "Registraion complete. Please log on." return render_to_response('intg_search.html',{'state':state})
def TaskValidate(request, task_id): log.debug("task_id %s - %s - %s" %(task_id,request.POST,request.GET)) task = get_object_or_404(Task, pk=task_id, owner=request.user) if request.POST: form = ValidationForm(request.POST) if form.is_valid(): # TODO: unify with the api, now the code is copied value = form.cleaned_data['validation'] for task_instance in task.taskinstance_set.all(): if 'validation' not in task_instance.parameters: task_instance.quality = value pars = task_instance.parameters if pars is None: pars = {} pars['validation'] = value task_instance.save() # if ("process_tactics_id" in task_instance.parameters): # signal(task_instance.parameters['process_tactics_id'], task_instance.task.id, task_instance.id) messages.info(request, 'Validation made') return redirect(reverse('r-taskinstances',args={task_instance.task.process.id,task_instance.task.id,})) else: return render_to_response('requester/form.html', {'form': form}, context_instance=RequestContext(request)) else: log.debug("GET task_id %s",task_id) form = ValidationForm() return render_to_response('requester/form.html', {'form': form}, context_instance=RequestContext(request))
def project_detail(request, pk, page=''): print pk, page try: project = Project.objects.get(pk=pk) except Project.DoesNotExist: raise Http404 testers = project.testers.all() bugs = project.bugs.all() if page == None: return render_to_response('project_detail.html', locals(), context_instance=RequestContext(request)) elif page == '/bugs': return render_to_response('project_bugs.html', locals(), context_instance=RequestContext(request)) elif page == '/testers': return render_to_response('project_testers.html', locals(), context_instance=RequestContext(request)) elif page == '/enlist': user = request.user if not user.is_authenticated(): raise PermissionDenied # Текущий залогиненый пользователь должен быть тестером if not hasattr(user, 'tester'): raise PermissionDenied tester = user.tester project.add_tester(tester) return HttpResponseRedirect('/projects/%i/testers' % project.pk) else: raise Http404
def TaskInstanceValidate(request, task_instance_id): task_instance = get_object_or_404(TaskInstance, pk=task_instance_id, task__owner=request.user) if request.POST: form = ValidationForm(request.POST) if form.is_valid(): if 'validation' not in task_instance.parameters: # TODO: unify with the api, now the code is copied value = form.cleaned_data['validation'] task_instance.quality = value pars = task_instance.parameters if pars is None: pars = {} pars['validation'] = value task_instance.save() # if ("process_tactics_id" in task_instance.parameters): # signal(task_instance.parameters['process_tactics_id'], task_instance.task.id, task_instance.id) messages.info(request, 'Validation made') else: messages.warning(request, 'Validation was already set') return redirect(reverse('r-taskinstances',args={task_instance.task.process.id,task_instance.task.id,})) else: return render_to_response('requester/form.html', {'form': form}, context_instance=RequestContext(request)) else: form = ValidationForm() return render_to_response('requester/form.html', {'form': form}, context_instance=RequestContext(request))
def contactview(request): name = request.POST.get('name', '') subject = request.POST.get('topic', '') message = request.POST.get('message', '') from_email = request.POST.get('email', '') if name and message and from_email: t = get_template('contact_message.txt') c = Context({ 'name': name, 'from_email': from_email, 'message': message }) email_message = t.render(c) try: mail_admins(subject, email_message) except BadHeaderError: return HttpResponse('Invalid header found.') return HttpResponseRedirect('/contact/thankyou/') else: return render_to_response('contact/contacts.html', {'form': ContactForm()}, RequestContext(request)) return render_to_response('contact/contacts.html', {'form': ContactForm()}, RequestContext(request))
def course_edit_homework_handler(request, course_id = 'CSC540', homework_id = 'CSC540_1'): args = {} args.update(csrf(request)) args['course'] = course_id if request.method == 'POST': homework = Homework.objects.get(homework_id__contains = homework_id) homework.homework_id = request.POST.get('homeworkid') homework.homework_startdate = request.POST.get('startdate') homework.homework_enddate = request.POST.get('enddate') homework.homework_numretries = request.POST.get('numberattempts') homework.homework_mindifficulty = request.POST.get('mindiff') homework.homework_maxdifficulty = request.POST.get('maxdiff') homework.homework_correctanswerpts = request.POST.get('correctpoints') homework.homework_wronganswerpts = request.POST.get('wrongpoints') homework.save() return render_to_response('coursepage_prof.html', args) else: homework = Homework.objects.filter(homework_cid__course_id__contains = course_id).filter(homework_id__contains = homework_id) args['homework'] = homework[0].homework_id args['startdate'] = homework[0].homework_startdate args['enddate'] = homework[0].homework_enddate args['numretries'] = homework[0].homework_numretries args['mindifficulty'] = homework[0].homework_mindifficulty args['maxdifficulty'] = homework[0].homework_maxdifficulty args['correctanswerpts'] = homework[0].homework_correctanswerpts args['wronganswerpts'] = homework[0].homework_wronganswerpts args['cid'] = homework[0].homework_cid return render_to_response('course_edit_homework_prof.html', args)
def register(request): form_data = request.POST.copy() form = RegistrationForm(form_data) errors = form.errors print request.POST print form.errors if errors: return render_to_response('login.html', {'form': form}) # logout the existing user if (isinstance (request.user, AnonymousUser)): u = None else: u = request.user logout(request) email = request.POST['register_email'] password = request.POST['register_password'] try: u = User(username=email) u.set_password(password) u.email = email u.save() except: return render_to_response('login.html', {'form': form}) response = render_to_response('login.html', {'registration_status': "Registered successfully! Now you can login with your credentials!" }) return response
def combo1(request): query = request.GET.get('q', '') elementos= Ciudad.objects.all() if query: results=Universidad.objects.filter(ciudad=query) return render_to_response("consulta_ciudad.html",{"results": results,"query": query,"elementos": elementos}, context_instance=RequestContext(request) ) return render_to_response("consulta_ciudad.html",{"results": elementos,"query": query,"elementos": elementos}, context_instance=RequestContext(request))
def create_saved_search(request, database_name=settings.MONGO_DB_NAME, collection_name=settings.MONGO_MASTER_COLLECTION, skip=0, limit=200, return_keys=()): name = _("Create a Saved Search") if request.method == 'POST': form = SavedSearchForm(request.POST) if form.is_valid(): ss = form.save(commit = False) ss.user = request.user ss.save() return HttpResponseRedirect(reverse('saved_searches')) else: #The form is invalid messages.error(request,_("Please correct the errors in the form.")) return render_to_response('generic/bootstrapform.html', {'form': form, 'name':name, }, RequestContext(request)) #this is a GET idata ={'database_name': database_name, 'collection_name': collection_name} context= {'name':name, 'form': SavedSearchForm(initial=idata) } return render_to_response('generic/bootstrapform.html', RequestContext(request, context,))
def owners(request): owners_list = User.objects.filter(pod__in=VIDEOS).order_by( 'last_name').distinct() # User.objects.all() owners_filter = request.GET.get( 'owners_filter') if request.GET.get('owners_filter') else None if owners_filter: owners_list = owners_list.filter( last_name__iregex=r'^%s+' % owners_filter) #per_page = request.GET.get('per_page') if request.GET.get('per_page') and request.GET.get('per_page').isdigit() else DEFAULT_PER_PAGE per_page = request.COOKIES.get('perpage') if request.COOKIES.get( 'perpage') and request.COOKIES.get('perpage').isdigit() else DEFAULT_PER_PAGE paginator = Paginator(owners_list, per_page) page = request.GET.get('page') owners = get_pagination(page, paginator) if request.is_ajax(): return render_to_response("owners/owners_list.html", {"owners": owners}, context_instance=RequestContext(request)) return render_to_response("owners/owners.html", {"owners": owners, "video_count": VIDEOS.filter( owner__in=list(owners_list)).count()}, context_instance=RequestContext(request))