0

kindly correct me with the tittle if it is wrong or misleading, thanks.

I am very new to Django Python. I am using Django 3.1.1.

My question is about the "Model".objects.create(), I use it with ajax to save or create data in my Logger model.

Question: How can I link the Logger.userprofile to UserProfile.user using Logger.objects.create() or what is the next thing to do to linked the two fields?

My UserProfile model is already linked to the User model via OneToOneField but was saving data using form.save(), and this was successful. below is what I have constructed so far by following numerous tutorials.

This is already working and it is creating data in my Model, I just need to add the link between the UserProfile and the Logger for the sake of easy identification of the log created.

Log is created in the Logger Model via qrcode scan.

Views.py

def processQRCode(request):

    if request.method == 'POST':
            qrcoderes = request.POST['qrcoderes']
            logged_in = request.POST['logged_in']
            logged_in_location = request.POST['logged_in_location']

            Logger.objects.create(
                qrcode_uuid = qrcoderes, #edited from qrcode_uuid to qrcoderes to distinguish the two variables.
                logged_in = logged_in,
                logged_in_location = logged_in_location 
            )

    return HttpResponse('Success!')

Models.py

UserProfile Model

class UserProfile(models.Model):

    GENDER = (
        ('Male', 'Male'),
        ('Female', 'Female'),
    )

    user = models.OneToOneField(User, related_name='userprofile', null=True, on_delete=models.SET_NULL)

    qrcode_uuid = models.UUIDField(unique=True, default=uuid4)
    qr_code = models.ImageField(upload_to='qr_codes', blank=True)

    firstName = models.CharField(max_length=200)
    middleName = models.CharField(max_length=200)
    lastName = models.CharField(max_length=200)
    gender = models.CharField(max_length=6, choices=GENDER)
    birthdate = models.DateField(max_length=200)
    contact = models.CharField(max_length=200)
    agency = models.CharField(max_length=200) 
    deptSec = models.CharField(max_length=200)
    designation = models.CharField(max_length=200)
    streetHouse = models.CharField(max_length=200)
    purok = models.CharField(max_length=200)
    barangay = models.CharField(max_length=200)
    cityMunicipality = models.CharField(max_length=200)
    province = models.CharField(max_length=200)
    date_created = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name_plural = 'User Profile'

    def __str__(self):
        return self.firstName + " " + self.middleName + " " + self.lastName

    def save(self, *args, **kwargs):
        qrcode_img = qrcode.make(self.qrcode_uuid)
        canvas = Image.new('RGB', (370, 370), 'white')
        draw = ImageDraw.Draw(canvas)
        canvas.paste(qrcode_img)
        fileName = f'qr-code-{self.qrcode_uuid}.png'
        buffer = BytesIO()
        canvas.save(buffer,'PNG')
        self.qr_code.save(fileName, File(buffer), save=False)
        canvas.close()
        super().save(*args, **kwargs)

Logger Model

class Logger(models.Model):
    userprofile = models.OneToOneField(UserProfile, null=True, on_delete=models.SET_NULL)

    qrcode_uuid = models.CharField(max_length=200, null=True)
    logged_in = models.CharField(max_length=1, default="1")
    logged_in_location = models.CharField(max_length=200, null=True)
    log_datetime = models.DateTimeField(auto_now_add=True)

    class Meta:
            verbose_name_plural = 'Logger'

    def __str__(self):
            return self.logged_in_location + " " + self.qrcode_uuid

Ajax.js

function processQRCodeDetails(){

$.ajax({
      type:'POST',
      url: '/processqrcode/',
      data:{
        qrcoderes: $('#process-qrcoderes').val(),
        logged_in: $('#logged_in').val(),
        logged_in_location: $('#logged_in_location').val(),
        csrfmiddlewaretoken: $('input[name="csrfmiddlewaretoken"]').val()
      },
      success: function(data){
        $('#staticBackdrop').modal();
        console.log('Success');
      },
      error: function(data){
        console.log('Error')
      }
    });

}

template.html

<form id="process-qrcoderes-form">
  {% csrf_token %}
  <input class="form-control" type="text" name="process-qrcoderes" id="process-qrcoderes" onchange="processQRCodeDetails(); return false;" autofocus="autofocus">
  <input type="text" name="logged_in" id="logged_in" value="1">
  <input type="text" name="logged_in_location" id="logged_in_location" value="test">
</form>
Markmeplease
  • 145
  • 14

2 Answers2

0

