Example #1
0
def recomendarJugadoresItem(request):
    items = None
    idUsuario = None
    usuario = None
    form = UserForm()
    if request.method == 'POST':
        form = UserForm(request.POST)
        if form.is_valid():
            idUsuario = form.cleaned_data['id']
            shelf = shelve.open("dataRS.dat")
            Prefs = shelf['Prefs']
            SimItems = shelf['SimItems']
            shelf.close()
            try:
                usuario = Usuario.objects.get(id=int(idUsuario))
            except:
                return redirect('/error')
            rankings = getRecommendedItems(Prefs, SimItems, int(idUsuario))
            recommended = rankings[:3]
            jugadores = []
            scores = []
            for re in recommended:
                jugadores.append(Jugador.objects.get(pk=re[1]))
                scores.append(re[0])
            items = zip(jugadores, scores)
    return render(request, 'searchRecommendJugadores.html', {
        'user': usuario,
        'items': items,
        'form': form
    })
Example #2
0
def editUser(request):
    us = None
    user_id = request.session['user']
    if user_id != -1:
        us = User.objects.get(id=user_id)
        form = UserForm(request.POST or None, instance=us)
    if form.is_valid():
        if us.password==form.cleaned_data['oldpassword']:
            if(us.email!=str(form.cleaned_data['email'])):
                us.email=form.cleaned_data['email']
            if form.cleaned_data['newpassword']!='':
                password=form.cleaned_data['newpassword']
                if password==form.cleaned_data['confirmpassword']:
                    if re.match(r'^(?=.*[a-z])(?=.*[0-9])(?=.*[A-Z])(?!.*[\!\@\#\$\%\^\&\*\(\)\,\+\.\=])(?=.*[\_\-])(?!.*\s).{6,}$',password) :
                        us.password=password
                    else:
                        return render_to_response('user.html', RequestContext(request, {'formset': form, 'msg': 'Nowe hasło powinno zawierać conajmniej 6 znaków w tym conajmniej jedną  małą i jedną wielką literę oraz jeden znak specjalny (- lub_) i jedną cyfrę'}))

                else:
                    return render_to_response('user.html', RequestContext(request, {'formset': form, 'msg':'Nowe hasło nie zgadza się z potwierdzeniem'}))

        else:
            return render_to_response('user.html', RequestContext(request, {'formset': form, 'msg':'Błędne hasło'}))
        us.save()
        return redirect('/')
    else:
        return render_to_response('user.html', RequestContext(request, {'formset': form}))
Example #3
0
    def post(self, request):

        if 'submitExamples' in request.POST:
            e_form = ExamplesForm(request.POST)
            if e_form.is_valid():
                file1 = e_form.cleaned_data['file1']
                file2 = e_form.cleaned_data['file2']
                self.generate_img('examples', file1, file2, find_files=True)
                return HttpResponseRedirect(reverse_lazy('main:home'))

            return self.render_to_response({
                'e_form': e_form,
                'u_form': UserForm
            })

        elif 'submitUser' in request.POST:
            u_form = UserForm(request.POST, request.FILES)
            if u_form.is_valid():
                file1 = u_form.cleaned_data['file1']
                file2 = u_form.cleaned_data['file2']
                try:
                    self.generate_img('user', file1, file2)
                    return HttpResponseRedirect(reverse_lazy('main:home'))

                except (IndexError, ValueError):
                    u_form.add_error(None, 'Can\'t parse SVG image')

            return self.render_to_response({
                'e_form': ExamplesForm,
                'u_form': u_form
            })

        return HttpResponseNotFound()
Example #4
0
def recommended_peripheral_items(request):
    if request.method == 'GET':
        form = UserForm(request.GET, request.FILES)
        if form.is_valid():
            id_user = form.cleaned_data['id']
            user = get_object_or_404(User, pk=id_user)
            shelf = shelve.open("dataRS.dat")
            prefs = shelf['Prefs']
            sim_items = shelf['SimItems']
            items = []
            if int(id_user) not in prefs:
                return render(request, 'recommendationItems.html', {
                    'user': user,
                    'items': items
                })
            shelf.close()
            getHybridRecommendation(prefs, int(id_user), sim_items)
            rankings = getRecommendedItems(prefs, sim_items, int(id_user))
            recommended = rankings[:
                                   20]  # Change number of similar items recommended
            peripherals = []
            scores = []
            for re in recommended:
                peripherals.append(Peripheral.objects.get(pk=re[1]))
                scores.append(re[0])
            items = zip(peripherals, scores)
            return render(request, 'recommendationItems.html', {
                'user': user,
                'items': items
            })
    form = UserForm()
    return render(request, 'searchUser.html', {'form': form})
