我正在为Django的项目构建虚假的社交网络。我已实施允许用户关注'其他如果需要(或者如果他们选择则根本没有)。但到目前为止,每次创建用户时,该用户都会自动跟踪'数据库中的所有其他用户。我不知道如何解决这个问题。
以下是模型:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
bio = models.CharField(max_length=200, blank=True)
followers = models.ManyToManyField('Profile',
related_name="followers_profile",
blank=True, symmetrical=False)
following = models.ManyToManyField('Profile',
related_name="following_profile",
blank=True, symmetrical=False)
avatar_thumbnail = ProcessedImageField(upload_to='profile_images',
processors=[ResizeToFill(320, 320)],
format='JPEG',
options={'quality': 40},
blank=True)
feed_type = models.CharField(max_length=8, choices=GENDER_CHOICES,
default='Both')
# @receiver(post_save, sender=User)
# def create_user_profile(sender, instance, created, **kwargs):
# if created:
# Profile.objects.create(user=instance)
#
# @receiver(post_save, sender=User)
# def save_user_profile(sender, instance, **kwargs):
# instance.profile.save()
def get_number_of_followers(self):
if self.followers.count():
return self.followers.count()
else:
return 0
def get_number_of_following(self):
if self.following.count():
return self.following.count()
else:
return 0
def __str__(self):
return self.user.username
以下是构建用户和配置文件的视图以及处理用户创建数据的表单:
def signup(request):
form = UserCreateForm()
if request.method == 'POST':
form = UserCreateForm(request.POST)
if form.is_valid():
form.save()
user = User.objects.get(username=request.POST['username'])
user_profile = Profile(user=user)
user_profile.save()
new_user = authenticate(username=form.cleaned_data['username'],
password=form.cleaned_data['password1'])
login(request,new_user)
return redirect('index')
return render(request, 'userapp/signup.html', {
'form': form
})
这是UserCreationForm:
class UserCreateForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = {"username", "email", "password1","password2"}
def save(self, commit=True):
user = super(UserCreateForm, self).save(commit=False)
user.email =self.cleaned_data["email"]
if commit:
user.save()
return user