Home > Net >  Get specific uuid object in view from model in django
Get specific uuid object in view from model in django

Time:08-16

I have django app in which user can upload files in course with 3 editable fields.

models.py

class Course(models.Model):
    course_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True)
    title = models.CharField(max_length=20)
    thumbnail = models.ImageField(upload_to='thumbnails', null=False, default='default.jpg')
    videofile = models.FileField(validators=[FileExtensionValidator], upload_to='videos')
    
    def path(self):
        return self.url

I have view to display those the thumbnails of all courses and when user click on thumbnail it redirects him to course detail page.

urls.py

path('course/<uuid:course_id>/', views.course_detail, name='course-detail')

So my question is how can I get information about fields of model Course in my html file to display them.

views.py

def course_detail(request, *args, **kwargs):
    course = models.Course.objects.get()
    context = {
        'course': course,
    }
    return render(request, 'courses/info_course_view.html', context)

Without uuid i would just write pk=pk in brackets but since i use uuid i don't know how to make it work.

template

<div >
    {{ course.title }}
</div>

CodePudding user response:

You probably have to modify your views and urls file as follows:

urls.py:

path('course/<str:course_id>/', views.course_detail, name='course-detail')

views.py:

def course_detail(request, course_id):
    course = models.Course.objects.get(course_id=course_id)
    context = {
        'course': course,
    }
    return render(request, 'courses/info_course_view.html', context)

template file:

<div >
{{ course.title }}
</div>

In fact, the main issue is that you didn't put the course_id inside the course argument.

  • Related