Melissa Stewart
Melissa Stewart

Reputation: 3605

Many-to-one relationship in Django

I'm new to django thus the question. This is my Location object,

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)

And this is my modified User object

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)

This is the User Registration API view

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, '[email protected]']
            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)

And this is the relevant url

url(r'^register/$', RegisterView.as_view(), name='register')

Now I want to modify this endpoint to take a location id as a path param and then add the logic in my UserCreation function that the user is added to the location as described by the id. Can someone help me do this ?

Upvotes: 3

Views: 769

Answers (1)

Astik Anand
Astik Anand

Reputation: 13047

You can do this way:

url(r'^register/(?P<location_id>[\w.-]+)/$', RegisterView.as_view(), name='regist

and then,

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()

Upvotes: 1

Related Questions