Example #5
0
def signup(request):
    if request.method == "POST":
        user_form = UserForm(request.POST)
        user_data_form = UserDataForm(request.POST)
        if user_form.is_valid() and user_data_form.is_valid():
            new_user = User.objects.create_user(
                user_form.cleaned_data['username'],
                user_form.cleaned_data['email'],
                user_form.cleaned_data['password'])
            new_user.first_name = user_form.cleaned_data['first_name']
            new_user.last_name = user_form.cleaned_data['last_name']
            new_user.save()
            new_user_data = user_data_form.save(commit=False)
            new_user_data.user = new_user
            new_user_data.save()
            user = authenticate(username=user_form.cleaned_data['username'],
                                password=user_form.cleaned_data['password'])
            if user is not None:
                login(request, user)
            else:
                print('invalid login')
            return redirect('index')
    else:
        user_form = UserForm()
        user_data_form = UserDataForm()
        return render(
            request, 'registration/signup.html', {
                "user_form": user_form,
                "user_data_form": user_data_form,
                'parts': my_models.Part.objects.all(),
            })
Example #6
0
def register(request):
	registered = False
	if request.method == 'POST':
         	user_form = UserForm(data=request.POST)
        	profile_form = UserProfileForm(data=request.POST)
        	if user_form.is_valid() and profile_form.is_valid():
            		user = user_form.save()
			user.username = user.email
            		user.set_password(user.password)
            		user.save()

            		# Since we need to set the user attribute ourselves, we set commit=False.
            		# This delays saving the model until we're ready to avoid integrity problems.
            		profile = profile_form.save(commit=False)
            		profile.user = user
			profile.email = user.email
			profile.first_name = user.first_name
			profile.last_name = user.last_name
            		profile.save()
            		registered = True
              	else:
			print user_form.errors, profile_form.errors

    	# Not a HTTP POST, so we render our form using two ModelForm instances.
    	else:
        	user_form = UserForm()
        	profile_form = UserProfileForm()
		
	return render(request,
      	    'main/home.html',
            {'user_form': user_form, 'profile_form': profile_form} )
Example #7
0
def mainpage(request):
    #FIX TO REDIRECT
    context = RequestContext(request)
    if request.user.is_authenticated():
         return HttpResponseRedirect('/main/userpage/')
    else:
        if request.method == 'POST':
            user_form = UserForm(data=request.POST)
            if user_form.is_valid() and (request.POST['password'] == request.POST['check']):
                user = user_form.save()
                user.set_password(user.password)
                user.save()
                userprofile = UserProfile()
                userprofile.user = user.username
                userprofile.email = user.email
                userprofile.joined = datetime.datetime.now()
                userprofile.save()

                user = authenticate(username=user_form.cleaned_data['username'],
                                    password=user_form.cleaned_data['password'],
                                    )
                login(request, user)

                return HttpResponseRedirect('/main/userpage/')

            else:
                print user_form.errors
        else:
            user_form = UserForm()



    return render_to_response('main/main.html',{'form': user_form,}, context)
