1

I'm using Django REST Framework that will allow users to save information and generate QR code image which will be URL of the user profile such as: http://127.0.0.1:8000/user/detail/fahad-md-kamal-fd028af3/

Something Like

enter image description here

How can I access host address from Django Model so that I can use it to generate QR code?

DRF Model

class UserInfo(models.Model):

    def save(self, *args, **kwargs):

        if not self.slug:
            self.slug =f'{slugify(self.name)}'
        qrcode_image = qrcode.make(f"{host}/{self.slug}/")
        super(UserInfo, self).save(*args, **kwargs)

Serializer Class

class UserBaseReadSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = models.UserBase
        fields = (
            'url',
            'phone',
            'name',
            'address',
            'qr_code',
            'slug',
        )

View Class:

    class UserInfoViewSet(viewsets.ModelViewSet):
       serializer_class = serializers.UserBaseSerializer
       queryset = models.UserInfo.objects.all()

While I was doing it with standared Django and Functional View I did it like:

Functional View:

def add_user_info(request):
    if request.method == 'POST':
        form_data = UserInfomationForm(request.POST)
        if form_data.is_valid():
            obj = form_data.save(commit=False)
            obj.save(host =request.META['HTTP_ORIGIN'])

Over ridding Model Class's save method

class UserInfo(models.Model):
    def save(self, host=None, *args, **kwargs):
        if not self.slug:
            self.slug =f'{slugify(self.name)}-{str(uuid.uuid4())[:8]}'
        qrcode_image = qrcode.make(f"{host}/{self.slug}/")
        super(UserInfo, self).save(*args, **kwargs)
Fahad Md Kamal
  • 243
  • 6
  • 20
  • Does this answer your question? [How can I get the full/absolute URL (with domain) in Django?](https://stackoverflow.com/questions/2345708/how-can-i-get-the-full-absolute-url-with-domain-in-django) – Brian Destura Oct 20 '21 at 02:49
  • 1
    The answer gives idea to get host address from functions that have direct or are related to request function. But models do not have direct relation to request. Therefore, it does not answers my question. – Fahad Md Kamal Oct 20 '21 at 04:17
  • Ah I see. You could move the generation of the qr code on another method in the model, and override `UserInfoViewSet`'s `create` method to handle it (where you have access to the request object) – Brian Destura Oct 20 '21 at 05:02
  • In that case if I create an object from admin site than qr code wouldn't be created. – Fahad Md Kamal Oct 20 '21 at 05:05
  • If you are in the admin, is the admin url going to be used? – Brian Destura Oct 20 '21 at 05:34
  • No, it will take only the base URL and append it with username. that's it. – Fahad Md Kamal Oct 21 '21 at 01:46

0 Answers0