Пример #1
0
    def authenticate(self, oauth_token, fb_id, name, user_id=None):
        """Authenticates user via Facebook API and saves user information.
        """
        try:
            # Find existing user
            facebook_user = FacebookProfile.objects.get(pk=fb_id, name=name)
            user = facebook_user.user

            # Update user's access token
            facebook_user.oauth_token = oauth_token
            facebook_user.save()
            
            # Set last visit to now
            user.userprofile.last_visit_date = datetime.now()
            user.userprofile.save()

        except FacebookProfile.DoesNotExist: # If requested user has not yet been registered
            # Create or get User and add FacebookProfile
            if user_id == None:
                user = User.objects.create_user(fb_id)
                user.save()
            
                # Create UserProfile to hold information
                userprofile = UserProfile(user=user)
                userprofile.save()
            
            else:
                user = User.objects.get(pk=user_id)

            facebook_user = FacebookProfile(user=user, pk=fb_id, oauth_token=oauth_token)
            facebook_user.save()

        return user
Пример #2
0
    def test_models_entry(self):
        # Sets a User instance.
        user1 = User()
        user1.save()

        up = UserProfile(user=user1,
                         full_name="bob smith",
                         phone_number=134256748,
                         street_address1="test1",
                         street_address2="test2",
                         postcode="po2099",
                         town_city="town",
                         country="Country",
                         employee=False,
                         image="image.jpg")
        up.save()

        self.assertEqual(up.user, user1)
        self.assertEqual(up.full_name, "bob smith")
        self.assertEqual(up.phone_number, 134256748)
        self.assertEqual(up.street_address1, "test1")
        self.assertEqual(up.street_address2, "test2")
        self.assertEqual(up.postcode, "po2099")
        self.assertEqual(up.town_city, "town")
        self.assertEqual(up.country, "Country")
        self.assertEqual(up.employee, False)
        self.assertEqual(up.image, "image.jpg")
Пример #3
0
def get_or_create_profile(user):
    try:
        profile = user.get_profile()
    except ObjectDoesNotExist:
        profile = UserProfile(user=user)
        profile.save()
    return profile
Пример #4
0
    def setUp(self):
        self.feed = Feed(link="http://link.to/rss.xml",
                         title="A Feed")
        self.feed.save()

        # Create an entry
        published = datetime.datetime(2013, 9, 25, 4, 0)
        published = published.timetuple()
        self.entry1 = FeedParserEntry(title="An Entry",
                                      link="http://entry",
                                      published_parsed=published)

        # Create another entry
        published = datetime.datetime(2013, 9, 28, 4, 0)
        published = published.timetuple()
        self.entry2 = FeedParserEntry(title="Another Entry",
                                      link="http://another/entry",
                                      published_parsed=published)

        # Create users
        user1 = User(username="******")
        user1.save()
        self.profile1 = UserProfile(user=user1)
        self.profile1.save()

        user2 = User(username="******")
        user2.save()
        self.profile2 = UserProfile(user=user2)
        self.profile2.save()
Пример #5
0
    def save(self, profile_callback=None):
        new_user = RegistrationProfile.objects.create_inactive_user(username=self.cleaned_data['username'],
        password=self.cleaned_data['password1'],
        email=self.cleaned_data['email'])

        new_profile = UserProfile(user=new_user)
        new_profile.save()

        return new_user
Пример #6
0
 def create_user(self, username):
     ben = User.objects.create_user(username, "*****@*****.**" % username, username)
     ben.set_password(username)
     ben.save()
     ben_profile = UserProfile(user=ben)
     ben_profile.save()
     ben.reputation = Reputation(user=ben)
     ben.reputation.save()        
     return ben
Пример #7
0
    def create_user(self, username, email, password):
        '''
		'''
        try:
            user = User.objects.filter(username__iexact=username)
        except:
            user = None
        if user:
            return False

        try:
            user = User.objects.filter(email__iexact=email)
        except:
            user = None
        if user:
            return False

        try:
            user = UserProfile.objects.filter(email_unconfirmed__iexact=email)
        except:
            user = None
        if user:
            return False

        try:
            new_user = User.objects.create_user(username=username,
                                                password=password)
            new_user.is_active = False
            new_user.save()
        except:
            return False

        confirm_key = generate_sha1()
        account = self.create(user=new_user, \
                  confirm_key=confirm_key, \
                  confirm_key_creat_time = now(), \
                  email_unconfirmed = email, \
                  last_active = now())
        account.send_confirm_email()

        profile = UserProfile(user=new_user)
        try:
            anonymous = User.objects.get(pk=ANONYMOUS_ID)
        except:
            anonymous = self.create_anonymous()
        profile.avatar = anonymous.userprofile.avatar
        profile.username = username
        profile.save()

        # print 'send create_user_done signal'
        # create_user_done.send(sender='UserAccount', user=new_user)
        filename = get_gravatar(account.email_unconfirmed)
        if filename:
            avatar = Avatar()
            avatar.avatar_save(filename)
            remove(filename)
            profile.avatar = avatar
            profile.save()

        return new_user
Пример #8
0
    def _make_test_profile():

        test_profile = UserProfile(
            created_by=make_test_user,
            username= '******',
            bio= 'this is a bio and its going to be outrageous',
            avatar= 'a picture here',

            )
        test_profile.save()
        test_profile.skills.add(make_skill)
        return test_profile
Пример #9
0
 def register_new_board(self, subdomain, name, description, user):
     board = Board(subdomain = subdomain, name = name, description = description, owner = user)
     board.save()
     from emailsubs.models import EmailSent
     email_sent = EmailSent(board =  board)
     email_sent.save()
     from profiles.models import UserProfile
     user_profile = UserProfile(user = user)
     user_profile.save()
     board_extended_settings = BoardExtendedSettings(board = board)
     board_extended_settings.save()
     JobFormModel.objects.create_default_form(board = board)
     return board
Пример #10
0
    def register(self, request, **kwargs):
        username, email, password = kwargs['username'], kwargs[
            'email'], kwargs['password1']
        if Site._meta.installed:
            site = Site.objects.get_current()
        else:
            site = RequestSite(request)
        new_user = RegistrationProfile.objects.create_inactive_user(
            username, email, password, site)
        signals.user_registered.send(sender=self.__class__,
                                     user=new_user,
                                     request=request)

        user = User.objects.get(username=new_user.username)
        user.first_name = kwargs['first_name']
        user.last_name = kwargs['last_name']
        user.save()
        new_profile = UserProfile(user=user)
        new_profile.fiscal_code = kwargs['fiscal_code']
        new_profile.telephone = kwargs['telephone']
        new_profile.area = kwargs['area']
        new_profile.personal_data = kwargs['personal_data']
        new_profile.save()

        return new_user
Пример #11
0
def create_user_profile(sender, instance, created, **kwargs):
    """
    A simple post_save signal tied to ``django.contrib.auth.User`` that 
    automatically creates a ``UserProfile`` linked to a new user.
    """
    if created:
        # Check to see if a profile with this user already exists
        # We have to do this just in case the signal gets fired twice
        # And catching IntegrityError is not properly supported yet
        try:
            UserProfile._default_manager.get(user=instance)
        except UserProfile.DoesNotExist:
            up = UserProfile(user=instance)
            up.save()
Пример #12
0
	def create_user(self, username, email, password):
		'''
		'''
		try:
			user = User.objects.filter(username__iexact=username)
		except:
			user = None
		if user:
			return False
			
		try:
			user = User.objects.filter(email__iexact=email)
		except:
			user = None
		if user:
			return False
		
		try:
			user = UserProfile.objects.filter(email_unconfirmed__iexact = email)
		except:
			user = None
		if user:
			return False
		
		try:
			new_user = User.objects.create_user(username=username, password=password)
			new_user.is_active = False
			new_user.save()
		except:
			return False
		
		confirm_key = generate_sha1()
		account = self.create(user=new_user, \
		          confirm_key=confirm_key, \
		          confirm_key_creat_time = now(), \
		          email_unconfirmed = email, \
		          last_active = now())
		account.send_confirm_email()
		
		profile = UserProfile(user=new_user)
		try:
			anonymous = User.objects.get(pk=ANONYMOUS_ID)
		except:
			anonymous = self.create_anonymous()
		profile.avatar = anonymous.userprofile.avatar
		profile.username = username
		profile.save()
		
		# print 'send create_user_done signal'
		# create_user_done.send(sender='UserAccount', user=new_user)
		filename = get_gravatar(account.email_unconfirmed)
		if filename:
			avatar = Avatar()
			avatar.avatar_save(filename)
			remove(filename)
			profile.avatar = avatar
			profile.save()
		
		return new_user
Пример #13
0
def favourites(request):
    current_user = {'user': request.user}
    if request.method == 'POST':
        id_product = request.POST['id_product']
        product = Product.objects.filter(id=id_product)
        new_favourite = UserProfile(current_user, product)
    return render(request, 'favourites/favourites.html', current_user)
Пример #14
0
def create_profile(sender, instance, signal, created, **kwargs):
    """When user is created also create a matching profile."""
 
    from profiles.models import UserProfile
 
    if created:
        UserProfile(user = instance).save()