Example #8
0
def recommendedFilms2(request):
    if request.method == 'GET':
        form = UserForm(request.GET, request.FILES)
        if form.is_valid():
            nombre = form.cleaned_data['name']
            generos = Genre.objects.all()
            diccionario = {}
            for g in generos:
                diccionario[g] = 0
            usuario = User.objects.get(name=nombre)
            id = usuario.idUser
            puntuaciones = Rating.objects.filter(user=usuario)
            peliculas = []
            for p in puntuaciones:
                print Film.objects.get(movieTitle=p.film)
                pelicula = Film.objects.get(movieTitle=p.film)
                peliculas.append(pelicula)
                generos_p = pelicula.genres.all()
                #intentar recorrer los generos de la pelicula
                for ge in generos_p:
                    diccionario[ge] += 1
            #ordenar de menor a mayor
            l = diccionario.items()
            l.sort(key=lambda x: x[1])
            #coger los dos generos del diccionario que mas valor tengan
            tamano = len(l)
            lista = l[tamano - 2:]
            g1 = lista[0][0]
            g2 = lista[1][0]
            lista = [g1.genreName, g2.genreName]
            pelis = Film.objects.filter(genres=g1)
            pelis1 = pelis.filter(genres=g2)
            items = list(pelis1)
            for pe in peliculas:
                if pe in items:
                    items.remove(pe)
            synopsis = []
            final = []
            for i in items:
                ix = open_dir(dirindex)
                with ix.searcher() as searcher:
                    query = QueryParser("sinopsis",
                                        ix.schema).parse(unicode(i.movieTitle))
                    results = searcher.search(query)
                    for r in results:
                        synopsis.append(r['sinopsis'].encode('utf-8'))
            for i in range(len(items) - 1):
                final.append("Title: " + items[i].movieTitle +
                             " -----   Synopsis: " +
                             synopsis[i].decode('utf-8'))
            return render_to_response('recommendationItemsByUser.html', {
                'user': usuario,
                'final': final
            },
                                      context_instance=RequestContext(request))

    form = UserForm()
    return render_to_response('search_user.html', {'form': form},
                              context_instance=RequestContext(request))
Example #9
0
def create_user(request):
    form = UserForm(request.POST)
    if form.is_valid():
        user = form.instance
        user.set_password(user.password)
        user.save()
        return HttpResponseRedirect("/")
    else:
        return HttpResponseRedirect("/register")
Example #10
0
    def test_clean_username_exception(self):
        User.objects.create_user(username='******',
                                 email='*****@*****.**',
                                 password='******')

        form = UserForm()

        with self.assertRaises(ValidationError):
            form.clean_username()
Example #11
0
def apartadoA(request):
    if request.method=='GET':
        form = UserForm(request.GET, request.FILES)
        if form.is_valid():
            idUsuario = form.cleaned_data['id']
            user = get_object_or_404(Usuario, pk=idUsuario)
            return render(request,'ratedBooks.html', {'usuario':user})
    form=UserForm()
    return render(request,'search_user.html', {'form':form })
Example #12
0
def search(request):
    if request.method == 'GET':
        form = UserForm(request.GET, request.FILES)
        if form.is_valid():
            id_user = form.cleaned_data['id']
            user = get_object_or_404(User, pk=id_user)
            return render(request, 'ratedPeripherals.html', {'user': user})
    form = UserForm()
    return render(request, 'searchUser.html', {'form': form})
Example #13
0
def search(request):
    if request.method == 'GET':
        form = UserForm(request.GET, request.FILES)
        if form.is_valid():
            idUser = form.cleaned_data['id']
            user = get_object_or_404(UserInformation, pk=idUser)
            return render(request, 'ratedFilms.html', {'usuario': user})
    form = UserForm()
    return render(request, 'search_user.html', {'form': form})
Example #14
0
def form_user(request):
    if request.method == 'POST':
        form = UserForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/')
    else:
        form = UserForm()
    return render(request, "main/form_user.html", {'form': form})
Example #15
0
def register(request):

    # A boolean value for telling the template whether the registration was successful.
    # Set to False initially. Code changes value to True when registration succeeds.
    registered = False

    # If it's a HTTP POST, we're interested in processing form data.
    if request.method == 'POST':
        # Attempt to grab information from the raw form information.
        # Note that we make use of both UserForm and UserProfileForm.
        user_form = UserForm(data=request.POST)
        profile_form = UserProfileForm(data=request.POST)

        # If the two forms are valid...
        if user_form.is_valid() and profile_form.is_valid():
            # Save the user's form data to the database.
            user = user_form.save()

            # Now we hash the password with the set_password method.
            # Once hashed, we can update the user object.
            user.set_password(user.password)
            user.save()

            # Now sort out the UserProfile instance.
            # Since we need to set the user attribute ourselves, we set commit=False.
            # This delays saving the model until we're ready to avoid integrity problems.
            profile = profile_form.save(commit=False)
            profile.user = user

            # Did the user provide a profile picture?
            # If so, we need to get it from the input form and put it in the UserProfile model.
            if 'picture' in request.FILES:
                profile.picture = request.FILES['picture']

            # Now we save the UserProfile model instance.
            profile.save()

            # Update our variable to tell the template registration was successful.
            registered = True

        # Invalid form or forms - mistakes or something else?
        # problems to the terminal.
        # They'll also be shown to the user.
        else:
            print user_form.errors, profile_form.errors

    # Not a HTTP POST, so we render our form using two ModelForm instances.
    # These forms will be blank, ready for user input.
    else:
        user_form = UserForm()
        profile_form = UserProfileForm()

    # Render the template depending on the context.
    return render(request,
            'main/register.html',
            {'user_form': user_form, 'profile_form': profile_form, 'registered': registered} )
 def test_user_create_form_valid(self):
     form = UserForm(
         data={
             'first_name': 'Osama',
             'last_name': 'Aboukoura',
             'username': '******',
             'email': '*****@*****.**',
             'password': '******'
         })
     self.assertTrue(form.is_valid())
