Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Create nested/cascading dropdown using django
I am trying to create multiple cascading dropdowns in django. I referred to this DJANGO_2WAY_NESTED_DROPDOWNS but when I tested the code for more than 2 dropdown the code does not works. Any suggestion would help. Cascading Dropdown Image -
UpdateView in django
i am trying to have attendance for student by the teacher, everything is working fine until i want to edit(update) this Student_Attendence model, i am not able to update this model. what if teacher want to update that attendance again, so need to have that i have list of subject and i can check who were(student) in that class(subject). models.py class Subject_Attendence(models.Model): # i am able to update this one, which i dont want to update lecturer = models.ForeignKey(Lecturer, on_delete=models.SET_NULL, blank=True, null=True) department = models.ForeignKey(to='sis.Department', on_delete=models.SET_NULL, blank=True, null=True) semester =models.ForeignKey(to='sis.Semester', on_delete=models.SET_NULL, blank=True, null=True) subject = models.ForeignKey(to='sis.Subject', on_delete=models.SET_NULL, blank=True, null=True) date = models.DateField(blank=True, null=True) def __str__(self): return str(self.subject) def get_absolute_url(self): return reverse('lecturer:student_attendance', kwargs={ 'pk': self.pk }) def get_update_url(self): return reverse('lecturer:subject_attendance_edit', kwargs={ 'pk': self.pk }) class Student_Attendence(models.Model): # want to update this model by the teacher lecturer = models.ForeignKey(Lecturer, on_delete=models.SET_NULL, blank=True, null=True) subject = models.ForeignKey(Subject_Attendence, related_name='subject_attendance', on_delete=models.SET_NULL, blank=True, null=True) student = models.ForeignKey(to='sis.Student', on_delete=models.SET_NULL, blank=True, null=True) date = models.DateField(blank=True, null=True) attend = models.BooleanField(default=False) def __str__(self): return str(self.student) def get_absolute_url(self): return reverse('lecturer:student_attendence_detail', kwargs={ 'pk': self.pk }) def get_update_url(self): return reverse('lecturer:student_attendance_edit', kwargs={ 'pk': self.pk }) views.py class Student_Attendance(generic.ListView): model = Subject_Attendence template_name = 'attendence.html' context_object_name = 'queryset' def get_context_data(self, *args, **kwargs): profile = Lecturer.objects.all() semester_course … -
How can I make my ReportLab table data wrap when data is sent from Django views?
I've been trying to get my cell strings to wrap, the table gets too wide and out of screen. I know that using Paragraph automatically wraps text, but the problem is that I'm sending my data from multiple views so the table width and number of columns varies. I've gotten errors like 'list' object has no attribute 'split', 'tuple' object has no attribute 'split' and even 'Paragraph' object is not iterable. class ComprasPDF(View): def get(self, request, *args, **kwargs): arr= [( o.unidad_inventario.control_stock.almacen, o.unidad_inventario.control_stock.producto, o.proveedor, o.cantidad, o.costo_unidad, ) for o in CompraProducto.objects.all()] data = { 'nombre':'COMPRAS', 'headings':('ALMACEN', 'PRODUCTO', 'PROVEEDOR','CANTIDAD','COSTO POR UNIDAD'), 'query': arr } pdf = generar_pdf(request,data) return HttpResponse(pdf, content_type='application/pdf') And using it on ReportLab like this. As you see, I'm using the data I'm sending directly and I don't know how to apply paragraphs styles to the query data. buff = BytesIO() doc = SimpleDocTemplate(buff,pagesize=A4) story = [] headings = data['headings'] alldata = data['query'] t = Table([headings] + alldata*10) t.setStyle(TableStyle( [ ('GRID', (0, 0), (-1, -1), 1, colors.black), ('BACKGROUND', (0, 0), (-1, 0), colors.gray) ] )) story = [Spacer(0,25),t] doc.build(story, onFirstPage=primera_pagina, onLaterPages=add_numero, ) And the table looks like this. Not even assigning colWidths make them wrap, they just overlap. I need … -
'mod_wsgi-express' is not recognized as an internal or external command, operable program or batch file
I am trying to host the django 3.1(python3.8) app on window 10 with WAMP64 and mod_wsgi API.(Yes its nightmare) Am able to preform the following command sucessfully. 1- set "MOD_WSGI_APACHE_ROOTDIR=C:\wamp64\bin\apache\apache2.4.46" 2- pip install mod_wsgi And the next command which is "mod_wsgi-express module-config" is throwing below error. 'mod_wsgi-express' is not recognized as an internal or external command, operable program or batch file. Please help me with, what am doing wrong or am using mod_wsgi is not the right choice for deploying django app. -
Displaying drop down values based on selection of another drop down using django
class UnassignedShiftForm(forms.ModelForm): date = forms.DateField(required=True, widget=forms.DateInput(attrs= { 'class':'datepicker' })) def __init__(self, *args, **kwargs): self.client = kwargs.pop('client') super(UnassignedForm, self).__init__(*args, **kwargs) self.fields['booked_with'].queryset = Company.objects.filter(client=self.client) self.fields['location'].queryset = ProjectIdentities.objects.filter(client=self.client, is_deleted=False) self.fields['date'].widget.attrs\ .update({ 'placeholder': 'Select Date', 'class': 'input-class_name' }) ward_list =[] location = ProjectIdentities.objects.filter(client=self.client, is_deleted=False) wards = Ward.objects.filter(corporate_identity__client=self.client) for identity in location: if identity.id in wards: ward = identity.id for q in wards: ward_list.append({"identity":q.corporate_identity,"ward":q}) class Meta: model = Unassigned fields = ['date','additional_days', 'positions', 'start_time', 'banding', 'qualification_speciality', 'location','ward', 'charge_rate'] DJANGO VIEW: class UnAssignedShiftCreateView(CreateView): template_name = 'unassigned_form.django.html' form_class = UnassignedShiftForm context_object_name = "shift" model = UnassignedShift def get_form_kwargs(self): kwargs = super(UnAssignedShiftCreateView, self).get_form_kwargs() kwargs["client"] = self.request.user.client return kwargs def form_valid(self, form): self.client = self.request.user.client try: shift_order = UnassignedShift.objects.filter(client=self.client).\ order_by('-id')[0].booking_order_number order_number = int(shift_order.split('-')[1]) order_number = 'US-'+str(order_number + 1) except: order_number = 'US-1' self.object = form.save(commit=False) self.object.client = self.request.user.client self.object.created_by = self.request.user self.object.booking_order_number = order_number addtional_days = form.cleaned_data['additional_days'] date = form.cleaned_data['date'] for i in range(0, int(addtional_days) + 1): try: shift_order = UnassignedShift.objects.filter(client=self.client).\ order_by('-id')[0].shift_number shift_number = int(shift_order.split('-')[1]) shift_number = 'UNS-'+str(shift_number + 1) except: shift_number = 'UNS-1' self.object.pk = None if i == 0: days = 0 else: days = 1 date = date + datetime.timedelta(days=days) self.object.client = self.request.user.client self.object.created_by = self.request.user self.object.booking_order_number = order_number self.object.shift_number = shift_number self.object.date = date try: … -
Can I use Django and Django Rest Framework together?
I am pretty new to Django and I have a question which I can't find an answer and feel confused about it. I have web based system where only admin can create users. I need to use JSON Web Token for Cross Login but the only way I found to implement this is with Django REST Framework. My current app is only Django based right now. My question is can I use both Django and Django REST Framework together so I can make my JWT for this part, but stayed with Django where is possible? -
Celery response queue is consuming but not acknowledging
I have a django application that has a rest endpoint which puts tasks in a queue and waits for the result through a callback. Unfortunately this leads to the callback function being executed, but the task is never acknowledged or consumed from rabbit. Means it stays in the queue even though the callback method finishes. The response that remains in the queue looks like after consuming (but also before): This is the code in the rest-framework: def post(self, request): individual_request = {'dummy': 'data'} task_id = my_task.apply_async( kwargs=individual_request, link=my_task_success.s(individual_request), link_error=my_task_error.s(individual_request), ) In another part of my code I have the function my_task registered as a task with: @task(queue='queue_name', name='task_name', soft_time_limit=10800) def my_task(dummy=None): ... do stuff ... return {'success':True} In the same code file I have the response tasks: @task(bind=True, queue=celery_config.DATA_EXTRACT_QUEUE) def my_task_success(self, result, individual_request): LOGGER.info( 'Successfully finished task' ) @task(queue=celery_config.DATA_EXTRACT_QUEUE) def my_task_error(context, error, stacktrace, individual_request): LOGGER.error( 'Failed to execute task' ) -
How to "login" in Django Rest Framewrok
I recently trying django. So, i want to create an login (API) here is what i do from django.db import models from django.contrib.auth.models import AbstractBaseUser class User(AbstractBaseUser): id = models.AutoField(primary_key=True) email = models.CharField(max_length=100, unique=True) password = models.CharField(max_length=200) register_date = models.DateTimeField(auto_now_add=True, blank=True) USERNAME_FIELD = 'email' class Meta: db_table = "user" and here is my view class Login(KnoxLoginView): permission_classes = (permissions.AllowAny,) def post(self, request, format=None): serializer = AuthTokenSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] login(request, user) return super(Login, self).post(request, format=None) My UserSerializer from api.models import User from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields =['id','email','password'] extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = User( email=validated_data['email'], ) user.set_password(validated_data['password']) user.save() return user There is no problem when i create new user. But when i try to login i get this { "non_field_errors": [ "Unable to log in with provided credentials." ] } i'm 100% sure the email and password is correct. Did i miss something ? -
When Django deletes users, why are avatars deleted together?
I created a user model, the user has a default avatar. class User(AbstractUser, BaseModel): avator = models.ImageField(upload_to='user/avator/', default='user/avator/default_avator.png') I put the default avatar here When the user is deleted, i found that the default avatar will also be taken away together!! delete code: user.delete() I want to know how to make Django not delete the Avatar together when deleting the user, hoping to add a judgment or something. -
trying to access Django Admin docs raises no reverse match error
I'm trying to generate docs for my Admin so I installed docutils and added the code: # installed apps [ 'jazzmin', 'admin_numeric_filter', 'django.contrib.admindocs', 'django.contrib.admin', # rest of installed apps... ] # in my urls url(r'^admin/doc/', include('django.contrib.admindocs.urls')), But I'm getting the following error when trying to access the docs: NoReverseMatch at /admin/doc/ Reverse for 'app_list' with keyword arguments '{'app_label': 'auth'}' not found. 1 pattern(s) tried: ['admin/(?P<app_label>consumer_api|users|authtoken)/$'] -
How to fix python manage.py giving no response
When I run the command python manage.py runserver I have installed python 3.9.0 and django 3.2.10 -
Unable to get CREATE modal when creating new user using DJANGO
i got a problem when creating new user using ajax crud in django . The program allows me to edit and delete the table data but shows INTERNAL SERVER ERROR when click on to ADD NEW . The below code i use in IndexPage.html to call all the product list <iframe id="encoder_iframe" height=75% width="50%" src='{% url 'product_list' %}'></iframe> then in product list i have a button that call product create . <button type="button" class="btn btn-primary js-create-product" data-url="{% url 'product_create' %}"> this button will call the productcreate file <form method="post" action="{% url 'product_create' %}" class="js-product-create-form"> {% csrf_token %} <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true"></span> </button> <h4 class="modal-title">Create</h4> </div> <div class="modal-body"> {% include 'includes/partial_product_form.html' %} </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Create Customer</button> </div> </form> and partial_product_form.html is below {% load widget_tweaks %} {% for field in form %} <div class="form-group{% if field.errors %} has-error{% endif %}"> <label for="{{ field.id_for_label }}">{{ field.label }}</label> {% render_field field class="form-control" %} {% for error in field.errors %} <p class="help-block">{{ error }}</p> {% endfor %} </div> {% endfor %} So when i click on new customer the page will be like this before click on New Customer button … -
How to offset timezone on the Back-End using Django?
I would like to ask for support for this problem. Basically, I am working on an app in which it will generate values based on the current month, date, and year let's say Company ID based on the user's preference while leaving the TZ on settings.py untouched. I live in the timezone 'Asia/Manila', however, I have read some devs discussing that setting the Django TZ other than 'UTC' is problematic so I'm leaving it as is. But, my app requires users to save generated Company ID based on their own user-configured timezone. I know it's easy to reflect the user's timezone on the frontend via a template, however, I would like my to do something like that as well on the back-end and I'm not really sure how. I have already read the documentation many times but I still can't it. I want it to be as 'Django' as possible. -
Django doesn't see the 'templates' and 'static' folders
I am coming from Django 1.x of which everything worked fine in regards of the said problem. I tried starting a new project in Django 3.x the same way I start projects on the older version. The problem I noticed is in regards of the templates and static directories. After I set them up, Django doesn't seem to "detect" them in some way and my IDE (PyCharm) doesn't suggest them when I point something on those directories. I use the same IDE on both the old and new versions of Django. Here is the structure of my project: myproj |_ myapp |_ myproj |_ templates |_myapp |_ base.html |_ index.html | |_ static In my settings.py: import os BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR], 'APP_DIRS': True, Now, when I use {% extends "app/base.html" %} on my index.html, it doesn't 'suggest' the base.html (of which in older versions of Django it does suggest it) so something must be wrong. Here's an example: But placing myapp/base.html, it would still work. Compared to an older project of mine which uses Django 1.x: Not just in the template files but almost everywhere in Django like … -
Python cursor how do I replace with a string and maintain quotation marks in a SQL que?y
I'm using django. I'm having trouble replacing the email string in the query. It needs quotations around it since it compares strings. I've tried using parameters on the execute function but that did not work: cursor.execute("SELECT password,id FROM account WHERE email = %(mail)s", {'mail': userEmail}) I get a DatabaseError at / ORA-00936: missing expression q = "SELECT password,id from account WHERE email = '%s'" % userEmail cursor.execute(q) This produces a correct SQL query with the quotations. But I've heard this is a bad idea due to sql injection. Regardless, I'm getting a ORA-00933: SQL command not properly ended error when I did this. -
Django Running Balance / Cumulative Balance
I have a transaction model with a function to calculate the balance(running balance/cumulative balance), but the balance output is returning as a Queryset. <QuerySet [{'id': 1, 'cumsum': -9.0}, {'id': 2, 'cumsum': -16.0},{'id': 3, 'cumsum': -21.0}]> how do I fix my function so that the balance only shows the numbers such that Oct 16 is -9.00, Oct 18 is -16.00, then Oct 20 is -21.00. Thank you in advance. model.py class Transaction(models.Model): transaction_date = models.DateField() account_nickname = models.ForeignKey(Accounts, on_delete=models.CASCADE) amount = models.FloatField() @property def balance(self): return Transaction.objects.annotate(cumsum=Func(Sum('amount'),template='%(expressions)s OVER (ORDER BY %(order_by)s)',order_by="id")).values('id', 'cumsum').order_by('id', 'cumsum') views.py def index(request): all_transactions = Transaction.objects.all() context = { "transactions": all_transactions } return render(request,'pages/index.html', context) index.html {% for each_transaction in transactions %} <tr> <td>{{each_transaction.transaction_date}}</td> <td>{{each_transaction.account_nickname}}</td> <td>{{each_transaction.amount}}</td> <td>{{each_transaction.balance}}</td> </tr> {% endfor %} Output: -
How to configure & enable OpenID Connect in DJango+Wagtail app?
I'm currently using the python-social-auth/social-core lib with a DJango app, which is configured (and working) to authenticate Wagtail CMS users with our (free) Azure Active Directory Tenant. Our NFRs stipulate that authentication should occur using OpenID Connect and to this end we've installed "social-auth-core" with the "openidconnect" extra like this in requirements.txt: ... social-auth-core[openidconnect] social-auth-app-django ... Again, things seem to work A-OK and users can login, but here's my problem - and I know I'm missing something here: As far as I know, OpenID Connect is simply a modification/addition to OAuth2.0 that gives OAuth super powers of authentication - not just authorisation - but I don't know if my DJango+Wagtail app is now just automagically configured to "just work" as/with OpenID Connect, or whether there's some additional logic/validation/config/whatever that I need to apply to the app. I don't see anything relevant in the official python-social-auth docs for Azure AD, and I don't see how/if I need to explicitly enable OpenID within Azure AD itself. Can anyone help? Thank you. -
Django/DRF: How can I get more than one slug_field from serializers.SlugRelatedField?
I have a serializer to populate an AJAX table that looks something like this: class BookSerializer(seralizers.ModelSerializer): author = serializers.SlugRelatedField( many=True, read_only=True, slug_field="name" ) class Meta: model = Book fields = ( "name", "author", "slug" ) author can contain any number of authors, which is why I need to handle it this way. Currently I can print out the name of the book and link it with its slug. I also get a list of author names rather than the IDs. My question is how I can also get the slugs for each author page? I would like to link each author to its own page, but using something like author.slug doesn't work, nor did adding this: author_slugs = serializers.HyperlinkedRelatedField( many=True, read_only=True, view_name="slug" ) Then I added author_slugs to fields -- this threw an error that author_slugs is not a valid field in the Book model. Is there a way to access more than field for each author? -
How to add multiple css file in django3 in a single html file?
I have a html file named index.html in template folder and two css file computer.css and mobile.css both are in static folder. How can i use them in a single index.html file. -
django channel_layer.send not sync even use async_to_sync
class ChatConsumer(WebsocketConsumer): def connect(self): print(self.channel_name) self.accept() def disconnect(self, close_code): pass def receive(self, text_data): async_to_sync(self.channel_layer.send)(self.channel_name, { "type": "chat.message", "text": "1", }) print("=============channel================") async_to_sync(self.channel_layer.send)(self.channel_name, { "type": "chat.message", "text": "2", }) def chat_message(self, event): message = event["text"] print(message) self.send(text_data=json.dumps({'message': message})) i call channel_layer.send twice in receive function , suppose should print like 1 ========channel======== 2 but it print =========channel======= 1 2 anyone could help to tell me where have problem ? -
Using the select_related function in Django
Hi so i'm trying to display table retailer_book, but instead of a seller_id, i want it to display the retailer instead. These are the tables class retailer(models.Model): sellerID = models.IntegerField(primary_key=True) retailer = models.CharField(max_length=255) def __str__(self): return self.retailer class retailer_book(models.Model): ISBN = models.ForeignKey(books, on_delete = models.CASCADE) sellerID = models.ForeignKey(retailer, on_delete = models.CASCADE) condition = models.CharField(max_length=255) price = models.FloatField() reviews= models.CharField(max_length=255) ID = models.IntegerField(primary_key=True) bookType = models.CharField(max_length=255) I've tried : object_list1 = retailer_book.objects.filter(ISBN_id = query).select_related("sellerID_id") but it doesn't display retailer when i try to display it. Here's my views.py class SearchResultsView1(ListView): model = books template_name = 'TextSearch/search_results.html' context_object_name = "object_list" def get_queryset(self): # new query = self.request.GET.get('q') object_list1 = retailer_book.objects.filter(ISBN_id = query).select_related("sellerID_id") return object_list and here's my HTML code <h1>Book Options: </h1> <table border="1"> <tr> <th> ID </th> <th> Retailer </th> <th> condition </th> <th> Book Type </th> <th> Reviews </th> <th> Price </th> </tr> {% for result in object_list %} <tr> <td> {{result.ID}} </td> <td> {{result.retailer}} </td> <td> {{result.condition}} </td> <td> {{result.bookType}} </td> <td> {{result.reviews}} </td> <td> {{result.price}} </td> </tr> {% endfor %} </table> -
Django displays tow different timezones for the same model attribute when viewing in admin site vs a query for the model in a script
How to make consistant timezone across Django. In my settings.py I have TIME_ZONE = 'America/New_York' and USE_TZ = True. I have a model def MyModel(models.Model): date_time = models.DateTimeField(auto_now_add=True) if I view a field from that model (say pk=1) it correctly displays value for an eastern timezone. From my terminal, when I run python manage.py shell and make a query for that same field (pk=1), it will print the date_time attribute of that field in UTC format as follows: datetime.datetime(2020, 10, 22, 0, 19, 28, 696739, tzinfo=<UTC>) Why is this happening? And how can I make it so that all queries use the correct timezone when filtering by date? -
OperationalError Django admin
I'm using a legacy mysql database on django. I need to display another table on the "bibliografias" admin page, it is referenced by the db with foreign keys. I get this error: OperationalError at /admin/accounts/bibrest51/ (1054, "Unknown column 'bibrest51.tema_f_id' in 'field list'") admin.py def get_tema(self, obj): return obj.tema_f.tema_nome get_tema.short_description = 'Tema' models.py class Tema(models.Model): tema_id = models.AutoField(primary_key=True) tema_nome = models.CharField(max_length=150, blank=True, null=True) datacriado = models.DateTimeField(db_column='dataCriado') # Field name made lowercase. @property def tema_id(self): return self.tema_id def __str__(self): return str(self.tema_id) class Meta: managed = False db_table = 'tema_table' class Bibrest51(models.Model): cadastro_id = models.AutoField(primary_key=True) tema_f = models.ForeignKey(Tema,on_delete=models.CASCADE) tema_id = models.IntegerField(blank=True, null=True) class Meta: managed = False db_table = 'bibrest51' verbose_name = "Bibliografia" verbose_name_plural = "Bibliografias" -
Serializing Nested foreign key objects
whoever is reading this, hope you're doing well. I am creating a social media application which includes post in it and likes and comments just like any other social media site, I am trying to send the data from my backend to front end via serializers, the problem I am getting through is I am not able to get the output of whole data but partial data. Following represents my models.py for the objects I am trying to serialize models.py class User(AbstractUser): contact_no = models.CharField(max_length=15,null=True,blank=True) profile_picture=models.ImageField(upload_to=to_upload,default="defaultprofile.jpg") class Post(models.Model): posted_by=models.ForeignKey(User,on_delete=models.CASCADE) date= models.DateField(auto_now=True) time=models.TimeField(auto_now=True) content=models.CharField(max_length=2000) media=models.ImageField(default=None,blank=True,upload_to=to_upload_post) class Like(models.Model): Liked_by=models.ForeignKey(User,on_delete=models.CASCADE,related_name="likes") post=models.ForeignKey(Post,on_delete=models.CASCADE) date = models.DateField(auto_now=True) time = models.TimeField(auto_now=True) and the serializers that I'm using is serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model=User fields=['id','username','first_name','last_name','profile_picture'] class LikeSerializer(serializers.ModelSerializer): Liked_by=UserSerializer() class Meta: model=Like fields=['Liked_by'] class PostSerializer(serializers.ModelSerializer): posted_by=UserSerializer() likes=LikeSerializer(many=True) class Meta: model=Post fields=['posted_by','id','content','date','time','media','likes'] This does not raise any errors while importing it but it doesn't give complete data. The output I'm getting is { 'posted_by': OrderedDict([ ('id', 7), ('username', 'user'), ('first_name', ''), ('last_name', ''), ('profile_picture', '/media/defaultprofile.jpg')]), 'id': 4, 'content': 'This is a test post for likes', 'date': '2020-10-22', 'time': '05:34:55.979863', 'media': None } but what I'm trying to get is Desired Output { 'posted_by': OrderedDict([ ('id', 7), ('username', 'user'), ('first_name', … -
Django: How to override the display of ModelForm fields in UpdateView, specifically
I have a function-based view that is currently working successfully. However, I want to learn how to create the equivalent Class Based View version of this function, using the generic UpdateView class -- though I imagine the solution, whatever it is, will be the exact same for CreateView, as well. I know how to create and use Class Based Views generally, but there is one line of my function-based view that I have not been able to work into the corresponding UpdateView -- as usual with the Generic Editing Class Based Views, it's not immediately clear which method I need to override to insert the desired functionality. The specific task that I can't port-over to the CBV, so to speak, is a line that overrides the queryset that will be used for the display of a specific field, one that is defined as ForeignKey to another model in my database. First, the working function-based view, with highlight at the specific bit of code I can't get working in the CVB version: @login_required def update_details(request, pk): """update details of an existing record""" umd_object = UserMovieDetail.objects.select_related('movie').get(pk=pk) movie = umd_object.movie if umd_object.user != request.user: raise Http404 if request.method != 'POST': form = UserMovieDetailForm(instance=umd_object) …