You need to get UserProfile from db and pass it to create method

 def processQRCode(request):
    if request.method == 'POST':
        qrcode_uuid = request.POST['qrcoderes']
        logged_in = request.POST['logged_in']
        logged_in_location = request.POST['logged_in_location']

        # edit: you can get your UserProfile instance by "qrcode_uuid" as well
        # use get_or_create, note that it returns tuple, not instance
        userprofile, created = UserProfile.objects.get_or_create(qrcode_uuid=qrcode_uuid)
 
        if created:
            # some additional actions here for newly created UserProfile, filling some fields may be
            
            # recommended naming convention for class attrs in python is underscore_case, not camelCase
            userprofile.firstName = "John"
            userprofile.save()

        Logger.objects.create(
            qrcode_uuid = qrcode_uuid,
            logged_in = logged_in,
            logged_in_location = logged_in_location,
            userprofile=userprofile
        )

    return HttpResponse('Success!')
Alexey Popov
  • 726
  • 4
  • 8
  • thanks for the response, `logged_in` is you are logged in to a specific location, just like a manual logbook where you are writing your information as a person. logged_in is not use in the login authentication of the system. :) – Markmeplease Sep 25 '20 at 14:02
  • this also means that `request.user` is not application since the user is not actually log in in the system. – Markmeplease Sep 25 '20 at 14:03
  • what I want to achieve is to log all the qrcode_uuid that was scanned via qrcode scanner and linked the `qrcode_uuid` of `Logger,userprofile` to `UserProfile` model to easily identify the log by not just looking at the` uuid` but with the `UserProfile` like fullname. :) – Markmeplease Sep 25 '20 at 14:13
  • thanks for the reply, already did that, but got an error `qrcodemonsys.models.UserProfile.DoesNotExist: UserProfile matching query does not exist.` I am really new in Django, sorry. :) – Markmeplease Sep 26 '20 at 00:23
  • The new edits will add/create new data in the `UserProfle` model not in `Logger` model. – Markmeplease Sep 26 '20 at 07:08
  • @Markmeplease your Logger model has OneToOne relation with UserProfile model, so to link Logger insntance to UserProfile instance you should create both – Alexey Popov Sep 26 '20 at 14:08
  • So, there is no way I can fetch the `UserProfile` to `Logger` Model? I thought, django should just generate something like `Select id from UserProfile where qrcode_uuid == POST['qrcoderes']` to fetch the data I want from `UserProfile` and store it in `Logger` model. – Markmeplease Sep 27 '20 at 08:25
  • @Markmeplease in current example method get_or_create fetches existing instance of UserProfile and if it does not exist creates it, then, in next few lines, we pass fetched or created instance as arg to the create method of Logger "userprofile=userprofile" – Alexey Popov Sep 27 '20 at 11:27
  • I tried it, but it mainly create a data to `UserProfile` model where I have nothing to create upon, I only want to create the `Logger` model where the `Logger.userprofile` is equal on the `UserProfile.id` that is based on the `qrcode_uuid` input. also, `UserProfile` is already created ahead of time and the two Models cannot be created at the same time. – Markmeplease Sep 28 '20 at 02:58
  • `UserProfile` is like an Identification Card where the `qrcode_uuid` is his/her identification number, once you have created your profile, you use your Identification Card to enter a facility where you need to present the QRcode to be able to enter, the system will just Logged your details in the database and later will be use to for auditing. – Markmeplease Sep 28 '20 at 03:01
0

Solved it accidentally.

I don't know what happened to the UUIDField but, got a record which was edited under the UserProfile model (has only 3 records in it), unfortunately and fortunately, when I scanned the 3rd record which was edited using the "Save and Continue editing" of django admin, "it work like a charm!" (as everyone call it when it worked :D), so, I proceeded editing the 2 other records and it worked also.

My primarily goal was to just insert the id of the UserProfile model to Logger model to linked the 2 models using the following syntax:

# been trying this syntax for ages now. lol. and it was not the problem.
userprofile_id = UserProfile.objects.get(qrcode_uuid=qrcoderes) 

    #Note: Using the .objects.create() method also works now.
    log = Logger(
            userprofile = userprofile_id,
            qrcode_uuid = qrcoderes, #edited from qrcode_uuid to qrcoderes to distinguish the two variables.
            logged_in = logged_in,
            logged_in_location = logged_in_location
        )
    log.save()

Note: this was not working, it was giving me an error UserProfile matching query does not exist., even using the shell, it is giving me the same error. So, I thought, my syntax was the problem, that's why I posted my problem here.

Maybe, I'll trying to use the CharField for the UUID if that's makes a difference or if it is compatible for the UUID.

Markmeplease
  • 145
  • 14