Example #17
0
def puntuacionesUsuarios(request):
    if request.method == 'GET':
        form = UserForm(request.GET, request.FILES)
        if form.is_valid():
            idUser = form.cleaned_data['id']
            rating = Rating.objects.filter(user=idUser)
            animes = Anime.objects.all()
            return render(request, 'ratedAnimes.html', {'idUser': idUser, 'puntuaciones': rating, 'animes': animes})
    form = UserForm()
    return render(request, 'search_user.html', {'form': form})
Example #18
0
def search(request):
    if request.method == 'GET':
        form = UserForm(request.GET, request.FILES)
        if form.is_valid():
            idUser = form.cleaned_data['id']
            rating = Rating.objects.filter(user=idUser)
            libros = Book.objects.all()
            return render(request, 'ratedBooks.html', {'idUser': idUser, 'puntuaciones': rating, 'libros': libros})
    form = UserForm()
    return render(request, 'search_user.html', {'form': form})
def add_user(request):
	form = UserForm()
	if request.method == 'POST':
		form = UserForm(request.POST,request.FILES)
		if form.is_valid():
			form.save()
			return redirect('home')
	return render_to_response('add_user.html', {
		'form': form,
	}, RequestContext(request))
Example #20
0
def entrenarDatos(request):
    if request.method == 'GET':
        form = UserForm(request.GET, request.FILES)
        if form.is_valid():
            guardarEntrenamiento(str(form.cleaned_data['id']))

    else:
        form = UserForm()
    return render_to_response('entrenarDatos.html', {'form': form},
                              context_instance=RequestContext(request))
Example #21
0
def sign_up(request):
    form = UserForm
    if request.method == 'POST':
        form = UserForm(request.POST)
        if form.is_valid():
            user = form.save()
            Profile.objects.create(user=user)
            return redirect('log_in')
    return render_to_response('sign_up.html', {
        'form': form, },
        RequestContext(request))
Example #22
0
def edit_user(request, pk):
	user = get_object_or_404(User, pk=pk)
	form = UserForm(instance=user)
	if request.method =='POST':
		form = UserForm(request.POST, instance=user)
		if form.is_valid():
			form.save()
			return redirect('home')
	return render_to_response('add_user.html',{
		'form': form,
	}, RequestContext(request))
Example #23
0
def editUser(request):
    us = None
    user_id = request.session['user']
    if user_id != -1:
        us = User.objects.get(id=user_id)
        form = UserForm(request.POST or None, instance=us)
    if form.is_valid():
        form.save()
        return redirect('/')
    else:
        return render_to_response('user.html', RequestContext(request, {'formset': form}))
Example #24
0
 def post(self, request, pk):
     form = UserForm(data=request.POST, instance=request.user)
     if form.is_valid():
         User.objects.filter(pk=pk).update(
             username=form.cleaned_data['username'],
             first_name=form.cleaned_data['first_name'],
             last_name=form.cleaned_data['last_name'],
             email=form.cleaned_data['email'])
         user = User.objects.get(pk=pk)
         return redirect('user', user.id)
     else:
         return render(request, 'main/user_form.html', {'form': form})