Пример #15
0
 def save(self, commit=True, request=None, **kwargs):
     # The field clean method (or something) checks that the username
     # isn't already taken.
     new_user = super().save(commit=False)
     new_user.set_password(self.cleaned_data['username'])
     new_user.email = self.cleaned_data['email_address']
     coop = request.user.profile.coop
     try:
         profile = new_user.profile
         profile_already_there = True
     except UserProfile.DoesNotExist:
         profile = UserProfile(
             user=new_user,
             coop=coop,
             public_calendar=True,
             points_steward=False,
             birthday=None,
         )
         profile_already_there = False
     profile.nickname      = self.cleaned_data['nickname']
     profile.email_address = self.cleaned_data['email_address']
     profile.presence      = self.cleaned_data['presence']
     profile.share         = self.cleaned_data['share']
     #TODO: this could result in orphaned profiles if `save` is called
     #with `commit` equal to `False` and the returned `new_user` isn't
     #later saved.
     #TODO: using `profile_already_there` to try to avoid this. Bad.
     if profile_already_there:
         #This gets run when editing.
         profile.save()
     else:
         #This gets run when creating.
         pass
     #TODO: Unsure this is consistent with how other forms use `commit`.
     if commit:
         #Avoid saving twice.
         new_user.save()
         if not profile_already_there:
             profile.user = new_user
             profile.save()
         coop.user_set.add(new_user)
     # TODO: email new user here with instructions. CC steward (maybe
     # just CC the person who made the request, to allow for other
     # people to create users in the future).
     return new_user
Пример #16
0
 def generate_user_profile(self, user):
     user_profile = UserProfile()
     user_profile.user = user
     user_profile.gender = 'M'
     user_profile.birthday = '1985-05-21'
     user_profile.save()
     return user_profile
Пример #17
0
def register(request):
    data = json.loads(request.raw_post_data)

    user = User(username=data["username"],
                first_name=data["firstname"],
                last_name=data["lastname"],
                email=data["email"])

    user.set_password(data["password"])
    user.save()

    user.reputation = Reputation(user=user)
    user.reputation.save()

    profile = UserProfile(user=user,zip_code=data["zipcode"],active=True)
    profile.save()

    return { "status": "success", "id": user.pk }
Пример #18
0
 def save(self, **kwargs):
     super(Post, self).save(**kwargs)
     # Add UserTags
     for user in UserProfile.auto_tag(self.text_content):
         user_profile = UserProfile.objects.get(user=user)
         UserTag(user_profile=user_profile, post=self).save()
     # Save tags
     for tag in Tag.extract(self.text_content):
         PostTag(post=self, tag=tag).save()
Пример #19
0
	def create_anonymous(self):
		'''
		'''
		anonymous = User(id=ANONYMOUS_ID, \
		                 username=ANONYMOUS_USERNAME, \
		                 password=ANONYMOUS_PASSWORD) # this password will 
		                                              # never be used!
		anonymous.save()
		avatar = Avatar()
		avatar.avatar_save(MEDIA_ROOT + ANONYMOUS_USERNAME + '.jpg')
		
		profile = UserProfile(user=anonymous)
		profile.avatar=avatar
		profile.name = ANONYMOUS_NAME
		profile.save()
		
		# there while add some other thing
		
		return anonymous
Пример #20
0
def user_registered_callback(sender, user, request, **kwargs):
    """
    Save name to user and automatically create shed and profile named
    """
    user.first_name = request.POST["first_name"]
    user.last_name = request.POST["last_name"]
    user.save()
    shed = Shed(name="%s's home" % user.username,
                owner=user,
                street=request.POST["street"],
                city=request.POST["city"],
                state=request.POST["state"],
                postal_code=request.POST["postal_code"])
    shed.save()
    profile = UserProfile(user=user, home_shed=shed)
    stats = Stats()
    stats.save()
    profile.stats = stats
    profile.save()
Пример #21
0
def checkout_confirm(request, order_number):
    """
    Handle successful checkouts
    """
    save_info = request.session.get('save_info')
    order = get_object_or_404(Order, order_number=order_number)

    if request.user.is_authenticated:
        profile = UserProfile.objects.get(user=request.user)
        # Attach the user's profile to the order
        order.user_profiles = profile
        order.save()

        # Save the user's info
        if save_info:
            profile_data = {
                'default_phone_number': order.phone_number,
                'default_country': order.country,
                'default_postcode': order.postcode,
                'default_town_or_city': order.town_or_city,
                'default_street_address1': order.street_address1,
                'default_street_address2': order.street_address2,
                'default_county': order.county,
            }
            user_profile_form = UserProfile(profile_data, instance=profile)
            if user_profile_form.is_valid():
                user_profile_form.save()

    messages.success(
        request, f'Order successfully processed! \
        Your order number is {order_number}. A confirmation \
        email will be sent to {order.email}.')

    if 'bag' in request.session:
        del request.session['bag']

    template = 'checkout/checkout_confirm.html'
    context = {
        'order': order,
    }

    return render(request, template, context)
Пример #22
0
    def get_context_data(self, *args, **kwargs):
        context = super(FAQSectionDetailView, self).get_context_data(**kwargs)

        # add the viewer's profile to this view
        self.viewer_profile = UserProfile.get_profile(self.request.user)

        valid_access_levels = access_levels(None, self.viewer_profile)
        context["faqsection_items"] = filter_access_levels(
            self.object.faqitem_set.all(), "access", valid_access_levels)

        return context
Пример #23
0
def user_registered_callback(sender, user, request, **kwargs):
    """
    Save name to user and automatically create shed and profile named
    """
    user.first_name = request.POST["first_name"]
    user.last_name = request.POST["last_name"]
    user.save()
    shed = Shed( 
            name= "%s's home" % user.username,
            owner=user,
            street=request.POST["street"],
            city=request.POST["city"],
            state=request.POST["state"],
            postal_code=request.POST["postal_code"]
        )
    shed.save()
    profile = UserProfile(user=user, home_shed=shed)
    stats = Stats()
    stats.save()
    profile.stats = stats
    profile.save()
Пример #24
0
 def create(self, validated_data):
     user = UserProfile(phone_number=validated_data['phone_number'],
                        name=validated_data['name'],
                        organisation=validated_data['organisation'])
     user.set_password(validated_data['password'])
     user.save()
     return user
Пример #25
0
 def register(self, request, **kwargs):
     new_user = super(TreeBackend, self).register(request, **kwargs)
     new_user.first_name = kwargs['first_name']
     new_user.last_name = kwargs['last_name']
     new_user.save()
     try:
         profile = new_user.get_profile()
     except:
         profile = UserProfile(user=new_user)
     profile.zip_code = kwargs.get('zip_code')
     profile.volunteer = kwargs.get('volunteer')
     profile.updates = kwargs.get('updates')
     profile.photo = kwargs.get('photo')
     profile.save()
     return new_user
Пример #26
0
    def authenticate(self, oauth_token, oauth_token_secret, screen_name, user_id=None):
        """Receives the callback from twitter api and gets user information"""
        try:
            # Find existing user
            twitter_user = TwitterProfile.objects.get(screen_name=screen_name)
            user = twitter_user.user

            # Update user's access token
            twitter_user.oauth_token=oauth_token
            twitter_user.oauth_secret=oauth_token_secret
            twitter_user.save()

            # Set last visit to now
            user.userprofile.last_visit_date = datetime.now()
            user.userprofile.save()

        except TwitterProfile.DoesNotExist: # If requested user has not yet been registered
            # Create or get User and add TwitterProfile
            if user_id == None:
                user = User.objects.create_user(screen_name)
                user.save()

                # Create UserProfile to hold information
                userprofile = UserProfile(user=user)
                userprofile.save()

            else:
                user = User.objects.get(pk=user_id)

            # Create TwitterProfile and add user and token
            twitter_user = TwitterProfile(
                user=user,
                screen_name=screen_name,
                oauth_token=oauth_token,
                oauth_secret=oauth_token_secret)
            twitter_user.save()

        return user
Пример #27
0
def register(request):
    """A view that manages the registration form"""
    if request.method == 'POST':
        user_form = UserRegistrationForm(request.POST)
        if user_form.is_valid():
            the_user = user_form.save()

            user = auth.authenticate(request.POST.get('email'),
                                     password=request.POST.get('password1'))
            if user:
                user_profile = UserProfile(user=the_user)
                user_profile.save()
                messages.success(request, "You have successfully registered")
                return redirect(reverse('login'))

            else:
                messages.error(request,
                               "Unable to create an account at this time!")
    else:
        user_form = UserRegistrationForm()

    args = {'user_form': user_form}
    return render(request, 'register.html', args)
Пример #28
0
 def make_user(self, coop=None):
     user = User.objects.create_user(
         username=random_letters(16),
         email='{local}@{domain}.com'.format(local=random_letters(8),
                                             domain=random_letters(8)),
         password=random_letters(32)
     )
     profile = UserProfile(
         user=user,
         coop=coop,
         nickname=random_letters(8),
         first_name=user.username.capitalize(),
         middle_name=random_letters(16),
         last_name=random_letters(16),
         email_address=user.email,
         presence=coop.profile.cycle_length,
         share=1,
         public_calendar=True,
         points_steward=False,
     )
     profile.save()
     coop.user_set.add(user)
     return user
Пример #29
0
    def create(self, validated_data):
        profile_data = validated_data.pop('profile', None)
        data = self.validated_data
        user = User.objects.create_user(
            username=data['username'],
            email=data['email'],
            password=data['password'],
        )
        user.save()

        profile_image = profile_data.get('profile_image') or None
        bio = "Say Hi to me. I'm new here"
        if not profile_image:
            profile_image = 'https://api.adorable.io/avatar/200/' + user.username
        profile = UserProfile(user=user,
                              bio=bio,
                              profile_image=profile_image,
                              full_name=profile_data.get('full_name', ''),
                              is_verified=profile_data.get(
                                  'is_verified', False),
                              address=profile_data.get('address', ''))
        profile.save()
        return user
