我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用django.urls.reverse()。
def send(self, request): if (not self.last_email) or self.last_email + timedelta(hours=12) < now(): # TODO: TIMEDELTA mit config old_lang = translation.get_language() translation.activate(self.user.language) link = reverse('poll_vote', args=(self.poll.url,)) # TODO: hier direkt das poll oder das Vote? email_content = render_to_string('invitations/mail_invite.txt', { 'receiver': self.user.username, 'creator': self.creator.username, 'link': link }) try: send_mail("Invitation to vote on {}".format(self.poll.title), email_content, None, [self.user.email]) self.last_email = now() self.save() except SMTPRecipientsRefused: translation.activate(old_lang) messages.error( request, _("The mail server had an error sending the notification to {}".format(self.user.username)) ) translation.activate(old_lang) else: messages.error( request, _("You have send an Email for {} in the last 12 Hours".format(self.user.username)) )
def sort_by_estimation(user, category): """ Sorts books by average count of estimation of each book. Uses aggregate function. :param django.contrib.auth.models.User user: The request user. :param app.models.Category category: The category. :return: The list with sorted books. """ books = [] filtered_books = Book.exclude_private_books(user, Book.objects.filter(id_category=category)) for item in filtered_books: book_rating = BookRating.objects.filter(id_book=item).aggregate(Avg('rating')) book = {'id': item.id, 'name': item.book_name, 'author': item.id_author.author_name, 'url': item.photo.url if item.photo else '', 'rating': book_rating['rating__avg']} books.append(book) return sorted(books, key=lambda info: (info['rating'] is not None, info['rating']), reverse=True) # ------------------------------------------------------------------------------------------------------------------
def new_game(request): """ This view creates a new game token when a user clicks on "New Game" button on index.html This is done randomly and then checks in the database to see if that token is already present. If so, it'll keep on trying until it finds a unique token. """ # Makes initial token new_token = str(random.randint(1000, 9999)) # Checks to see if the token created is unique # What if ALL tokens already taken? Well, that would suck! while Game.objects.filter(token=new_token).exists(): new_token = str(random.randint(1000, 9999)) # Make new game in database with the token if 'game_mode' not in request.session: request.session['game_mode'] = request.POST['game_mode'] game = Game(token=new_token, mode=request.session['game_mode']) game.save() if not request.user.is_authenticated(): _give_random_name(request) try: _attach_user_to_game(game, request) except IntegrityError: return redirect(reverse('game:index')) return HttpResponseRedirect(reverse('game:pre_game_room', args=(new_token,)))
def test_user_get(self): # Not authenticated response = self.client.get(reverse("api:user-detail", kwargs={"pk": self.user.id})) self.assertEqual(response.status_code, 403) # Normal user authenticated self.client.login(username=self.user.username, password="password") response = self.client.get(reverse("api:user-detail", kwargs={"pk": self.staff_user.id})) self.assertEqual(response.status_code, 404) response = self.client.get(reverse("api:user-detail", kwargs={"pk": self.user.id})) self.assertEqual(response.status_code, 200) self.assertEqual(response.data["username"], self.user.username) # Staff user authenticated self.client.login(username=self.staff_user.username, password="password") response = self.client.get(reverse("api:user-detail", kwargs={"pk": self.staff_user.id})) self.assertEqual(response.status_code, 200) response = self.client.get(reverse("api:user-detail", kwargs={"pk": self.user.id})) self.assertEqual(response.status_code, 200)
def test_profile_get(self): # Not authenticated response = self.client.get(reverse("api:profile-detail", kwargs={"pk": self.profile.id})) self.assertEqual(response.status_code, 200) response = self.client.get(reverse("api:profile-detail", kwargs={"pk": self.site_profile.id})) self.assertEqual(response.status_code, 404) response = self.client.get(reverse("api:profile-detail", kwargs={"pk": self.self_profile.id})) self.assertEqual(response.status_code, 404) # Normal user authenticated self.client.login(username=self.user.username, password="password") response = self.client.get(reverse("api:profile-detail", kwargs={"pk": self.profile.id})) self.assertEqual(response.status_code, 200) response = self.client.get(reverse("api:profile-detail", kwargs={"pk": self.site_profile.id})) self.assertEqual(response.status_code, 200) response = self.client.get(reverse("api:profile-detail", kwargs={"pk": self.self_profile.id})) self.assertEqual(response.status_code, 404) # Staff user authenticated self.client.login(username=self.staff_user.username, password="password") response = self.client.get(reverse("api:profile-detail", kwargs={"pk": self.profile.id})) self.assertEqual(response.status_code, 200) response = self.client.get(reverse("api:profile-detail", kwargs={"pk": self.site_profile.id})) self.assertEqual(response.status_code, 200) response = self.client.get(reverse("api:profile-detail", kwargs={"pk": self.self_profile.id})) self.assertEqual(response.status_code, 200)
def get(self, request, *args, **kwargs): """See if we have a direct match. If so redirect, if not, search. Try fetching a remote profile if the search term is a handle. """ try: q = safe_text(request.GET.get("q")) if q: q = q.strip() validate_email(q) except ValidationError: pass else: profile = None try: profile = Profile.objects.visible_for_user(request.user).get(handle=q) except Profile.DoesNotExist: # Try a remote search remote_profile = retrieve_remote_profile(q) if remote_profile: profile = Profile.from_remote_profile(remote_profile) if profile: return redirect(reverse("users:profile-detail", kwargs={"guid": profile.guid})) return super().get(request, *args, **kwargs)
def setUpTestData(cls): super().setUpTestData() user = UserFactory() not_related_user = UserFactory() replying_user = UserFactory() replying_user2 = UserFactory() sharing_user = UserFactory() replying_user3 = UserFactory() cls.content = ContentFactory(author=user.profile) cls.not_related_content = ContentFactory(author=not_related_user.profile) cls.reply = ContentFactory(author=replying_user.profile, parent=cls.content) cls.reply2 = ContentFactory(author=replying_user2.profile, parent=cls.content) cls.share = ContentFactory(author=sharing_user.profile, share_of=cls.content) cls.reply3 = ContentFactory(author=replying_user3.profile, parent=cls.share) cls.content_url = "http://127.0.0.1:8000%s" % reverse( "content:view-by-slug", kwargs={"pk": cls.content.id, "slug": cls.content.slug} ) cls.participant_emails = [ user.email, replying_user.email, sharing_user.email, replying_user3.email, ]
def test_send_get_request_via_user_viewset(self): # list GET : POST # retrive / patch / des / GET:PUT:DELETE admin_user = mixer.blend( 'auth.User', is_staff=True, is_superuser=True) app = self.set_oauth2_app_by_admin(admin_user) access_token = self.get_token(admin_user, app) url = reverse('user-list') self.client.credentials( HTTP_AUTHORIZATION=f'Bearer {access_token}' ) response = self.client.get(url, format='json') assert response.status_code == status.HTTP_200_OK
def test_make_sale_quickbuy_success(self, fulfill, can_fulfill): can_fulfill.return_value = True response = self.client.post( reverse('quickbuy', args=(1,)), {"quickbuy": "jokke 1"} ) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, "stregsystem/index_sale.html") assertCountEqual(self, response.context["products"], { Product.objects.get(id=1) }) self.assertEqual(response.context["member"], Member.objects.get(username="jokke")) fulfill.assert_called_once_with(PayTransaction(900))
def test_quicksale_increases_bought(self): before = Product.objects.get(id=2) before_bought = before.bought before_member = Member.objects.get(username="jokke") response = self.client.post( reverse('quickbuy', args=(1,)), {"quickbuy": "jokke 2"} ) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, "stregsystem/index_sale.html") after = Product.objects.get(id=2) after_member = Member.objects.get(username="jokke") self.assertEqual(before_bought + 1, after.bought) # 900 is the product price self.assertEqual(before_member.balance - 900, after_member.balance)
def test_quicksale_quanitity_none_noincrease(self): before = Product.objects.get(id=1) before_member = Member.objects.get(username="jokke") response = self.client.post( reverse('quickbuy', args=(1,)), {"quickbuy": "jokke 1"} ) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, "stregsystem/index_sale.html") after = Product.objects.get(id=1) after_member = Member.objects.get(username="jokke") self.assertEqual(before.bought, after.bought) # 900 is the product price self.assertEqual(before_member.balance - 900, after_member.balance)
def test_quicksale_out_of_stock(self): before = Product.objects.get(id=1) before_member = Member.objects.get(username="jokke") response = self.client.post( reverse('quickbuy', args=(1,)), {"quickbuy": "jokke 3"} ) self.assertEqual(response.status_code, 200) # I don't know which template to use (I should probably make one). So # for now let's just make sure that we at least don't use the one that # says "correct" - Jesper 14/09-2017 self.assertTemplateNotUsed(response, "stregsystem/index_sale.html") after = Product.objects.get(id=1) after_member = Member.objects.get(username="jokke") self.assertEqual(before.bought, after.bought) self.assertEqual(before_member.balance, after_member.balance)
def test_quicksale_product_not_in_room(self): before_product = Product.objects.get(id=4) before_member = Member.objects.get(username="jokke") response = self.client.post( reverse('quickbuy', args=(1,)), {"quickbuy": "jokke 4"} ) after_product = Product.objects.get(id=4) after_member = Member.objects.get(username="jokke") self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, "stregsystem/error_productdoesntexist.html") self.assertEqual(before_product.bought, after_product.bought) self.assertEqual(before_member.balance, after_member.balance)
def test_quicksale_product_available_all_rooms(self): before_product = Product.objects.get(id=1) before_member = Member.objects.get(username="jokke") response = self.client.post( reverse('quickbuy', args=(1,)), {"quickbuy": "jokke 1"} ) after_product = Product.objects.get(id=1) after_member = Member.objects.get(username="jokke") self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, "stregsystem/index_sale.html") self.assertEqual(before_member.balance - 900, after_member.balance)
def start_game(request, token): """ The game is initiated through this view, not actually displayed though """ # current_game can use refactoring to be queryset for easier updating and cleaner code current_game = Game.objects.get(token=token) current_game.game_active = True current_game.save() if request.session['game_mode'] == HOTSEAT_MODE: return HttpResponseRedirect(reverse('game:game_lobby', args=(token,))) elif request.session['game_mode'] == MULTIPLAYER_MODE: # initiallizes round 1 for all users in a multiplayer game users = User.objects.filter(usergame__game__token=token) for user in users: GameRound.objects.update_or_create( round_number=1, user=user, game=current_game, origin_user=user) current_game.total_rounds = len(users) current_game.mode = MULTIPLAYER_MODE current_game.save() return HttpResponseRedirect(reverse('game:multi_game_lobby', args=(token,)))
def pass_on(request, token): g = Game.objects.get(token=token) # Hotseat mode if g.mode == 'hotseat': g.current_round += 1 g.save() return HttpResponseRedirect(reverse('game:game_lobby', args=(token,))) # Multiplayer mode if g.mode == 'multiplayer': game_round = g.gameround_set.get( user=request.user, round_number=g.current_round) game_round.committed = True game_round.save() return HttpResponseRedirect(reverse('game:waiting_room', args=(token,))) # ================== MULTIPLAYER GAMEPLAY =========================
def test_access_checkout_url_with_empty_cart(self): """ Test when accessing /checkout url without items in cart will redirect back to cart """ session = self.client.session request = self.client.get(reverse('checkout:index')) request.session = session request.user = self.anonymous_user cart = get_cart(request) self.assertEqual(cart, None, "Cart should not exists") self.assertRedirects( request, reverse('cart:index'), 302, 200, "It should be redirected to cart index." )
def test_cart_available_in_checkout(self): """ Test if checkout is receiving Cart instance """ session = self.client.session test_cart = self._create_testing_cart() self._create_testing_cart_item( cart_instance=test_cart, product_instance=self.test_product ) test_cart.session_key = session.session_key test_cart.save() r = self.client.get(reverse('checkout:index')) r.session = session r.user = self.anonymous_user self.assertEqual(r.context['cart'], test_cart) self.assertEqual(r.status_code, 200) self.assertTemplateUsed(r, 'checkout_index.html')
def _search_by_field(self, field_name, search_term): """Search by field.""" self.authenticate() url = reverse('bookdocument-list', kwargs={}) data = {} # Should contain 20 results response = self.client.get(url, data) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.data['results']), self.all_count) # Should contain only 10 results filtered_response = self.client.get( url + '?search={}'.format(search_term), data ) self.assertEqual(filtered_response.status_code, status.HTTP_200_OK) self.assertEqual( len(filtered_response.data['results']), self.special_count )
def _search_by_nested_field(self, search_term): """Search by field.""" self.authenticate() url = reverse('citydocument-list', kwargs={}) data = {} # Should contain 20 results response = self.client.get(url, data) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.data['results']), self.all_cities_count) # Should contain only 10 results filtered_response = self.client.get( url + '?search={}'.format(search_term), data ) self.assertEqual(filtered_response.status_code, status.HTTP_200_OK) self.assertEqual( len(filtered_response.data['results']), self.switz_cities_count )
def setUpClass(cls): """Set up.""" cls.geo_origin = factories.PublisherFactory.create( **{ 'latitude': 48.8549, 'longitude': 2.3000, } ) cls.geo_in_count = 5 cls.unit = 'km' cls.algo = 'plane' cls.geo_in = [] for index in range(cls.geo_in_count): __publisher = factories.PublisherFactory.create( **{ 'latitude': 48.8570 + index, 'longitude': 2.3005, } ) cls.geo_in.append(__publisher) cls.base_publisher_url = reverse('publisherdocument-list', kwargs={}) call_command('search_index', '--rebuild', '-f')
def _test_pagination(self): """Test pagination.""" self.authenticate() publishers_url = reverse('publisherdocument-list', kwargs={}) books_url = reverse('bookdocument-list', kwargs={}) data = {} invalid_page_url = books_url + '?page=3&page_size=30' invalid_response = self.client.get(invalid_page_url, data) self.assertEqual( invalid_response.status_code, status.HTTP_404_NOT_FOUND ) valid_page_url = publishers_url + '?limit=5&offset=8' # Check if response now is valid valid_response = self.client.get(valid_page_url, data) self.assertEqual(valid_response.status_code, status.HTTP_200_OK) # Check totals self.assertEqual(len(valid_response.data['results']), 5)
def index(request, sitemaps, template_name='sitemap_index.xml', content_type='application/xml', sitemap_url_name='django.contrib.sitemaps.views.sitemap'): req_protocol = request.scheme req_site = get_current_site(request) sites = [] for section, site in sitemaps.items(): if callable(site): site = site() protocol = req_protocol if site.protocol is None else site.protocol sitemap_url = reverse(sitemap_url_name, kwargs={'section': section}) absolute_url = '%s://%s%s' % (protocol, req_site.domain, sitemap_url) sites.append(absolute_url) for page in range(2, site.paginator.num_pages + 1): sites.append('%s?p=%s' % (absolute_url, page)) return TemplateResponse(request, template_name, {'sitemaps': sites}, content_type=content_type)
def label_for_value(self, value): key = self.rel.get_related_field().name try: obj = self.rel.model._default_manager.using(self.db).get(**{key: value}) except (ValueError, self.rel.model.DoesNotExist): return '' label = ' <strong>{}</strong>' text = Truncator(obj).words(14, truncate='...') try: change_url = reverse( '%s:%s_%s_change' % ( self.admin_site.name, obj._meta.app_label, obj._meta.object_name.lower(), ), args=(obj.pk,) ) except NoReverseMatch: pass # Admin not registered for target model. else: text = format_html('<a href="{}">{}</a>', change_url, text) return format_html(label, text)
def password_change(self, request, extra_context=None): """ Handles the "change password" task -- both form display and validation. """ from django.contrib.admin.forms import AdminPasswordChangeForm from django.contrib.auth.views import password_change url = reverse('admin:password_change_done', current_app=self.name) defaults = { 'password_change_form': AdminPasswordChangeForm, 'post_change_redirect': url, 'extra_context': dict(self.each_context(request), **(extra_context or {})), } if self.password_change_template is not None: defaults['template_name'] = self.password_change_template request.current_app = self.name return password_change(request, **defaults)
def response_post_save_add(self, request, obj): """ Figure out where to redirect after the 'Save' button has been pressed when adding a new object. """ opts = self.model._meta if self.has_change_permission(request, None): post_url = reverse('admin:%s_%s_changelist' % (opts.app_label, opts.model_name), current_app=self.admin_site.name) preserved_filters = self.get_preserved_filters(request) post_url = add_preserved_filters({'preserved_filters': preserved_filters, 'opts': opts}, post_url) else: post_url = reverse('admin:index', current_app=self.admin_site.name) return HttpResponseRedirect(post_url)
def response_post_save_change(self, request, obj): """ Figure out where to redirect after the 'Save' button has been pressed when editing an existing object. """ opts = self.model._meta if self.has_change_permission(request, None): post_url = reverse('admin:%s_%s_changelist' % (opts.app_label, opts.model_name), current_app=self.admin_site.name) preserved_filters = self.get_preserved_filters(request) post_url = add_preserved_filters({'preserved_filters': preserved_filters, 'opts': opts}, post_url) else: post_url = reverse('admin:index', current_app=self.admin_site.name) return HttpResponseRedirect(post_url)
def test_limited_admin(self): urls = [ reverse('admin:app_category_changelist'), reverse('admin:app_category_change', args=(self.wikipedia.pk, )) ] for url in urls: response = self.client.get(url) self.assertEquals(response.status_code, 200) with override('nl'): response = self.client.get(url) self.assertEquals(response.status_code, 200) with override('de'): response = self.client.get(url) self.assertEquals(response.status_code, 200)
def test_image_upload(self): # Anonymous user response = self.client.post(reverse("api-image-upload"), {"image": self.get_temp_image()}, format="multipart") self.assertEqual(response.status_code, 403) # User self.client.force_authenticate(self.user) response = self.client.post(reverse("api-image-upload"), {"image": self.get_temp_image()}, format="multipart") self.assertEqual(response.status_code, 201) code = response.data["code"] url = response.data["url"] self.assertIn("![](http://127.0.0.1:8000/media/uploads/", code) self.assertIn("http://127.0.0.1:8000/media/uploads/", url) image_upload = ImageUpload.objects.filter(user=self.user).first() self.assertEqual(image_upload.image.name, url.replace("http://127.0.0.1:8000/media/", ""))
def test_last_id_is_respected(self): self.get("%s?last_id=%s" % (reverse("api-streams:public"), self.content2.id)) self.assertEqual(len(self.last_response.data), 1) self.assertEqual(self.last_response.data[0]["id"], self.content.id)
def test_profile_edit(self): # Not authenticated response = self.client.patch(reverse("api:profile-detail", kwargs={"pk": self.profile.id}), {"name": "foo"}) self.assertEqual(response.status_code, 403) response = self.client.patch( reverse("api:profile-detail", kwargs={"pk": self.site_profile.id}), {"name": "foo"} ) self.assertEqual(response.status_code, 403) response = self.client.patch( reverse("api:profile-detail", kwargs={"pk": self.self_profile.id}), {"name": "foo"} ) self.assertEqual(response.status_code, 403) # Normal user authenticated self.client.login(username=self.user.username, password="password") response = self.client.patch(reverse("api:profile-detail", kwargs={"pk": self.profile.id}), {"name": "foo"}) self.assertEqual(response.status_code, 200) response = self.client.patch( reverse("api:profile-detail", kwargs={"pk": self.site_profile.id}), {"name": "foo"} ) self.assertEqual(response.status_code, 403) response = self.client.patch( reverse("api:profile-detail", kwargs={"pk": self.self_profile.id}), {"name": "foo"} ) self.assertEqual(response.status_code, 404) # Staff user authenticated self.client.login(username=self.staff_user.username, password="password") response = self.client.patch(reverse("api:profile-detail", kwargs={"pk": self.profile.id}), {"name": "foo"}) self.assertEqual(response.status_code, 403) response = self.client.patch( reverse("api:profile-detail", kwargs={"pk": self.site_profile.id}), {"name": "foo"} ) self.assertEqual(response.status_code, 403) response = self.client.patch( reverse("api:profile-detail", kwargs={"pk": self.self_profile.id}), {"name": "foo"} ) self.assertEqual(response.status_code, 403)
def test_user_add_follower(self): # Not authenticated response = self.client.post(reverse("api:profile-add-follower", kwargs={"pk": self.profile.id}), { "guid": self.profile.guid, }) self.assertEqual(response.status_code, 403) # Normal user authenticated self.client.login(username=self.user.username, password="password") response = self.client.post(reverse("api:profile-add-follower", kwargs={"pk": self.staff_profile.id}), { "guid": self.profile.guid, }) self.assertEqual(response.status_code, 404) response = self.client.post(reverse("api:profile-add-follower", kwargs={"pk": self.profile.id}), { "guid": self.site_profile.guid, }) self.assertEqual(response.status_code, 200) self.assertEqual(response.data["status"], "Follower added.") # Staff user authenticated self.client.login(username=self.staff_user.username, password="password") response = self.client.post(reverse("api:profile-add-follower", kwargs={"pk": self.profile.id}), { "guid": self.staff_profile.guid, }) self.assertEqual(response.status_code, 403) response = self.client.post(reverse("api:profile-add-follower", kwargs={"pk": self.staff_profile.id}), { "guid": self.profile.guid, }) self.assertEqual(response.status_code, 200) self.assertEqual(response.data["status"], "Follower added.")
def test_user_remove_follower(self): # Not authenticated response = self.client.post(reverse("api:profile-remove-follower", kwargs={"pk": self.profile.id}), { "guid": self.profile.guid, }) self.assertEqual(response.status_code, 403) # Normal user authenticated self.client.login(username=self.user.username, password="password") response = self.client.post(reverse("api:profile-remove-follower", kwargs={"pk": self.staff_profile.id}), { "guid": self.profile.guid, }) self.assertEqual(response.status_code, 404) response = self.client.post(reverse("api:profile-remove-follower", kwargs={"pk": self.profile.id}), { "guid": self.staff_profile.guid, }) self.assertEqual(response.status_code, 200) self.assertEqual(response.data["status"], "Follower removed.") # Staff user authenticated self.client.login(username=self.staff_user.username, password="password") response = self.client.post(reverse("api:profile-remove-follower", kwargs={"pk": self.profile.id}), { "guid": self.staff_profile.guid, }) self.assertEqual(response.status_code, 403) response = self.client.post(reverse("api:profile-remove-follower", kwargs={"pk": self.staff_profile.id}), { "guid": self.profile.guid, }) self.assertEqual(response.status_code, 200) self.assertEqual(response.data["status"], "Follower removed.")
def test_returns_a_result(self): self.get("%s?q=%s" % (reverse("search:global"), "foobar")) self.assertResponseContains("Results", html=False) self.assertResponseContains(self.public_profile.name, html=False) self.assertResponseContains(self.public_profile.username_part, html=False)
def test_direct_profile_match_goes_to_profile_view(self): self.get("%s?q=%s" % (reverse("search:global"), self.public_profile.handle), follow=True) self.assertResponseNotContains("Results", html=False) self.assertEqual(self.context["view"].__class__, ProfileAllContentView) self.assertEqual(self.context["object"], self.public_profile)
def test_dict_for_view_for_author(self): Profile.objects.filter(id=self.profile.id).update(name="Foo Bar") self.assertEqual(self.public_content.dict_for_view(self.user), { "author": self.public_content.author_id, "author_guid": self.public_content.author.guid, "author_handle": self.public_content.author.handle, "author_home_url": self.public_content.author.home_url, "author_image": self.public_content.author.safer_image_url_small, "author_is_local": bool(self.public_content.author.user), "author_name": self.public_content.author.handle, "author_profile_url": self.public_content.author.get_absolute_url(), "content_type": self.public_content.content_type.string_value, "delete_url": reverse("content:delete", kwargs={"pk": self.public_content.id}), "detail_url": self.public_content.get_absolute_url(), "formatted_timestamp": self.public_content.timestamp, "guid": self.public_content.guid, "has_shared": False, "humanized_timestamp": self.public_content.humanized_timestamp, "id": self.public_content.id, "is_authenticated": True, "is_author": True, "is_following_author": False, "parent": "", "profile_id": self.public_content.author.id, "rendered": self.public_content.rendered, "reply_count": 0, "reply_url": reverse("content:reply", kwargs={"pk": self.public_content.id}), "shares_count": 0, "slug": self.public_content.slug, "through": self.public_content.id, "update_url": reverse("content:update", kwargs={"pk": self.public_content.id}), })
def test_dict_for_view_edited_post(self): with freeze_time(self.public_content.created + datetime.timedelta(minutes=16)): self.public_content.save() self.assertEqual(self.public_content.dict_for_view(self.user), { "author": self.public_content.author_id, "author_guid": self.public_content.author.guid, "author_handle": self.public_content.author.handle, "author_home_url": self.public_content.author.home_url, "author_image": self.public_content.author.safer_image_url_small, "author_is_local": bool(self.public_content.author.user), "author_name": self.public_content.author.handle, "author_profile_url": self.public_content.author.get_absolute_url(), "content_type": self.public_content.content_type.string_value, "delete_url": reverse("content:delete", kwargs={"pk": self.public_content.id}), "detail_url": self.public_content.get_absolute_url(), "formatted_timestamp": self.public_content.timestamp, "guid": self.public_content.guid, "has_shared": False, "humanized_timestamp": "%s (edited)" % self.public_content.humanized_timestamp, "id": self.public_content.id, "is_authenticated": True, "is_author": True, "is_following_author": False, "parent": "", "profile_id": self.public_content.author.id, "rendered": self.public_content.rendered, "reply_count": 0, "reply_url": reverse("content:reply", kwargs={"pk": self.public_content.id}), "shares_count": 0, "slug": self.public_content.slug, "through": self.public_content.id, "update_url": reverse("content:update", kwargs={"pk": self.public_content.id}), })
def get_absolute_url(self): if self.slug: return reverse("content:view-by-slug", kwargs={"pk": self.id, "slug": self.slug}) return reverse("content:view", kwargs={"pk": self.id})
def test_home(self): """Test for url 'base:home'. Visit the url of name 'home' and check it loads the content """ self.browser.visit(self.live_server_url + reverse('home')) time.sleep(0.3) self.assertTrue(self.browser.is_text_present('Hello, world!'))
def test_robots(self): """Test for url 'base:base_files(robots.txt)'. Visit the url of robots.txt and check it loads the file """ self.browser.visit(self.live_server_url + reverse('base_files', kwargs={'filename': 'robots.txt'})) time.sleep(0.3) self.assertTrue(self.browser.is_text_present('robotstxt'))
def test_humans(self): """Test for url 'base:base_files(humans.txt)'. Visit the url of humans.txt and check it loads the file """ self.browser.visit(self.live_server_url + reverse('base_files', kwargs={'filename': 'humans.txt'})) time.sleep(0.3) self.assertTrue(self.browser.is_text_present('humanstxt'))
def associate(request, project_id, task_id, project_or_task): # Submit the data submit_result = project_tasks( project_id_id=project_id, task_id_id=task_id, change_user=request.user, ) submit_result.save() # Once we assign them together, we go back to the original if project_or_task == "P": return HttpResponseRedirect(reverse('project_information', args={project_id})) else: return HttpResponseRedirect(reverse('task_information', args={task_id}))
def delete_campus_contact(request, customers_campus_id, cust_or_camp): """ So... I will need to add in security to define IF a user can do this action """ save_customers_campus = customers_campus.objects.get(pk=customers_campus_id) save_customers_campus.is_deleted = "TRUE" save_customers_campus.change_user = request.user save_customers_campus.save() print(save_customers_campus.campus_id.id) if cust_or_camp=="CAMP": return HttpResponseRedirect(reverse('campus_information', args={save_customers_campus.campus_id.id})) else: return HttpResponseRedirect(reverse('customer_information', args={save_customers_campus.customer_id.customer_id}))
def delete_cost(request, cost_id, location_id, project_or_task): # Delete the cost cost_save = costs.objects.get(pk=cost_id) cost_save.is_deleted = "TRUE" cost_save.change_user=request.user cost_save.save() # Once we assign them together, we go back to the original if project_or_task == "P": return HttpResponseRedirect(reverse('project_information', args={location_id})) else: return HttpResponseRedirect(reverse('task_information', args={location_id}))
def delete_opportunity_permission(request, opportunity_id, groups_id, assigned_user): """ Method ~~~~~~ 1.) If groups_id not empty, remove the permissions 2.) If user_id not empty, remove the permissions 3.) If the count of active permissions for the opportunity is 0, add the permission "ALL USERS" """ opportunity_instance = opportunity.objects.get(opportunity_id=opportunity_id) if (not groups_id == 0): # Will remove the ALL USERS permissions now that we have limited the permissions opportunity_permissions.objects.filter( opportunity_id=opportunity_instance, groups_id=groups_id, is_deleted='FALSE' ).update(is_deleted='TRUE') if (not assigned_user == 0): # Will remove the ALL USERS permissions now that we have limited the permissions opportunity_permissions.objects.filter( opportunity_id=opportunity_instance, assigned_user=assigned_user, is_deleted='FALSE' ).update(is_deleted='TRUE') if (opportunity_permissions.objects.filter(opportunity_id=opportunity_id,is_deleted='FALSE').count() == 0): #Add all users permission_save=opportunity_permissions( opportunity_id=opportunity_instance, all_users='TRUE', user_id=request.user, change_user=request.user, ) permission_save.save() return HttpResponseRedirect(reverse('opportunity_information', args={opportunity_id})) #MyModel.objects.filter(pk=some_value).update(field1='some value')
def logout(request): # log the user out and go to login page auth.logout(request) return HttpResponseRedirect(reverse('login'))
def next_step(request, next_step_id, opportunity_id): next_step_save = opportunity_next_step.objects.get(id=next_step_id) next_step_save.next_step_completed = 1 next_step.change_user=request.user next_step_save.save() return HttpResponseRedirect( reverse( opportunity_information, args={opportunity_id} ) )
def resolve_project(request, project_id): project_update = project.objects.get(project_id=project_id) project_update.project_status = 'Resolved' project_update.change_user=request.user project_update.save() return HttpResponseRedirect(reverse('active_projects'))
def resolve_task(request, task_id): task_update = tasks.object.get(task_id=task_id) task_update.task_status = 'Resolved' task_update.change_user=request.user task_update.save() return HttpResponseRedirect(reverse('active_projects'))