Example #25
0
def searchByUser(request):
    if request.method == 'GET':
        form = UserForm(request.GET, request.FILES)
        if form.is_valid():
            nombre = form.cleaned_data['name']
            usuario = get_object_or_404(User, name=nombre)
            print usuario
            return render_to_response('ratedFilms.html', {'usuario': usuario},
                                      context_instance=RequestContext(request))
    else:
        form = UserForm()
    return render_to_response('search_user.html', {'form': form},
                              context_instance=RequestContext(request))
 def test_user_create_form_invalid(self):
     form = UserForm(
         data={
             'first_name': 'Osama',
             'last_name':
             '',  # this should cause an error: invalid last name.
             'username': '******',
             'email':
             'osama.aboukoura@',  # this should cause an error: invalid email.
             'password': '******'
         })
     self.assertFalse(form.is_valid())  # an invalid form
     self.assertEquals(len(form.errors),
                       2)  # total number of errors in the form.
Example #27
0
def player_form(request):
    if request.method == 'POST':
        user_form = UserForm(request.POST)
        player_form = PlayerForm(request.POST)
        if all((user_form.is_valid(), player_form.is_valid())):
            new_user = user_form.save()
            new_player = player_form.save(commit=False)
            new_player.user = new_user
            new_player.save()
            return HttpResponseRedirect('/playerform/')
    else:
        user_form = UserForm()
        player_form = PlayerForm()
    return render(request, 'main/player_form.html',
                  {'user_form': user_form, 'player_form': player_form})
Example #28
0
    def post(self, request, *args, **kwargs):
        self.object = None

        form = self.get_form()
        form_user = UserForm(request.POST)
        form_basic = PersonForm_Basic(request.POST)
        form_personal = PersonForm_Personal(request.POST)
        form_contact = PersonForm_Contact(request.POST)
        form_ecclesiastic = PersonForm_Ecclesiastic(request.POST)

        if form_basic.is_valid() and form_user.is_valid() and form_personal.is_valid() and form_contact.is_valid() and \
                form_ecclesiastic.is_valid():
            return self.form_valid(form, form_user, form_basic)
        else:
            return self.form_invalid(form_basic, form_user, form_personal, form_contact, form_ecclesiastic)
Example #29
0
def profile(request, template='main/account/profile.html'):
    
    instance = request.user.driver.car if hasattr(request.user,'driver') and hasattr(request.user.driver,'car') else None
    userform   = UserForm(prefix='user', instance=request.user)
    if request.method == "POST":
        
        userform   = UserForm(request.POST, prefix='user', instance=request.user)
        if userform.is_valid():
            user = userform.save()

        messages.info(request, _("Your personal page has been updated!"))
    
        
    context = {"userform": userform}
    return render(request, template, context)
Example #30
0
def register(request):
    form = UserForm(request.POST or None)
    if form.is_valid():
        username = form.cleaned_data.get("username")
        des = form.cleaned_data.get("designation")
        form.save()
        if des == "1":
            UserCategory.objects.create(user_category=form.instance,
                                        is_patient=True)
        elif des == "2":
            UserCategory.objects.create(user_category=form.instance,
                                        is_doctor=True)

        messages.success(request, f"Account created for {username}")
        return redirect("main:home")
    return render(request, "register.html", {"form": form})
Example #31
0
def register(request):
    registered = False
    
    if request.method == "POST":
        user_form = UserForm(data = request.POST)

        if user_form.is_valid():
            user = user_form.save()
            user.set_password(user.password)
            user.save()
            registered = True
    else:
        user_form = UserForm()

    context_dict = {'user_form' : user_form,'registered' : registered}
    return render(request, 'main/register.html', context_dict)
Example #32
0
def profile_edit(request):
    user = request.user

    if request.method == "POST":
        form = UserForm(request.POST)
        if form.is_valid():
            user.first_name = form.cleaned_data['first_name']
            user.last_name = form.cleaned_data['last_name']
            user.email = form.cleaned_data['email']
            user.save()

            return HttpResponseRedirect( reverse( 'main.views.home_profile' ) )
        
    else:
        form = UserForm(initial={'first_name':user.first_name,'last_name':user.last_name,'email':user.email})

    return render_to_response('main/profile_edit.html', {'form':form,'dance':dance})
Example #33
0
def edit_profile(request):
    profile = request.user.get_profile()
    user_form = UserForm(instance=request.user)
    userprofile_form = UserProfileForm(instance=profile)
    if request.method == 'POST':
        user_form = UserForm(request.POST, instance=request.user)
        userprofile_form = UserProfileForm(request.POST, instance=profile)

        if user_form.is_valid() and userprofile_form.is_valid():
            #assert False, (user_form.cleaned_data, request.user, user_form.save())
            user_form.save()
            userprofile_form.save()
            return redirect('sesion')
    return render_to_response('editprofile.html', {
        'user_form': user_form,
        'userprofile_form': userprofile_form,
    }, RequestContext(request))