Пример #30
0
 def register(self, request, **kwargs):
     new_user = super(TreeBackend,self).register(request, **kwargs)
     new_user.first_name = kwargs['first_name']
     new_user.last_name = kwargs['last_name']
     new_user.save()
     try:
         profile = new_user.get_profile()
     except:
         profile = UserProfile(user=new_user)
     profile.zip_code = kwargs.get('zip_code')
     profile.volunteer = kwargs.get('volunteer')
     profile.updates = kwargs.get('updates')
     profile.photo = kwargs.get('photo')
     profile.save()
     return new_user
Пример #31
0
 def setUp(self):
     self.browser = webdriver.Firefox()
     self.browser.implicitly_wait(3)
     self.browser.wait = WebDriverWait(self.browser, 10)
     sally = UserModel().objects.create_user(
         first_name='Sally',
         last_name='Hayes',
         username='******',
         email='[email protected]:8081',
         password='******'
     )
     sally_profile = UserProfile()
     sally_profile.user = sally
     sally_profile.birthday = '1985-07-22'
     sally_profile.gender = 'F'
     sally_profile.save()
Пример #32
0
    def create_anonymous(self):
        '''
		'''
        anonymous = User(id=ANONYMOUS_ID, \
                         username=ANONYMOUS_USERNAME, \
                         password=ANONYMOUS_PASSWORD) # this password will
        # never be used!
        anonymous.save()
        avatar = Avatar()
        avatar.avatar_save(MEDIA_ROOT + ANONYMOUS_USERNAME + '.jpg')

        profile = UserProfile(user=anonymous)
        profile.avatar = avatar
        profile.name = ANONYMOUS_NAME
        profile.save()

        # there while add some other thing

        return anonymous
Пример #33
0
    def register(self, request, **kwargs):
        username, email, password = kwargs['username'], kwargs['email'], kwargs['password1']
        if Site._meta.installed:
            site = Site.objects.get_current()
        else:
            site = RequestSite(request)
        new_user = RegistrationProfile.objects.create_inactive_user(username, email,
                                                                    password, site)
        signals.user_registered.send(sender=self.__class__,
                                     user=new_user,
                                     request=request)

        user = User.objects.get(username=new_user.username)
        user.first_name = kwargs['first_name']
        user.last_name = kwargs['last_name']
        user.save()
        new_profile = UserProfile(user=user)
        new_profile.fiscal_code = kwargs['fiscal_code']
        new_profile.telephone = kwargs['telephone']
        new_profile.area = kwargs['area']
        new_profile.personal_data = kwargs['personal_data']
        new_profile.save()

        return new_user
Пример #34
0
    def get(self, request, **kwargs):
        token = kwargs.get("token")
        uidb64 = kwargs.get("uidb64")
        try:
            uid = force_text(urlsafe_base64_decode(uidb64))
            user = User.objects.get(pk=uid)
        except (TypeError, ValueError, OverflowError, User.DoesNotExist):
            user = None

        if user and not user.is_active and default_token_generator.check_token(
                user, token):
            user.is_active = True
            user.save()
            createprofile = UserProfile()
            createprofile.name = user.first_name
            createprofile.email = user.email
            createprofile.save()

            return super(CreateCompleteView, self).get(request, **kwargs)
        else:
            raise Http404
Пример #35
0
def setupTreemapEnv():
    settings.GEOSERVER_GEO_LAYER = ""
    settings.GEOSERVER_GEO_STYLE = ""
    settings.GEOSERVER_URL = ""

    def local_render_to_response(*args, **kwargs):
        from django.template import loader, RequestContext
        from django.http import HttpResponse

        httpresponse_kwargs = {'mimetype': kwargs.pop('mimetype', None)}
        hr = HttpResponse(loader.render_to_string(*args, **kwargs),
                          **httpresponse_kwargs)

        if hasattr(args[1], 'dicts'):
            hr.request_context = args[1].dicts

        return hr

    django.shortcuts.render_to_response = local_render_to_response

    r1 = ReputationAction(name="edit verified", description="blah")
    r2 = ReputationAction(name="edit tree", description="blah")
    r3 = ReputationAction(name="Administrative Action", description="blah")
    r4 = ReputationAction(name="add tree", description="blah")
    r5 = ReputationAction(name="edit plot", description="blah")
    r6 = ReputationAction(name="add plot", description="blah")
    r7 = ReputationAction(name="add stewardship", description="blah")
    r8 = ReputationAction(name="remove stewardship", description="blah")

    for r in [r1, r2, r3, r4, r5, r6, r7, r8]:
        r.save()

    bv = BenefitValues(co2=0.02,
                       pm10=9.41,
                       area="InlandValleys",
                       electricity=0.1166,
                       voc=4.69,
                       ozone=5.0032,
                       natural_gas=1.25278,
                       nox=12.79,
                       stormwater=0.0078,
                       sox=3.72,
                       bvoc=4.96)

    bv.save()

    dbh = "[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]"
    dbh2 = "[2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]"

    rsrc1 = Resource(meta_species="BDM OTHER", region="NoEastXXX")
    rsrc2 = Resource(meta_species="BDL OTHER", region="NoEastXXX")

    rsrc1.save()
    rsrc2.save()

    u = User.objects.filter(username="******")

    if u:
        u = u[0]
    else:
        u = User.objects.create_user("jim", "*****@*****.**", "jim")
        u.is_staff = True
        u.is_superuser = True
        u.save()
        up = UserProfile(user=u)
        up.save()
        u.reputation = Reputation(user=u)
        u.reputation.save()

    amy_filter_result = User.objects.filter(username="******")
    if not amy_filter_result:
        amy = User.objects.create_user("amy", "*****@*****.**", "amy")
    else:
        amy = amy_filter_result[0]
        amy.is_staff = False
        amy.is_superuser = False
        amy.save()
        amy_profile = UserProfile(user=amy)
        amy_profile.save()
        amy.reputation = Reputation(user=amy)
        amy.reputation.save()

    olivia_filter_result = User.objects.filter(username="******")
    if not amy_filter_result:
        olivia = User.objects.create_user("olivia", "*****@*****.**",
                                          "olivia")
    else:
        olivia = olivia_filter_result[0]
        olivia.is_staff = False
        olivia.is_superuser = False
        olivia.save()
        olivia_profile = UserProfile(user=olivia)
        olivia_profile.save()
        olivia.reputation = Reputation(user=olivia)
        olivia.reputation.save()

    n1geom = MultiPolygon(
        Polygon(((0, 0), (100, 0), (100, 100), (0, 100), (0, 0))))
    n2geom = MultiPolygon(
        Polygon(((0, 101), (101, 101), (101, 200), (0, 200), (0, 101))))

    n1 = Neighborhood(name="n1",
                      region_id=2,
                      city="c1",
                      state="PA",
                      county="PAC",
                      geometry=n1geom)
    n2 = Neighborhood(name="n2",
                      region_id=2,
                      city="c2",
                      state="NY",
                      county="NYC",
                      geometry=n2geom)

    n1.save()
    n2.save()

    z1geom = MultiPolygon(
        Polygon(((0, 0), (100, 0), (100, 100), (0, 100), (0, 0))))
    z2geom = MultiPolygon(
        Polygon(((0, 100), (100, 100), (100, 200), (0, 200), (0, 100))))

    z1 = ZipCode(zip="19107", geometry=z1geom)
    z2 = ZipCode(zip="10001", geometry=z2geom)

    z1.save()
    z2.save()

    exgeom1 = MultiPolygon(
        Polygon(((0, 0), (25, 0), (25, 25), (0, 25), (0, 0))))
    ex1 = ExclusionMask(geometry=exgeom1, type="building")

    ex1.save()

    agn1 = AggregateNeighborhood(annual_stormwater_management=0.0,
                                 annual_electricity_conserved=0.0,
                                 annual_energy_conserved=0.0,
                                 annual_natural_gas_conserved=0.0,
                                 annual_air_quality_improvement=0.0,
                                 annual_co2_sequestered=0.0,
                                 annual_co2_avoided=0.0,
                                 annual_co2_reduced=0.0,
                                 total_co2_stored=0.0,
                                 annual_ozone=0.0,
                                 annual_nox=0.0,
                                 annual_pm10=0.0,
                                 annual_sox=0.0,
                                 annual_voc=0.0,
                                 annual_bvoc=0.0,
                                 total_trees=0,
                                 total_plots=0,
                                 location=n1)

    agn2 = AggregateNeighborhood(annual_stormwater_management=0.0,
                                 annual_electricity_conserved=0.0,
                                 annual_energy_conserved=0.0,
                                 annual_natural_gas_conserved=0.0,
                                 annual_air_quality_improvement=0.0,
                                 annual_co2_sequestered=0.0,
                                 annual_co2_avoided=0.0,
                                 annual_co2_reduced=0.0,
                                 total_co2_stored=0.0,
                                 annual_ozone=0.0,
                                 annual_nox=0.0,
                                 annual_pm10=0.0,
                                 annual_sox=0.0,
                                 annual_voc=0.0,
                                 annual_bvoc=0.0,
                                 total_trees=0,
                                 total_plots=0,
                                 location=n2)

    agn1.save()
    agn2.save()

    s1 = Species(symbol="s1",
                 genus="testus1",
                 species="specieius1",
                 cultivar_name='',
                 family='',
                 alternate_symbol='a1')
    s2 = Species(symbol="s2",
                 genus="testus2",
                 species="specieius2",
                 cultivar_name='',
                 family='',
                 alternate_symbol='a2')
    s3 = Species(symbol="s3",
                 genus="testus2",
                 species="specieius3",
                 cultivar_name='',
                 family='',
                 alternate_symbol='a3')

    s1.native_status = 'True'
    s1.fall_conspicuous = True
    s1.flower_conspicuous = True
    s1.palatable_human = True

    s2.native_status = 'True'
    s2.fall_conspicuous = False
    s2.flower_conspicuous = True
    s2.palatable_human = False
    s2.wildlife_value = True

    s3.wildlife_value = True

    s1.save()
    s2.save()
    s3.save()

    s1.resource.add(rsrc1)
    s2.resource.add(rsrc2)
    s3.resource.add(rsrc2)

    ie = ImportEvent(file_name='site_add')
    ie.save()
 def handle(self, *args, **options):
     user = User.objects.get(id=1)
     up =  UserProfile(user = user, privacy='open')
     up.save()
