Итак, я пытался добавить свой собственный генератор QRCode в мое приложение django, чтобы информация о пользователе также сохранялась в пользовательский QRCode с изображением посередине. И я хочу, чтобы QRCode был сохранен в моей базе данных (я использую mysql), чтобы я мог отобразить этот QRCode на панели пользователя. Как я могу это сделать? Функция QRCode - это qrr ()
#models.py
from django.db import models
from django.contrib.auth.models import User
from django_countries.fields import CountryField
from phonenumber_field.modelfields import PhoneNumberField
from short_text_field.models import ShortTextField
class UserProfileInfo(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
nama_lengkap = models.CharField(default="", null=False, max_length=30)
birthdate = models.DateField(default="")
city = ShortTextField(default='', blank=True, help_text="Masukkan nama kota dengan benar")
GENDER_CHOICES = (('Laki-laki', 'Laki-laki'), ('Perempuan', 'Perempuan'))
gender = models.CharField(choices=GENDER_CHOICES, max_length=10)
phone_number = PhoneNumberField(default='+62',null=False, blank=False, unique=True, max_length=15)
qrcode = models.ImageField(default="")
Akun_Instagram = models.CharField(blank=True, null=False, default="@", max_length=35)
bio = models.TextField(default='', blank=True)
def __str__(self):
return self.user.username
#views.py
from django.shortcuts import render
from accounts.forms import UserForm,UserProfileInfoForm
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect, HttpResponse
from django.urls import reverse
from django.contrib.auth.decorators import login_required
from PIL import Image
from django.contrib.auth.models import User
from accounts.models import UserProfileInfo
import qrcode
def index(request):
return render(request, 'templates/landing.html')
@login_required
def special(request):
return HttpResponse("You are logged in !")\
@login_required
def user_logout(request):
logout(request)
return HttpResponseRedirect(reverse('home'))
def register(request):
registered = False
if request.method == 'POST':
user_form = UserForm(data=request.POST)
profile_form = UserProfileInfoForm(data=request.POST)
if user_form.is_valid() and profile_form.is_valid():
user = user_form.save()
user.set_password(user.password)
user.save()
profile = profile_form.save(commit=False)
profile.user = user
profile.save()
registered = True
else:
print(user_form.errors,profile_form.errors)
else:
user_form = UserForm()
profile_form = UserProfileInfoForm()
return render(request,'accounts/templates/registration/register.html',
{'user_form':user_form,
'profile_form':profile_form,
'registered':registered})
def user_login(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username, password=password)
if user:
if user.is_active:
login(request,user)
return HttpResponseRedirect(reverse('utama'))
else:
return HttpResponse("Your account was inactive.")
else:
print("Someone tried to login and failed.")
print("They used username: {} and password: {}".format(username,password))
return HttpResponse("Invalid login details given")
else:
return render(request, 'accounts/templates/registration/login.html', {})
def dasbor(request):
return render(request, 'accounts/templates/dashboard.html')
def qrr(request):
user = User.username
email = User.email
nama = UserProfileInfoForm.nama_lengkap
ttl = UserProfileInfoForm.birthdate
kelamin = UserProfileInfoForm.gender
telepon = UserProfileInfoForm.phone_number
ig = UserProfileInfoForm.Akun_Instagram
bio = UserProfileInfoForm.bio
alamat = UserProfileInfoForm.city
qr = qrcode.QRCode(
error_correction=qrcode.constants.ERROR_CORRECT_H
)
basewidth = 100
img = Image.open(UserProfileInfo.qrcode)
wpercent = (basewidth/float(img.size[0]))
hsize = int((float(img.size[1])*float(wpercent)))
img = img.resize((basewidth,hsize), Image.ANTIALIAS)
img.save()
qr.add_data('Nama: {}\nUsername: {}\nEmail: {}\nTanggal Lahir: {}\nJenis Kelamin: {}\nNomor Telepon: {}\nKota: {}\nInstagram: {}\nBio: {}').format(nama,user,email,ttl,kelamin,telepon,alamat,bio)
qr.make()
img_qr = qr.make_image(fill_color="orange", back_color="white").convert('RGB')
pos = ((img_qr.size[0] - img.size[0]) // 2, (img_qr.size[1] - img.size[1]) // 2)
img_qr.paste(img,pos)
img_qr.save()
Я новичок в django. Как мне подключить эту функцию qrr к моей базе данных, чтобы изображение сохранялось прямо в моей базе данных? Или я должен поставить эту функцию qrr в models.py?