Example #34
0
def update_profile(request):
    if request.method == 'POST':
        user_form = UserForm(request.POST, instance=request.user)
        profile_form = ProfileForm(request.POST, instance=request.user.profile)
        # image_form=ImageUploadForm(request.POST)
        if user_form.is_valid() and profile_form.is_valid() and image_form.is_valid():
            user_form.save()
            profile_form.save()
            # m = ExampleModel.objects.get(pk=course_id)
            # m.model_pic = image_form.cleaned_data['image']
            # m.save()
#            messages.success(request, _('Your profile was successfully updated!'))
            return redirect('home')
#        else:
#             messages.error(request, _('Please correct the error below.'))
    else:
        user_form = UserForm(instance=request.user)
        profile_form = ProfileForm(instance=request.user.profile)
        # image_form=ImageUploadForm()
    return render(request, 'profile.html', {
        'user_form': user_form,
        'profile_form': profile_form,
        # 'image_form': image_form
    })

# def upload_pic(request):
#     if request.method == 'POST':
#         form = ImageUploadForm(request.POST, request.FILES)
#         if form.is_valid():
#             m = ExampleModel.objects.get(pk=course_id)
#             m.model_pic = form.cleaned_data['image']
#             m.save()
#             return HttpResponse('image upload success')
#     return HttpResponseForbidden('allowed only via POST')
Example #35
0
def home_submit(request):

    user = User.objects.get(pk=1)

    if request.method == 'POST':
        keywordform = KeywordForm(data=request.POST, prefix='keyword')
        userform = UserForm(data=request.POST, instance=user)
        userprofileform = UserProfileForm(data=request.POST, instance=user.userprofile, prefix='userprofile')

        if keywordform.is_valid():
            keywordform.save()

        if  userprofileform.is_valid():
            user = userform.save()
            profile = userprofileform.save()
            result = {'status': 'Update Succesfull'}

    return HttpResponseRedirect('/')
Example #36
0
def entrenarDatos(request):
    if request.method == 'GET':
        form = UserForm(request.GET, request.FILES)
        if form.is_valid():
            entrenamientoDatos(str(form.cleaned_data['id']))

            conn = sqlite3.connect('carnaval.db')
            cursor = conn.execute("SELECT distinct NOTICIA FROM ENTRENAMIENTO")
            res = []
            for registro in cursor:
                res.append(registro[0])

            return render_to_response('entreno.html', {'noticiasssss': res},
                                      context_instance=RequestContext(request))
    else:
        form = UserForm()
    return render_to_response('entrenarDatos.html', {'form': form},
                              context_instance=RequestContext(request))
Example #37
0
def recommendedFilms(request):
    if request.method=='GET':
        form = UserForm(request.GET, request.FILES)
        if form.is_valid():
            idUser = form.cleaned_data['id']
            user = get_object_or_404(UserInformation, pk=idUser)
            shelf = shelve.open("dataRS.dat")
            Prefs = shelf['Prefs']
            SimItems = shelf['SimItems']
            shelf.close()
            rankings = getRecommendedItems(Prefs, SimItems, int(idUser))
            recommended = rankings[:2]
            items = []
            for re in recommended:
                item = Film.objects.get(pk=re[1])
                items.append(item)
            return render(request,'recommendationItems.html', {'user': user, 'items': items})
    form = UserForm()
    return render(request,'search_user.html', {'form': form})
Example #38
0
def test_edit_other_user(django_user_model):
    user_1 = django_user_model.objects.create(username='******')
    user_1.set_password('takeajacket')
    user_1.profile.about = 'Built a wall.'
    user_1.save()
    user_2 = django_user_model.objects.create(username='******')
    form_data = {
        'username': '******',
        'about': 'Watching Grease',
    }
    form = UserForm(data=form_data)
    assert form.is_valid()
    c = Client()
    logged_in = c.login(username='******', password='******')
    assert logged_in
    response = c.post('/@' + user_2.username + '/edit/',
                      form_data,
                      follow=True)
    assert response.status_code == 403
Example #39
0
def user_page(request):
    if request.method == 'POST':
        form = UserForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return render(request, 'thanks_page.html')
    else:
        form = UserForm()
    return render(request, 'main_page.html', {'form': form})