Пример #37
0
class PollFeedTest(TestCase):
    def setUp(self):
        self.feed = Feed(link="http://link.to/rss.xml", title="A Feed")
        self.feed.save()

        # Create an entry
        published = datetime.datetime(2013, 9, 25, 4, 0)
        published = published.timetuple()
        self.entry1 = FeedParserEntry(title="An Entry", link="http://entry", published_parsed=published)

        # Create another entry
        published = datetime.datetime(2013, 9, 28, 4, 0)
        published = published.timetuple()
        self.entry2 = FeedParserEntry(title="Another Entry", link="http://another/entry", published_parsed=published)

        # Create users
        user1 = User(username="******")
        user1.save()
        self.profile1 = UserProfile(user=user1)
        self.profile1.save()

        user2 = User(username="******")
        user2.save()
        self.profile2 = UserProfile(user=user2)
        self.profile2.save()

    def test_profile_display(self):
        self.assertEqual(str(self.profile1), "user1's profile")
        self.assertEqual(str(self.profile2), "user2's profile")

    @mock.patch("feedparser.parse")
    def test_poll_new_subscriber(self, mock_parse):
        """Test a successful polling of a feed."""

        # Set up mock data
        parser = mock.MagicMock()
        parser.entries = [self.entry1, self.entry2]
        mock_parse.return_value = parser
        Subscription(profile=self.profile1, feed=self.feed).save()

        # Verify initial state
        self.assertEqual(Feed.objects.count(), 1)
        self.assertEqual(Entry.objects.count(), 0)
        self.assertEqual(UserEntryDetail.objects.count(), 0)

        # Perform poll
        tasks.poll_feed(self.feed)

        # Verify final state
        self.assertEqual(Feed.objects.count(), 1)
        self.assertEqual(Entry.objects.count(), 2)
        self.assertEqual(UserEntryDetail.objects.count(), 2)

    @mock.patch("feedparser.parse")
    def test_poll_two_new_subscribers(self, mock_parse):
        """Test a successful polling of a feed."""

        # Set up mock data
        parser = mock.MagicMock()
        parser.entries = [self.entry1, self.entry2]
        mock_parse.return_value = parser
        Subscription(profile=self.profile1, feed=self.feed).save()
        Subscription(profile=self.profile2, feed=self.feed).save()

        # Verify initial state
        self.assertEqual(Feed.objects.count(), 1)
        self.assertEqual(Entry.objects.count(), 0)
        self.assertEqual(UserEntryDetail.objects.count(), 0)

        # Perform poll
        tasks.poll_feed(self.feed)

        # Verify final state
        self.assertEqual(Feed.objects.count(), 1)
        self.assertEqual(Entry.objects.count(), 2)
        self.assertEqual(UserEntryDetail.objects.count(), 4)

    @mock.patch("feedparser.parse")
    def test_poll_new_and_existing_subscribers(self, mock_parse):
        """Test a successful polling of a feed."""

        # Set up mock data
        parser = mock.MagicMock()
        parser.entries = [self.entry1, self.entry2]
        mock_parse.return_value = parser
        Subscription(profile=self.profile1, feed=self.feed).save()
        Subscription(profile=self.profile2, feed=self.feed).save()
        entry1 = Entry(
            link=self.entry1.link,
            feed=self.feed,
            title=self.entry1.title,
            published=datetime.datetime(2013, 9, 25, 4, 0),
        )
        entry1.save()
        UserEntryDetail(profile=self.profile1, entry=entry1).save()

        # Verify initial state
        self.assertEqual(Feed.objects.count(), 1)
        self.assertEqual(Entry.objects.count(), 1)
        self.assertEqual(UserEntryDetail.objects.count(), 1)

        # Perform poll
        tasks.poll_feed(self.feed)

        # Verify final state
        self.assertEqual(Feed.objects.count(), 1)
        self.assertEqual(Entry.objects.count(), 2)
        self.assertEqual(UserEntryDetail.objects.count(), 4)

    @mock.patch("feedparser.parse")
    def test_poll_after_unsubscribe(self, mock_parse):
        # Set up mock data
        parser = mock.MagicMock()
        parser.entries = [self.entry1]
        mock_parse.return_value = parser
        Subscription(profile=self.profile1, feed=self.feed).save()

        # Verify initial state
        self.assertEqual(Feed.objects.count(), 1)
        self.assertEqual(Entry.objects.count(), 0)
        self.assertEqual(UserEntryDetail.objects.count(), 0)

        # Perform poll
        tasks.poll_feed(self.feed)

        # Verify state
        self.assertEqual(Feed.objects.count(), 1)
        self.assertEqual(Entry.objects.count(), 1)
        self.assertEqual(UserEntryDetail.objects.count(), 1)

        # Unsubscribe
        self.profile1.unsubscribe(self.feed)

        # Verify state
        self.assertEqual(Feed.objects.count(), 1)
        self.assertEqual(Entry.objects.count(), 1)
        self.assertEqual(UserEntryDetail.objects.count(), 0)

        # Resubscribe
        self.profile1.subscribe(self.feed)

        # Perform poll (find another entry)
        parser.entries = [self.entry1, self.entry2]
        tasks.poll_feed(self.feed)

        # Verify final state
        self.assertEqual(Feed.objects.count(), 1)
        self.assertEqual(Entry.objects.count(), 2)
        self.assertEqual(UserEntryDetail.objects.count(), 2)

    @mock.patch("feedparser.parse")
    def test_mark_read_unread(self, mock_parse):
        parser = mock.MagicMock()
        parser.entries = [self.entry1, self.entry2]
        mock_parse.return_value = parser

        unread_entries = self.profile1.unread_entries(self.feed)
        self.assertEqual(unread_entries, 0)

        self.profile1.subscribe(self.feed)
        tasks.poll_feed(self.feed)
        unread_entries = self.profile1.unread_entries(self.feed)
        self.assertEqual(unread_entries, 2)

        self.profile1.mark_read(self.feed)
        unread_entries = self.profile1.unread_entries(self.feed)
        self.assertEqual(unread_entries, 0)

        self.profile1.mark_unread(self.feed)
        unread_entries = self.profile1.unread_entries(self.feed)
        self.assertEqual(unread_entries, 2)
Пример #38
0
def page(request):
    form = Form_register(prefix='register')
    form_log = Form_login(prefix='login')
    context = {
        "form": form,
        "form_log": form_log,
    }
    if request.method == 'POST' and 'login' in request.POST:
        form_log = Form_login(request.POST, prefix='login')
        if form_log.is_valid():
            username = form_log.cleaned_data["username"]
            password = form_log.cleaned_data["password"]
            user = authenticate(username=username, password=password)
            if user:
                from django.contrib.auth import login
                login(request, user)
            if request.user.is_authenticated():
                profile = UserProfile.objects.get(user_auth=request.user)
                context['profile'] = profile
                frequests = Invite.objects.filter(r_to=profile).exclude(
                    r_from=profile)
                context['frequests'] = frequests
                return render(request, "welcome.html", context)
            form_log = Form_login(prefix='login')
            context["form_log"] = form_log
            return render(request, "welcome.html", context)
        context["form_log"] = form_log
        return render(request, "welcome.html", context)

    if request.method == 'POST' and 'register' in request.POST:
        form = Form_register(request.POST, prefix='register')
        if form.is_valid():
            login = form.cleaned_data['login'].lower()
            password = form.cleaned_data['password']
            email = form.cleaned_data['email']
            user_auth = User.objects.create_user(username=login,
                                                 email=email,
                                                 password=password)
            user_auth.is_active = True

            user_auth.save()
            new_user = UserProfile(user_auth=user_auth)
            new_user.save()
            user = authenticate(username=login, password=password)
            if user:
                from django.contrib.auth import login
                login(request, user)
            return HttpResponseRedirect(reverse('welcome'))
        else:
            if request.user.is_authenticated():
                profile = UserProfile.objects.get(user_auth=request.user)
                context['profile'] = profile
                frequests = Invite.objects.filter(r_to=profile).exclude(
                    r_from=profile)
                context['frequests'] = frequests
            context["form"] = form
            return render(request, 'welcome.html', context)
        context["form"] = form
        return render(request, "welcome.html", context)

    if request.user.is_authenticated():
        profile = UserProfile.objects.get(user_auth=request.user)
        context['profile'] = profile
        frequests = Invite.objects.filter(r_to=profile).exclude(r_from=profile)
        context['frequests'] = frequests

    return render(request, "welcome.html", context)
