测试类:
class UpadtePadlockTest(TestCase):
username = "testusername"
email = "testuser@name.com"
username2 = "testusername2"
email2 = "testuser2@name.com"
def test_update_padlock(self):
User = get_user_model()
user1 = User.objects.create_user(
self.username, self.email ,
)
user2 = User.objects.create_user(
self.username2, self.email2 , user_locked_with=user1
)
user1.user_locked_with=user2
new_padlock= PadLock.objects.create(start_date=datetime.date(datetime.today()),motto_field="Jodo is my motto",creator=user1,modifier=user2)
response = self.client.post(
reverse('edit_padlock'),
{'start_date':datetime.date(datetime.today()),
'motto_field':"Jodo is not my motto"})
self.assertEqual(response.status_code,302)
new_padlock.refresh_from_db()
self.assertEqual(new_padlock.motto_field,"Jodo is not my motto")
字符串
导致问题的视图
def edit_padlock(request):
# dictionary for initial data with
# field names as keys
context ={}
user = request.user
# this is the attr that the AnonymousUser is lacking "user_locked_with"
# So filtering users by this attr is not possible
user2 = CustomUser.objects.get(username= user.user_locked_with)
# fetch the object related to passed id
try:
obj = PadLock.objects.get(modifier=request.user)
except Exception:
obj = PadLock.objects.get(creator=request.user)
# pass the object as instance in form
form = PadLockForm(request.POST or None, instance = obj)
# save the data from the form and
# redirect to detail_view
if form.is_valid():
user.lock_published = True
user2.lock_published = True
user.save()
user2.save()
form.save()
try:
padlock = PadLock.objects.get(modifier=request.user)
padlock.active_state = True
padlock.save()
except:
padlock = PadLock.objects.get(creator=request.user)
padlock.active_state = True
padlock.save()
return HttpResponseRedirect("/")
# add form dictionary to context
context["form"] = form
return render(request, "edit_padlock.html", context)
型
我的自定义用户:
class CustomUser(AbstractUser):
age= models.PositiveBigIntegerField(null=True,blank=True)
lock_status = models.BooleanField(default=False)
lock_count = models.PositiveIntegerField(default=7,validators=[MaxValueValidator(7),MinValueValidator(0)])
user_is_sender = models.BooleanField(default=False)
user_is_reciever = models.BooleanField(default=False)
user_locked_with = models.CharField(max_length=125,null=True,blank=True)
lock_exist = models.BooleanField(default=False)
lock_published = models.BooleanField(default=False)
型
博客文章又名PadLock模型:
class PadLock(models.Model):
start_date = models.DateField()
lock_nature = models.TextField(max_length=5,choices=lock_natures,default=story)
motto_field = models.CharField(max_length=200)
story_field = models.TextField(max_length=20000,blank=True ,validators=[MinLengthValidator(4000)])
active_state= models.BooleanField(default=False)
creator = models.OneToOneField(get_user_model(),related_name="creator",on_delete=models.CASCADE,null=True)
modifier = models.OneToOneField(get_user_model(),related_name="modifier",on_delete=models.CASCADE,null=True)
def get_absolute_url(self):
return reverse("padlock_detail", args=[str(self.id)])
型
我正在为某个功能编写测试,该功能是修改一篇博客文章并发布该文章,这在我的代码中被称为“挂锁”。我应该重写AnonymousUser类吗?有没有办法避免不必要的麻烦?
1条答案
按热度按时间yr9zkbsy1#
u/Quantra 2112回答了r/djangolearning上的问题
您正在从请求中获取用户,当该用户未通过身份验证时,它将是AnonymousUser的示例。所以你可以在测试客户端上使用login方法:https://docs.djangoproject.com/en/4.2/topics/testing/tools/#django.test.Client.login
然后,您还应该使用login_required装饰器来保护您的视图:https://docs.djangoproject.com/en/4.2/topics/auth/default/#the-login-required-decorator
如果您不想将视图限制为经过身份验证的用户,我会寻找一个使用会话的解决方案,而不是尝试使用AnonymousUser类来做任何事情。https://docs.djangoproject.com/en/4.2/topics/http/sessions/#module-django.contrib.sessions
解决方案是在客户机上使用login方法,并在edit_padlock视图中添加所需的decorator @login。