Example #40
0
def recommendedBooksUser(request):
    if request.method=='GET':
        form = UserForm(request.GET, request.FILES)
        if form.is_valid():
            idUser = form.cleaned_data['id']
            user = get_object_or_404(Usuario, pk=idUser)
            shelf = shelve.open("dataRS.dat")
            Prefs = shelf['Prefs']
            shelf.close()
            rankings = getRecommendations(Prefs,int(idUser))
            recommended = rankings[:2]
            books = []
            scores = []
            for re in recommended:
                books.append(Libro.objects.get(pk=re[1]))
                scores.append(re[0])
            items= zip(books,scores)
            return render(request,'recommendationItems.html', {'user': user, 'items': items})
    form = UserForm()
    return render(request,'search_user.html', {'form': form})
Example #41
0
def usuariosParecidos(request):
    punt = None
    if request.method == 'GET':
        form = UserForm(request.GET, request.FILES)
        if form.is_valid():
            idUser = form.cleaned_data['id']
            punt = Rating.objects.filter(user=idUser)
            shelf = shelve.open("dataRS.dat")
            ItemsPrefs = shelf['Prefs']
            shelf.close()
            recommended = topMatches(ItemsPrefs, int(idUser), n=3)
            users = []
            similar = []
            for re in recommended:
                users.append(Rating.objects.filter(user=re[1]).first())
                similar.append(re[0])
            items = zip(users, similar)
            return render(request, 'similarUsers.html', {'idUser':idUser,'punt': punt, 'users': items})
    form = UserForm()
    return render(request, 'search_user.html', {'form': form})
Example #42
0
def __create_user_view_get(request):
    form = (fEMRAdminUserForm() if request.user.groups.filter(
        name="fEMR Admin").exists() else UserForm())
    return render(
        request,
        "admin/user_create_form.html",
        {
            "error": "",
            "form": form
        },
    )
Example #43
0
def register(request):
    if request.method == 'POST':
        form = UserForm(request.POST)
        try:
            user = form.save(commit=False)
        except ValueError:
            request.message = 'There\'s a problem with the information. May be the ' \
                              'email is taken or password is not strong enough.'
            return render(
                request, 'form.html', {
                    'form': form,
                    'message': request.message,
                    'form_action': '/main/register'
                })
        raw_password = user.password
        user.password = User.hash(user.password)
        if user.save():
            request.message = 'Successfully registered.'
            authenticated_user = authenticate(username=user.email,
                                              password=raw_password)
            if authenticated_user is not None:
                auth.login(
                    request,
                    user=authenticated_user,
                    backend=
                    'main.authentication_backends.ForsatAuthenticationBackend')
            return panel(request)
        else:
            request.message = 'There\'s a problem with the information. May be the ' \
                              'email is taken or password is not strong enough.'
    else:
        form = UserForm()
    if hasattr(request, 'message'):
        message = request.message
    else:
        message = None
    return render(request, 'form.html', {
        'form': form,
        'message': message,
        'form_action': '/main/register'
    })
Example #44
0
def crear_usuario(request):
    '''
    Metodo ajax que retorna el formulario de registro de los usuarios o ejecuta la accion de guardar
    '''

    if request.method == 'POST':
        form = UserForm(request.POST)
        if form.is_valid():
            # us = User()
            # us.email =
            # us.username = form.cleaned_data['username']
            # us.fk_rol_codigo = form.cleaned_data['rol']
            # us.fk_sucursal_codigo = form.cleaned_data['sucursal']
            # us.cl_estado=form.cleaned_data['estado']

            ps = form.cleaned_data['password1']
            # us.password = hashers.make_password(ps)

            User.objects.create(email=form.cleaned_data['email'],
                                pk_codigo=form.cleaned_data['codigo'],
                                username=form.cleaned_data['username'],
                                fk_rol_codigo=form.cleaned_data['rol'],
                                fk_sucursal_codigo= form.cleaned_data['sucursal'],
                                cl_estado=form.cleaned_data['estado'],
                                is_active=form.cleaned_data['estado'],
                                password=hashers.make_password(ps)
                                )

            messages.add_message(request, messages.SUCCESS,'El usuario ha sido registrado con exito')
            context = {
                'form': form
            }
            return redirect('usuarios')

    elif request.method == 'GET':
        form = UserForm(initial={'estado':False})
        context = {
            'form': form
        }
        html = render_to_string('admin/usuarios/crear.html', context, request=request)
        return JsonResponse({'html_form': html})