Пример #39
0
def setupTreemapEnv():
    settings.GEOSERVER_GEO_LAYER = ""
    settings.GEOSERVER_GEO_STYLE = ""
    settings.GEOSERVER_URL = ""

    def local_render_to_response(*args, **kwargs):
        from django.template import loader, RequestContext
        from django.http import HttpResponse

        httpresponse_kwargs = {"mimetype": kwargs.pop("mimetype", None)}
        hr = HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)

        if hasattr(args[1], "dicts"):
            hr.request_context = args[1].dicts

        return hr

    django.shortcuts.render_to_response = local_render_to_response

    r1 = ReputationAction(name="edit verified", description="blah")
    r2 = ReputationAction(name="edit tree", description="blah")
    r3 = ReputationAction(name="Administrative Action", description="blah")
    r4 = ReputationAction(name="add tree", description="blah")
    r5 = ReputationAction(name="edit plot", description="blah")
    r6 = ReputationAction(name="add plot", description="blah")
    r7 = ReputationAction(name="add stewardship", description="blah")
    r8 = ReputationAction(name="remove stewardship", description="blah")

    for r in [r1, r2, r3, r4, r5, r6, r7, r8]:
        r.save()

    bv = BenefitValues(
        co2=0.02,
        pm10=9.41,
        area="InlandValleys",
        electricity=0.1166,
        voc=4.69,
        ozone=5.0032,
        natural_gas=1.25278,
        nox=12.79,
        stormwater=0.0078,
        sox=3.72,
        bvoc=4.96,
    )

    bv.save()

    dbh = "[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]"
    dbh2 = "[2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]"

    rsrc1 = Resource(meta_species="BDM OTHER", region="NoEastXXX")
    rsrc2 = Resource(meta_species="BDL OTHER", region="NoEastXXX")

    rsrc1.save()
    rsrc2.save()

    u = User.objects.filter(username="******")

    if u:
        u = u[0]
    else:
        u = User.objects.create_user("jim", "*****@*****.**", "jim")
        u.is_staff = True
        u.is_superuser = True
        u.save()
        up = UserProfile(user=u)
        up.save()
        u.reputation = Reputation(user=u)
        u.reputation.save()

    amy_filter_result = User.objects.filter(username="******")
    if not amy_filter_result:
        amy = User.objects.create_user("amy", "*****@*****.**", "amy")
    else:
        amy = amy_filter_result[0]
        amy.is_staff = False
        amy.is_superuser = False
        amy.save()
        amy_profile = UserProfile(user=amy)
        amy_profile.save()
        amy.reputation = Reputation(user=amy)
        amy.reputation.save()

    olivia_filter_result = User.objects.filter(username="******")
    if not amy_filter_result:
        olivia = User.objects.create_user("olivia", "*****@*****.**", "olivia")
    else:
        olivia = olivia_filter_result[0]
        olivia.is_staff = False
        olivia.is_superuser = False
        olivia.save()
        olivia_profile = UserProfile(user=olivia)
        olivia_profile.save()
        olivia.reputation = Reputation(user=olivia)
        olivia.reputation.save()

    n1geom = MultiPolygon(Polygon(((0, 0), (100, 0), (100, 100), (0, 100), (0, 0))))
    n2geom = MultiPolygon(Polygon(((0, 101), (101, 101), (101, 200), (0, 200), (0, 101))))

    n1 = Neighborhood(name="n1", region_id=2, city="c1", state="PA", county="PAC", geometry=n1geom)
    n2 = Neighborhood(name="n2", region_id=2, city="c2", state="NY", county="NYC", geometry=n2geom)

    n1.save()
    n2.save()

    z1geom = MultiPolygon(Polygon(((0, 0), (100, 0), (100, 100), (0, 100), (0, 0))))
    z2geom = MultiPolygon(Polygon(((0, 100), (100, 100), (100, 200), (0, 200), (0, 100))))

    z1 = ZipCode(zip="19107", geometry=z1geom)
    z2 = ZipCode(zip="10001", geometry=z2geom)

    z1.save()
    z2.save()

    exgeom1 = MultiPolygon(Polygon(((0, 0), (25, 0), (25, 25), (0, 25), (0, 0))))
    ex1 = ExclusionMask(geometry=exgeom1, type="building")

    ex1.save()

    agn1 = AggregateNeighborhood(
        annual_stormwater_management=0.0,
        annual_electricity_conserved=0.0,
        annual_energy_conserved=0.0,
        annual_natural_gas_conserved=0.0,
        annual_air_quality_improvement=0.0,
        annual_co2_sequestered=0.0,
        annual_co2_avoided=0.0,
        annual_co2_reduced=0.0,
        total_co2_stored=0.0,
        annual_ozone=0.0,
        annual_nox=0.0,
        annual_pm10=0.0,
        annual_sox=0.0,
        annual_voc=0.0,
        annual_bvoc=0.0,
        total_trees=0,
        total_plots=0,
        location=n1,
    )

    agn2 = AggregateNeighborhood(
        annual_stormwater_management=0.0,
        annual_electricity_conserved=0.0,
        annual_energy_conserved=0.0,
        annual_natural_gas_conserved=0.0,
        annual_air_quality_improvement=0.0,
        annual_co2_sequestered=0.0,
        annual_co2_avoided=0.0,
        annual_co2_reduced=0.0,
        total_co2_stored=0.0,
        annual_ozone=0.0,
        annual_nox=0.0,
        annual_pm10=0.0,
        annual_sox=0.0,
        annual_voc=0.0,
        annual_bvoc=0.0,
        total_trees=0,
        total_plots=0,
        location=n2,
    )

    agn1.save()
    agn2.save()

    s1 = Species(symbol="s1", genus="testus1", species="specieius1", cultivar_name="", family="", alternate_symbol="a1")
    s2 = Species(symbol="s2", genus="testus2", species="specieius2", cultivar_name="", family="", alternate_symbol="a2")
    s3 = Species(symbol="s3", genus="testus2", species="specieius3", cultivar_name="", family="", alternate_symbol="a3")

    s1.native_status = "True"
    s1.fall_conspicuous = True
    s1.flower_conspicuous = True
    s1.palatable_human = True

    s2.native_status = "True"
    s2.fall_conspicuous = False
    s2.flower_conspicuous = True
    s2.palatable_human = False
    s2.wildlife_value = True

    s3.wildlife_value = True

    s1.save()
    s2.save()
    s3.save()

    s1.resource.add(rsrc1)
    s2.resource.add(rsrc2)
    s3.resource.add(rsrc2)

    ie = ImportEvent(file_name="site_add")
    ie.save()
