我对django这个问题很新。 这是我的Location对象,
class Location(models.Model):
country = models.CharField(max_length=255)
city = models.CharField(max_length=255, unique=True)
latitude = models.CharField(max_length=255)
longitude = models.CharField(max_length=255)
这是我修改过的用户对象
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(unique=True, max_length=255)
mobile = PhoneNumberField(null=True)
username = models.CharField(max_length=255, null=True)
full_name = models.CharField(max_length=255, blank=True, null=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
is_active = models.BooleanField(default=False)
is_mobile_verified = models.BooleanField(default=False)
location = models.ForeignKey(Location, on_delete=models.SET_NULL, null=True)
这是用户注册API视图
class RegisterView(views.APIView):
def post(self, request):
serializer = UserSerializer(data=request.data)
if serializer.is_valid():
user = serializer.save()
subject = "Please Activate Your Account!"
token = self._generate()
link = HOST + PREFIX + str(user.id) + SUFFIX + token
message = 'Please use the following link to activate your account.\n\n{}'.format(link)
from_email = settings.EMAIL_HOST_USER
to_list = [user.email, 'melissa@gmail.com']
send_mail(subject, message, from_email, to_list, fail_silently=True)
Token.objects.create(user=user, token=token)
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
这是相关的网址
url(r'^register/$', RegisterView.as_view(), name='register')
现在我想修改此端点以将位置ID作为路径参数,然后在我的UserCreation函数中添加逻辑,用户将其添加到id所描述的位置。 有人可以帮我这么做吗?
答案 0 :(得分:1)
你可以这样做:
url(r'^register/(?P<location_id>[\w.-]+)/$', RegisterView.as_view(), name='regist
然后,
def post(self, request, *args, **kwargs):
self.location_id = kwargs.get('location_id', "any_default")
location = Location.objects.get(id=self.location_id)
# Now assign to user
if serializer.is_valid():
user = serializer.save()
user.location = location
user.save()