'Django: How to autogenerate a random 6 digit string

I would like to generate a unique 6 digit code each time a user clicks "generate code".

Error AttributeError at /subjects/ 'Manager' object has no attribute 'make_random_password'

i have added the templates, models and views used for it.

Full source code: https://github.com/Zainab692/Fyp2/tree/master/django-project/cms

ps. Still a beginner in django

Views.py

class SubjectView(TemplateView):
template_name='subjects.html'
# context='subjects'
random_number = Subject.objects.make_random_password(length=10, allowed_chars='123456789')
while Subject.objects.filter(attendcode__temp_password=random_number):
         random_number = Subject.objects.make_random_password(length=10, allowed_chars='123456789')


def get_context_data(self, *args, **kwargs):
    context = super().get_context_data(*args, **kwargs)
    context['Attendance code']=Subject.objects.all()
    context['subjects'] =Subject .objects.all()
    context['students']=Student.objects.all()
    context['attendace_code']=Subject.objects.get("attendance_code")
    obj = CourseRegistration.objects.filter(subject_code__gt=0)
    no_students=obj.count()

    # no_students=CourseRegistration.objects.all().count()
    context['no_students']=no_students
    return context

def get_success_url(self):
    print(self.kwargs['slug'])
    return reverse('subject', args=(self.kwargs['slug'],))

Template

{% for subject in subjects %}
                        <tbody class="list" style="text-transform:capitalize;">
                            <tr>
                                <th scope="row">
                                <div class="media align-items-center">
                                    <a href="#" class="avatar rounded-circle mr-3">
                                    {% if subject.thumbnail %}
                                        <img alt="Logo" src="{{subject.thumbnail.url}}">
                                    {% endif %}
                                    </a>
                                    <div class="media-body">
                                    <span class="name mb-0 text-sm">{{subject.subject_name}}</span>
                                    </div>
                                </div>
                                </th>
                                <td class="budget">
                                {{subject.subject_code}}
                                </td>
                                <td>
                                <div class="d-flex align-items-center">
                                    <span class="completion mr-2">{{no_students}}</span>
                                </div>
                                </td>
                                <td>
                                <div class="d-flex align-items-center">
                                    <span class="completion mr-2">{{attendace_code}}</span>
                                </div>
                                </td>
                            </tr>
                        </tbody>
                    {% endfor %}

Models.py

class Subject(models.Model):
    subject_name=models.CharField(max_length=1000,unique=True)
    subject_code=models.CharField(max_length=7,primary_key=True)
    lecturer_ID=models.ForeignKey(Lecturer, related_name="subj1_FK",on_delete=models.PROTECT)
    thumbnail=models.ImageField(blank=True,null=True,upload_to=get_thumbnail)


Solution 1:[1]

There's no reason why Subject.objects.make_random_password should be a function at all if you haven't defined it on the Manager object associated with Subjects.

Also, looking at your code on GitHub, I couldn't find a reference to a temp_password field either.

In any case, once you do have a temp_password field that has been set unique=True,

import random
import string

# ...
while True:
    password = "".join(random.choice(string.digits) for x in range(10))
    if not Subject.objects.filter(attendcode__temp_password=password).exists():
        break
# ... do something that creates a `Subject` with the given `password`

Since the random number is not being generated in the database, there is a miniscule chance that you could get a collision between two concurrent requests, but since the field is set unique=True, it will just cause saving to fail and the user to retry.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 AKX