Пример #40
0
    def setUp(self):
        ######
        # Request/Render mock
        ######
        def local_render_to_response(*args, **kwargs):
            from django.template import loader, RequestContext
            from django.http import HttpResponse

            httpresponse_kwargs = {'mimetype': kwargs.pop('mimetype', None)}
            hr = HttpResponse(loader.render_to_string(*args, **kwargs),
                              **httpresponse_kwargs)

            if hasattr(args[1], 'dicts'):
                hr.request_context = args[1].dicts

            return hr

        django.shortcuts.render_to_response = local_render_to_response

        ######
        # Content types
        ######
        r1 = ReputationAction(name="edit verified", description="blah")
        r2 = ReputationAction(name="edit tree", description="blah")
        r3 = ReputationAction(name="Administrative Action", description="blah")
        r4 = ReputationAction(name="add tree", description="blah")
        r5 = ReputationAction(name="edit plot", description="blah")
        r6 = ReputationAction(name="add plot", description="blah")
        r7 = ReputationAction(name="add stewardship", description="blah")
        r8 = ReputationAction(name="remove stewardship", description="blah")

        self.ra = [r1, r2, r3, r4, r5, r6, r7, r8]

        for r in self.ra:
            r.save()

        ######
        # Set up benefit values
        ######
        bv = BenefitValues(co2=0.02,
                           pm10=9.41,
                           area="InlandValleys",
                           electricity=0.1166,
                           voc=4.69,
                           ozone=5.0032,
                           natural_gas=1.25278,
                           nox=12.79,
                           stormwater=0.0078,
                           sox=3.72,
                           bvoc=4.96)

        bv.save()
        self.bv = bv

        dbh = "[1.0, 2.0, 3.0]"

        rsrc = Resource(meta_species="BDM_OTHER",
                        electricity_dbh=dbh,
                        co2_avoided_dbh=dbh,
                        aq_pm10_dep_dbh=dbh,
                        region="Sim City",
                        aq_voc_avoided_dbh=dbh,
                        aq_pm10_avoided_dbh=dbh,
                        aq_ozone_dep_dbh=dbh,
                        aq_nox_avoided_dbh=dbh,
                        co2_storage_dbh=dbh,
                        aq_sox_avoided_dbh=dbh,
                        aq_sox_dep_dbh=dbh,
                        bvoc_dbh=dbh,
                        co2_sequestered_dbh=dbh,
                        aq_nox_dep_dbh=dbh,
                        hydro_interception_dbh=dbh,
                        natural_gas_dbh=dbh)
        rsrc.save()
        self.rsrc = rsrc

        ######
        # Users
        ######
        u = User.objects.filter(username="******")

        if u:
            u = u[0]
        else:
            u = User.objects.create_user("jim", "*****@*****.**", "jim")
            u.is_staff = True
            u.is_superuser = True
            u.save()
            up = UserProfile(user=u)
            u.reputation = Reputation(user=u)
            u.reputation.save()

        self.u = u

        #######
        # Setup geometries -> Two stacked 100x100 squares
        #######
        n1geom = MultiPolygon(
            Polygon(((0, 0), (100, 0), (100, 100), (0, 100), (0, 0))))
        n2geom = MultiPolygon(
            Polygon(((0, 101), (101, 101), (101, 200), (0, 200), (0, 101))))

        n1 = Neighborhood(name="n1",
                          region_id=2,
                          city="c1",
                          state="PA",
                          county="PAC",
                          geometry=n1geom)
        n2 = Neighborhood(name="n2",
                          region_id=2,
                          city="c2",
                          state="NY",
                          county="NYC",
                          geometry=n2geom)

        n1.save()
        n2.save()

        z1geom = MultiPolygon(
            Polygon(((0, 0), (100, 0), (100, 100), (0, 100), (0, 0))))
        z2geom = MultiPolygon(
            Polygon(((0, 100), (100, 100), (100, 200), (0, 200), (0, 100))))

        z1 = ZipCode(zip="19107", geometry=z1geom)
        z2 = ZipCode(zip="10001", geometry=z2geom)

        z1.save()
        z2.save()

        exgeom1 = MultiPolygon(
            Polygon(((0, 0), (25, 0), (25, 25), (0, 25), (0, 0))))
        ex1 = ExclusionMask(geometry=exgeom1, type="building")

        ex1.save()

        agn1 = AggregateNeighborhood(annual_stormwater_management=0.0,
                                     annual_electricity_conserved=0.0,
                                     annual_energy_conserved=0.0,
                                     annual_natural_gas_conserved=0.0,
                                     annual_air_quality_improvement=0.0,
                                     annual_co2_sequestered=0.0,
                                     annual_co2_avoided=0.0,
                                     annual_co2_reduced=0.0,
                                     total_co2_stored=0.0,
                                     annual_ozone=0.0,
                                     annual_nox=0.0,
                                     annual_pm10=0.0,
                                     annual_sox=0.0,
                                     annual_voc=0.0,
                                     annual_bvoc=0.0,
                                     total_trees=0,
                                     total_plots=0,
                                     location=n1)

        agn2 = AggregateNeighborhood(annual_stormwater_management=0.0,
                                     annual_electricity_conserved=0.0,
                                     annual_energy_conserved=0.0,
                                     annual_natural_gas_conserved=0.0,
                                     annual_air_quality_improvement=0.0,
                                     annual_co2_sequestered=0.0,
                                     annual_co2_avoided=0.0,
                                     annual_co2_reduced=0.0,
                                     total_co2_stored=0.0,
                                     annual_ozone=0.0,
                                     annual_nox=0.0,
                                     annual_pm10=0.0,
                                     annual_sox=0.0,
                                     annual_voc=0.0,
                                     annual_bvoc=0.0,
                                     total_trees=0,
                                     total_plots=0,
                                     location=n2)

        agn1.save()
        agn2.save()

        self.agn1 = agn1
        self.agn2 = agn2

        self.z1 = z1
        self.z2 = z2
        self.n1 = n1
        self.n2 = n2

        ######
        # And we could use a few species...
        ######
        s1 = Species(symbol="s1", genus="testus1", species="specieius1")
        s2 = Species(symbol="s2", genus="testus2", species="specieius2")

        s1.save()
        s2.save()

        self.s1 = s1
        self.s2 = s2

        #######
        # Create some basic plots
        #######
        ie = ImportEvent(file_name='site_add')
        ie.save()

        self.ie = ie

        p1_no_tree = Plot(geometry=Point(50, 50),
                          last_updated_by=u,
                          import_event=ie,
                          present=True,
                          data_owner=u)
        p1_no_tree.save()

        p2_tree = Plot(geometry=Point(51, 51),
                       last_updated_by=u,
                       import_event=ie,
                       present=True,
                       data_owner=u)
        p2_tree.save()

        p3_tree_species1 = Plot(geometry=Point(50, 100),
                                last_updated_by=u,
                                import_event=ie,
                                present=True,
                                data_owner=u)
        p3_tree_species1.save()

        p4_tree_species2 = Plot(geometry=Point(50, 150),
                                last_updated_by=u,
                                import_event=ie,
                                present=True,
                                data_owner=u)
        p4_tree_species2.save()

        t1 = Tree(plot=p2_tree,
                  species=None,
                  last_updated_by=u,
                  import_event=ie)
        t1.present = True
        t1.save()

        t2 = Tree(plot=p3_tree_species1,
                  species=s1,
                  last_updated_by=u,
                  import_event=ie)
        t2.present = True
        t2.save()

        t3 = Tree(plot=p4_tree_species2,
                  species=s2,
                  last_updated_by=u,
                  import_event=ie)
        t3.present = True
        t3.save()

        self.p1_no_tree = p1_no_tree
        self.p2_tree = p2_tree
        self.p3_tree_species1 = p3_tree_species1
        self.p4_tree_species2 = p4_tree_species2

        self.plots = [p1_no_tree, p2_tree, p3_tree_species1, p4_tree_species2]

        self.t1 = t1
        self.t2 = t2
        self.t3 = t3
Пример #41
0
def makeProfile(request):
    """ This creates an empty profile for the user to fill out """
    upr = UserProfile()
    upr.user = request.user
    upr.image = "images/no-pic.png"
    upr.save()
 def test_userprofile(self):
     user = User(username='******')
     user.save()
     userprofile = UserProfile(user=user, default_email='*****@*****.**')
     self.assertEqual(str(userprofile), 'testuser, [email protected]')
Пример #43
0
def setupTreemapEnv():
    settings.GEOSERVER_GEO_LAYER = ""
    settings.GEOSERVER_GEO_STYLE = ""
    settings.GEOSERVER_URL = ""

    r1 = ReputationAction(name="edit verified", description="blah")
    r2 = ReputationAction(name="edit tree", description="blah")
    r3 = ReputationAction(name="Administrative Action", description="blah")
    r4 = ReputationAction(name="add tree", description="blah")
    r5 = ReputationAction(name="edit plot", description="blah")
    r6 = ReputationAction(name="add plot", description="blah")

    for r in [r1, r2, r3, r4, r5, r6]:
        r.save()

    bv = BenefitValues(
        co2=0.02,
        pm10=9.41,
        area="InlandValleys",
        electricity=0.1166,
        voc=4.69,
        ozone=5.0032,
        natural_gas=1.25278,
        nox=12.79,
        stormwater=0.0078,
        sox=3.72,
        bvoc=4.96)

    bv.save()

    dbh = "[1.0, 2.0, 3.0]"

    rsrc = Resource(
        meta_species="BDM_OTHER",
        electricity_dbh=dbh,
        co2_avoided_dbh=dbh,
        aq_pm10_dep_dbh=dbh,
        region="Sim City",
        aq_voc_avoided_dbh=dbh,
        aq_pm10_avoided_dbh=dbh,
        aq_ozone_dep_dbh=dbh,
        aq_nox_avoided_dbh=dbh,
        co2_storage_dbh=dbh,
        aq_sox_avoided_dbh=dbh,
        aq_sox_dep_dbh=dbh,
        bvoc_dbh=dbh,
        co2_sequestered_dbh=dbh,
        aq_nox_dep_dbh=dbh,
        hydro_interception_dbh=dbh,
        natural_gas_dbh=dbh)
    rsrc.save()

    u = User.objects.filter(username="******")

    if u:
        u = u[0]
    else:
        u = User.objects.create_user("jim", "*****@*****.**", "jim")
        u.is_staff = True
        u.is_superuser = True
        u.save()
        up = UserProfile(user=u)
        up.save()
        u.reputation = Reputation(user=u)
        u.reputation.save()

    amy_filter_result = User.objects.filter(username="******")
    if not amy_filter_result:
        amy = User.objects.create_user("amy", "*****@*****.**", "amy")
    else:
        amy = amy_filter_result[0]
    amy.is_staff = False
    amy.is_superuser = False
    amy.save()
    amy_profile = UserProfile(user=amy)
    amy_profile.save()
    amy.reputation = Reputation(user=amy)
    amy.reputation.save()

    n1geom = MultiPolygon(
        Polygon(((0, 0), (100, 0), (100, 100), (0, 100), (0, 0))))
    n2geom = MultiPolygon(
        Polygon(((0, 101), (101, 101), (101, 200), (0, 200), (0, 101))))

    n1 = Neighborhood(
        name="n1",
        region_id=2,
        city="c1",
        state="PA",
        county="PAC",
        geometry=n1geom)
    n2 = Neighborhood(
        name="n2",
        region_id=2,
        city="c2",
        state="NY",
        county="NYC",
        geometry=n2geom)

    n1.save()
    n2.save()

    z1geom = MultiPolygon(
        Polygon(((0, 0), (100, 0), (100, 100), (0, 100), (0, 0))))
    z2geom = MultiPolygon(
        Polygon(((0, 100), (100, 100), (100, 200), (0, 200), (0, 100))))

    z1 = ZipCode(zip="19107", geometry=z1geom)
    z2 = ZipCode(zip="10001", geometry=z2geom)

    z1.save()
    z2.save()

    exgeom1 = MultiPolygon(
        Polygon(((0, 0), (25, 0), (25, 25), (0, 25), (0, 0))))
    ex1 = ExclusionMask(geometry=exgeom1, type="building")

    ex1.save()

    agn1 = AggregateNeighborhood(
        annual_stormwater_management=0.0,
        annual_electricity_conserved=0.0,
        annual_energy_conserved=0.0,
        annual_natural_gas_conserved=0.0,
        annual_air_quality_improvement=0.0,
        annual_co2_sequestered=0.0,
        annual_co2_avoided=0.0,
        annual_co2_reduced=0.0,
        total_co2_stored=0.0,
        annual_ozone=0.0,
        annual_nox=0.0,
        annual_pm10=0.0,
        annual_sox=0.0,
        annual_voc=0.0,
        annual_bvoc=0.0,
        total_trees=0,
        total_plots=0,
        location=n1)

    agn2 = AggregateNeighborhood(
        annual_stormwater_management=0.0,
        annual_electricity_conserved=0.0,
        annual_energy_conserved=0.0,
        annual_natural_gas_conserved=0.0,
        annual_air_quality_improvement=0.0,
        annual_co2_sequestered=0.0,
        annual_co2_avoided=0.0,
        annual_co2_reduced=0.0,
        total_co2_stored=0.0,
        annual_ozone=0.0,
        annual_nox=0.0,
        annual_pm10=0.0,
        annual_sox=0.0,
        annual_voc=0.0,
        annual_bvoc=0.0,
        total_trees=0,
        total_plots=0,
        location=n2)

    agn1.save()
    agn2.save()

    s1 = Species(symbol="s1", genus="testus1", species="specieius1")
    s2 = Species(symbol="s2", genus="testus2", species="specieius2")

    s1.save()
    s2.save()

    ie = ImportEvent(file_name='site_add')
    ie.save()