Example #45
0
def res_new(request):
    if request.method == 'POST':
        form = UserForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('restaurants')
    else:
        form = UserForm()
    context = {'form': form}
    return render(request, 'new.html', context)
Example #46
0
def users_edit(request, pk):
    """Edit an user"""

    try:
        object = User.objects.get(pk=pk)
    except:
        object = User()

    if request.method == 'POST':  # If the form has been submitted...
        form = UserForm(request.POST, instance=object)

        if form.is_valid():  # If the form is valid
            object = form.save()

            messages.success(request, 'The user has been saved.')

            return redirect(reverse('main.views.users_list'))
    else:
        form = UserForm(instance=object)

    return render_to_response('main/users/edit.html', {'form': form}, context_instance=RequestContext(request))
Example #47
0
 def post(self, request):
     form = UserForm(request.POST)
     if form.is_valid():
         form.save()
         form = UserForm()
     args = {
         'users': self.model.objects.all().order_by('-id'),
         'user_form': form,
     }
     return render(request, self.template_name, args)
Example #48
0
def register(request):
    registered = False
    if request.method == 'POST':
        user_form = UserForm(request.POST)
        profile_form = UserProfileForm(request.POST)
        
        if user_form.is_valid() and profile_form.is_valid():
            user = user_form.save()
            user.set_password(user.password)
            user.save()
            
            profile = profile_form.save(commit=False)
            profile.user = user
            
            profile.save()
            registered = True
        else:
            print(user_form.errors, profile_form.errors)
    else:
        user_form = UserForm()
        profile_form = UserProfileForm()
    
    context_dict={}
    context_dict['user_form'] = user_form
    context_dict['profile_form'] =  profile_form
    context_dict['registered'] = registered
    
    response = render(request, 'main/signup.html', context_dict)
    return response
Example #49
0
def signup(request, backend, success_url=None, extra_context=None):
    disallowed_url = 'registration_disallowed'
    backend = get_backend(backend)

    if not backend.registration_allowed(request):
        return redirect(disallowed_url)

    if request.method == 'POST':
        user_form = UserForm(request.POST)
        signup_form = SignupForm(request.POST)

        if user_form.is_valid() and signup_form.is_valid():
            new_user = backend.register(request, **user_form.cleaned_data)
            profile = signup_form.save(commit=False)
            profile.user = new_user
            profile.save()
            if success_url is None:
                to, args, kwargs = backend.post_registration_redirect(request, new_user)
                return redirect(to, *args, **kwargs)
            else:
                return redirect(success_url)
    else:
        user_form = UserForm()
        signup_form = SignupForm()
    
    if extra_context is None:
        extra_context = {}
    context = RequestContext(request)
    for key, value in extra_context.items():
        context[key] = callable(value) and value() or value

    return render_to_response(
        'signup.html',
        {
            'user_form': user_form,
            'signup_form': signup_form
        },
        context_instance=context)
Example #50
0
def signup(request, backend, success_url=None, extra_context=None):
    disallowed_url = 'registration_disallowed'
    backend = get_backend(backend)
    success_url = reverse('registration_complete')
    if not backend.registration_allowed(request):
        return redirect(disallowed_url)

    if request.method == 'POST':
        data = request.POST.copy()
        data['username'] = data.get('email')
        form = UserForm(data)
        if form.is_valid() :
            form.cleaned_data['username'] = form.cleaned_data.get('email')
            new_user = backend.register(request, **form.cleaned_data)
            new_user.first_name = form.cleaned_data.get('first_name')
            new_user.last_name = form.cleaned_data.get('last_name')
            new_user.groups.add(2)
            new_user.save()

            if success_url is None:
                to, args, kwargs = backend.post_registration_redirect(request, new_user)
                return redirect(to, *args, **kwargs)
            else:
                return redirect(success_url)
    else:
        form = UserForm()
    
    if extra_context is None:
        extra_context = {}
    context = RequestContext(request)
    for key, value in extra_context.items():
        context[key] = callable(value) and value() or value

    return render_to_response('registration/registration_form.html', {
            'form': form,
    }, context_instance=context)