Пример #44
0
def create_profile_handler(sender, instance, **kwargs):
    """As New User created, create and attach Profile"""
    if not kwargs.get('created'):
        return None
    profile = UserProfile(user=instance)
    profile.save()
Пример #45
0
def Registration(request):
	'''register a user as a Rooroo member'''
	if request.user.is_authenticated():
		# already registered and logged in
		return HttpResponseRedirect('index.html')

	if request.method == 'POST':
		# submission of customized form
		form = RegistrationForm(request.POST)
		if form.is_valid():
			try:
				# all fields in form are filled out, unique username, correct email format, matching passwords
				new_user = User.objects.create_user(username=form.cleaned_data['username'], # pass value in username field in form
											email=form.cleaned_data['email'],
											password=form.cleaned_data['password'])
			except Exception as e:
				print e
				import traceback
				import sys
				traceback.print_exc(file=sys.stdout)
			else:
				new_user.is_active = False
				new_user.save() # save form input into a user object for logging into account

			finally:
				# build the activation key for new user profile account; expires after 2 days
				salt = hashlib.sha1(str(random.random())).hexdigest()[:5] 
				activation_key = hashlib.sha1(salt+new_user.username).hexdigest() 
				key_expires = datetime.datetime.utcnow().replace(tzinfo=utc) + datetime.timedelta(2)

			try:
				# create manual UserProfile object
				print"userprofile"
				new_userprofile = UserProfile(user=new_user, activation_key=activation_key, key_expires=key_expires, position=form.cleaned_data['position'])
			except Exception as e:
				print e
				import traceback
				traceback.print_exc(file=sys.stdout)
				# error: new user object created but not new user profile;
				# make new user inactive to avoid breaking foreign keys to users, then delete
				new_user.is_active = False
				new_user.delete()
				return render_to_response('registration/registration_form.html', { 'form': form }, context_instance=RequestContext(request))
			else:
				print"in else"
				new_userprofile.save()

				email_subject = "REQUEST: Activate Your RooRoo Account"
				email_body = "Hello %s,\n\nTo activate your account, please click on the link within 48 hours:\nhttp://localhost:8000/accounts/confirm/%s \n\nNote: This is an auto-generated e-mail message; please do not reply."%(
																						new_user.username,
																						new_userprofile.activation_key)
				#https://mol-flipbook.sbgrid.org/accounts/confirm/%s \n\nNote: This is an auto-generated e-mail message, please do not reply."%(

				from_sender = '*****@*****.**'
				to_recipient = [new_user.email]

				try:
					send_mail(email_subject, email_body, from_sender, to_recipient)
				except Exception as e:
					print e
					traceback.print_exc(file=sys.stdout)
				finally:
					# render html page stating email is sent out to user
					return render_to_response('registration/registration_complete.html', context_instance=RequestContext(request))
		else:
			# form not valid, try again
			print("User form is bound:{0} errors:{1}").format(form.is_bound, form.errors)
			return render_to_response('registration/registration_form.html', { 'form': form }, context_instance=RequestContext(request))

	else:
		'''user is not submitting the form, show them a blank registration form'''
		form = RegistrationForm()
		# add form to context
		context = { 'form': form }
		return render_to_response('registration/registration_form.html', context, context_instance=RequestContext(request))
Пример #46
0
 def get_success_url(self, *args, **kwargs):
     return UserProfile.get_list_url()
Пример #47
0
 def handle(self, *args, **options):
     user = User.objects.get(id=1)
     up = UserProfile(user=user, privacy='open')
     up.save()
Пример #48
0
 def update(self, validated_data):
     user = UserProfile(phone_number=validated_data['phone_number'], )
     otp = random.randrange(0, 4)
     user.set_password(otp)
     user.save()
     return user
Пример #49
0
def Registration(request):
    '''register a user as a Rooroo member'''
    if request.user.is_authenticated():
        # already registered and logged in
        return HttpResponseRedirect('index.html')

    if request.method == 'POST':
        # submission of customized form
        form = RegistrationForm(request.POST)
        if form.is_valid():
            try:
                # all fields in form are filled out, unique username, correct email format, matching passwords
                new_user = User.objects.create_user(
                    username=form.cleaned_data[
                        'username'],  # pass value in username field in form
                    email=form.cleaned_data['email'],
                    password=form.cleaned_data['password'])
            except Exception as e:
                print e
                import traceback
                import sys
                traceback.print_exc(file=sys.stdout)
            else:
                new_user.is_active = False
                new_user.save(
                )  # save form input into a user object for logging into account

            finally:
                # build the activation key for new user profile account; expires after 2 days
                salt = hashlib.sha1(str(random.random())).hexdigest()[:5]
                activation_key = hashlib.sha1(salt +
                                              new_user.username).hexdigest()
                key_expires = datetime.datetime.utcnow().replace(
                    tzinfo=utc) + datetime.timedelta(2)

            try:
                # create manual UserProfile object
                print "userprofile"
                new_userprofile = UserProfile(
                    user=new_user,
                    activation_key=activation_key,
                    key_expires=key_expires,
                    position=form.cleaned_data['position'])
            except Exception as e:
                print e
                import traceback
                traceback.print_exc(file=sys.stdout)
                # error: new user object created but not new user profile;
                # make new user inactive to avoid breaking foreign keys to users, then delete
                new_user.is_active = False
                new_user.delete()
                return render_to_response(
                    'registration/registration_form.html', {'form': form},
                    context_instance=RequestContext(request))
            else:
                print "in else"
                new_userprofile.save()

                email_subject = "REQUEST: Activate Your RooRoo Account"
                email_body = "Hello %s,\n\nTo activate your account, please click on the link within 48 hours:\nhttp://localhost:8000/accounts/confirm/%s \n\nNote: This is an auto-generated e-mail message; please do not reply." % (
                    new_user.username, new_userprofile.activation_key)
                #https://mol-flipbook.sbgrid.org/accounts/confirm/%s \n\nNote: This is an auto-generated e-mail message, please do not reply."%(

                from_sender = '*****@*****.**'
                to_recipient = [new_user.email]

                try:
                    send_mail(email_subject, email_body, from_sender,
                              to_recipient)
                except Exception as e:
                    print e
                    traceback.print_exc(file=sys.stdout)
                finally:
                    # render html page stating email is sent out to user
                    return render_to_response(
                        'registration/registration_complete.html',
                        context_instance=RequestContext(request))
        else:
            # form not valid, try again
            print("User form is bound:{0} errors:{1}").format(
                form.is_bound, form.errors)
            return render_to_response('registration/registration_form.html',
                                      {'form': form},
                                      context_instance=RequestContext(request))

    else:
        '''user is not submitting the form, show them a blank registration form'''
        form = RegistrationForm()
        # add form to context
        context = {'form': form}
        return render_to_response('registration/registration_form.html',
                                  context,
                                  context_instance=RequestContext(request))
Пример #50
0
def user_created(sender, user, request, **kwargs):
    form = RegistrationFormProfile(request.POST)
    profile = UserProfile(user=user, phone=form.data['phone'], contact_person=form.data['contact_person'])
    profile.save()
Пример #51
0
def handle_user_signed_up(sender, **kwargs):
    log(
        user=kwargs.get("user"),
        action="USER_SIGNED_UP",
        extra={}
    )

    profile = UserProfile()
    profile.user = kwargs.get("user")
    profile.save()

    steam = SteamProfile()
    steam.username = "******"
    steam.url = "None"
    steam.save()

    lol = LeagueOfLegendsProfile()
    lol.username = "******"
    lol.save()
    
    eve = EveOnlineProfile()
    eve.username = "******"
    eve.save()
    
    minecraft = MinecraftProfile()
    minecraft.username = "******"
    minecraft.save()
    
    nintendo = NintendoProfile()
    nintendo.username = "******"
    nintendo.friendcode = "None"
    nintendo.save()
    
    psn = PlaystationNetworkProfile()
    psn.username = "******"
    psn.save()
    
    xbl = XboxLiveProfile()
    xbl.gamertag = "None"
    xbl.save()
    
    bf4 = BattlefieldFourProfile()
    bf4.username = "******"
    bf4.save()
    
    blizz = BlizzardProfile()
    blizz.realid = "None"
    blizz.email = "None"
    blizz.save()
    
    wot = WorldOfTanksProfile()
    wot.username = "******"
    wot.save()

    profile.steam = steam
    profile.leagueoflegends = lol
    profile.eveonline = eve
    profile.minecraft = minecraft
    profile.nintendo = nintendo
    profile.psn = psn
    profile.xbl = xbl
    profile.bf4 = bf4
    profile.blizzard = blizz
    profile.worldoftanks = wot

    profile.save()
Пример #52
0
def create_profile(user, nb_seats, birthdate, smoke_bool, communities, moneyperkm, gender, bank_account, car_id, phone_nb, car_desc):
    p = UserProfile()
    p.user = user
    p.number_of_seats = nb_seats
    p.date_of_birth = birthdate
    p.smoker = smoke_bool
    p.communities = communities
    p.money_per_km = moneyperkm
    p.gender = gender
    p.bank_account_number = bank_account
    p.account_balance = random.randint(0,500)
    p.car_id = car_id
    p.phone_number = phone_nb
    p.car_description = car_desc
    p.save()
    return p
Пример #53
0
def checkout(request):
    """
    View to render the shopping basket page
    and handle the stripe payment
    """
    stripe_public_key = settings.STRIPE_PUBLIC_KEY
    stripe_secret_key = settings.STRIPE_SECRET_KEY

    if request.method == 'POST':
        basket = request.session.get('basket', {})
        form_data = {
            'full_name': request.POST['full_name'],
            'email': request.POST['email'],
            'phone_number': request.POST['phone_number'],
            'street_address1': request.POST['street_address1'],
            'street_address2': request.POST['street_address2'],
            'town_city': request.POST['town_city'],
            'postcode': request.POST['postcode'],
            'county': request.POST['county'],
            'country': request.POST['country'],
        }
        order_form = OrderForm(form_data)
        if order_form.is_valid():
            order = order_form.save(commit=False)

            pid = request.POST.get('client_secret').split('_secret')[0]
            order.stripe_pid = pid
            order.original_basket = json.dumps(basket)
            order.save()

            for item_id, quantity in basket.items():
                try:
                    product = Product.objects.get(id=item_id)
                    order_line_item = OrderLineItem(
                        order=order,
                        product=product,
                        quantity=quantity,
                    )
                    order_line_item.save()
                except Product.DoesNotExist:
                    messages.error(request, (
                        "One of the items in your basket was not found in our database"
                        "Please contact us for assistance."))
                    order.delete()
                    return redirect(reverse('view_basket'))
            request.session['save_info'] = 'save-info' in request.POST
            return redirect(
                reverse('checkout_success', args=[order.order_number]))
        else:
            messages.error(
                request,
                "There was an error with your form, please check your info")
    else:
        basket = request.session.get('basket', {})
        if not basket:
            messages.error(request, 'There are no items in your basket')
            return redirect(reverse('products'))

        current_basket = basket_content(request)
        total = current_basket['grand_total']
        stripe_total = round(total * 100)
        stripe.api_key = stripe_secret_key
        intent = stripe.PaymentIntent.create(
            amount=stripe_total,
            currency=settings.STRIPE_CURRENCY,
        )
        # Check if the customer has a account with delivery info saved
        if request.user.is_authenticated:
            try:
                profile = UserProfile.objects.get(user=request.user)
                order_form = OrderForm(
                    initial={
                        'full_name': profile.default_full_name,
                        'email': profile.user.email,
                        'phone_number': profile.default_phone_number,
                        'street_address1': profile.default_street_address1,
                        'street_address2': profile.default_street_address2,
                        'town_city': profile.default_town_city,
                        'postcode': profile.default_postcode,
                        'county': profile.default_county,
                        'country': profile.default_country,
                    })
            except UserProfile.DoesNotExist():
                order_form = OrderForm()
        else:
            order_form = OrderForm()

        if not stripe_public_key:
            messages.warning(
                request,
                'Stripe public key is missing. Did you forget to set it?')

    context = {
        'order_form': order_form,
        'stripe_public_key': stripe_public_key,
        'client_secret': intent.client_secret,
    }

    return render(request, 'checkout/checkout.html', context)
Пример #54
0
def setupTreemapEnv():
    Choices(field="plot_type", key="blah", value="blah", key_type="str").save()

    r1 = ReputationAction(name="edit verified", description="blah")
    r2 = ReputationAction(name="edit tree", description="blah")
    r3 = ReputationAction(name="Administrative Action", description="blah")
    r4 = ReputationAction(name="add tree", description="blah")
    r5 = ReputationAction(name="edit plot", description="blah")
    r6 = ReputationAction(name="add plot", description="blah")

    for r in [r1, r2, r3, r4, r5, r6]:
        r.save()

    bv = BenefitValues(co2=0.02,
                       pm10=9.41,
                       area="InlandValleys",
                       electricity=0.1166,
                       voc=4.69,
                       ozone=5.0032,
                       natural_gas=1.25278,
                       nox=12.79,
                       stormwater=0.0078,
                       sox=3.72,
                       bvoc=4.96)

    bv.save()

    dbh = "[1.0, 2.0, 3.0]"

    rsrc = Resource(meta_species="BDM_OTHER",
                    electricity_dbh=dbh,
                    co2_avoided_dbh=dbh,
                    aq_pm10_dep_dbh=dbh,
                    region="Sim City",
                    aq_voc_avoided_dbh=dbh,
                    aq_pm10_avoided_dbh=dbh,
                    aq_ozone_dep_dbh=dbh,
                    aq_nox_avoided_dbh=dbh,
                    co2_storage_dbh=dbh,
                    aq_sox_avoided_dbh=dbh,
                    aq_sox_dep_dbh=dbh,
                    bvoc_dbh=dbh,
                    co2_sequestered_dbh=dbh,
                    aq_nox_dep_dbh=dbh,
                    hydro_interception_dbh=dbh,
                    natural_gas_dbh=dbh)
    rsrc.save()

    u = User.objects.filter(username="******")

    if u:
        u = u[0]
    else:
        u = User.objects.create_user("jim", "*****@*****.**", "jim")
        u.is_staff = True
        u.is_superuser = True
        u.save()
        up = UserProfile(user=u)
        u.reputation = Reputation(user=u)
        u.reputation.save()

    n1geom = MultiPolygon(
        Polygon(((0, 0), (100, 0), (100, 100), (0, 100), (0, 0))))
    n2geom = MultiPolygon(
        Polygon(((0, 101), (101, 101), (101, 200), (0, 200), (0, 101))))

    n1 = Neighborhood(name="n1",
                      region_id=2,
                      city="c1",
                      state="PA",
                      county="PAC",
                      geometry=n1geom)
    n2 = Neighborhood(name="n2",
                      region_id=2,
                      city="c2",
                      state="NY",
                      county="NYC",
                      geometry=n2geom)

    n1.save()
    n2.save()

    z1geom = MultiPolygon(
        Polygon(((0, 0), (100, 0), (100, 100), (0, 100), (0, 0))))
    z2geom = MultiPolygon(
        Polygon(((0, 100), (100, 100), (100, 200), (0, 200), (0, 100))))

    z1 = ZipCode(zip="19107", geometry=z1geom)
    z2 = ZipCode(zip="10001", geometry=z2geom)

    z1.save()
    z2.save()

    exgeom1 = MultiPolygon(
        Polygon(((0, 0), (25, 0), (25, 25), (0, 25), (0, 0))))
    ex1 = ExclusionMask(geometry=exgeom1, type="building")

    ex1.save()

    agn1 = AggregateNeighborhood(annual_stormwater_management=0.0,
                                 annual_electricity_conserved=0.0,
                                 annual_energy_conserved=0.0,
                                 annual_natural_gas_conserved=0.0,
                                 annual_air_quality_improvement=0.0,
                                 annual_co2_sequestered=0.0,
                                 annual_co2_avoided=0.0,
                                 annual_co2_reduced=0.0,
                                 total_co2_stored=0.0,
                                 annual_ozone=0.0,
                                 annual_nox=0.0,
                                 annual_pm10=0.0,
                                 annual_sox=0.0,
                                 annual_voc=0.0,
                                 annual_bvoc=0.0,
                                 total_trees=0,
                                 total_plots=0,
                                 location=n1)

    agn2 = AggregateNeighborhood(annual_stormwater_management=0.0,
                                 annual_electricity_conserved=0.0,
                                 annual_energy_conserved=0.0,
                                 annual_natural_gas_conserved=0.0,
                                 annual_air_quality_improvement=0.0,
                                 annual_co2_sequestered=0.0,
                                 annual_co2_avoided=0.0,
                                 annual_co2_reduced=0.0,
                                 total_co2_stored=0.0,
                                 annual_ozone=0.0,
                                 annual_nox=0.0,
                                 annual_pm10=0.0,
                                 annual_sox=0.0,
                                 annual_voc=0.0,
                                 annual_bvoc=0.0,
                                 total_trees=0,
                                 total_plots=0,
                                 location=n2)

    agn1.save()
    agn2.save()

    s1 = Species(symbol="s1", genus="testus1", species="specieius1")
    s2 = Species(symbol="s2", genus="testus2", species="specieius2")

    s1.save()
    s2.save()

    ie = ImportEvent(file_name='site_add')
    ie.save()