Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to change the appearance of some similar fields in Django admin according some condition
What I want I have three fields of type DateField, what I want is to change its appearance in the admin if the value of that field is a specific date without repeating the same method to check the value of each field and change their appearance(DRY). What I've tried 1. Firs approach: use a model method to checks the field value Model class Case(TimeStampedModel, models.Model): fulfillment = models.DateField(default=date.today) caducity = models.DateField(default=date.today) prescription = models.DateField(default=date.today) # With this approach I need to repeat this method to check the value for every field def is_prescripted(self): """Check if one case is prescripted.""" if self.prescription == date.today(): return True return False Admin from django.contrib import admin from .models import Case @admin.register(Case) class CaseAdmin(admin.ModelAdmin): list_display = ( "_fulfillment", "_caducity", "_prescription", ) # With this approach I need to repeat this method to change the appearance for every field def _prescription(self, obj: Case) -> str: """Render a red badge alert in the admin for cases that are prescribed.""" date = formats.date_format(obj.prescription) if obj.is_prescripted(): return create_badge(text=date) return date 2. second approach: use a manager method to checks the value from all fields at the same time Model Manager class CaseManager(models.Manager): def expired(self) -> "QuerySet[Case]": """Get all … -
Django DRF PUT Request ImageField
I am uploading images using the ImageField in Django. After saving the image in the database when I GET the data to display on the frontend, I get it in the format: {"pk":5,"employee_image":"/media/emp_temp_mast/5.png","first_name":"TEST",} After changing the data on the frontend, I send a PUT request for the respective entry in the form: {"pk":5,"employee_image":"/media/emp_temp_mast/5.png","first_name":"DATA CHANGED",} However I get the following error after making the request: employee_image: ["The submitted data was not a file. Check the encoding type on the form."] How should I call the PUT request from frontend. -
django template dose not render response returned by view
I have a c++ client that will make an HTTP POST request to a django server and submit some data. I want to this data to be shown in my browser under 127.0.0.1/postReq/. The problem is that response is just shown in the console and not in the browser. For further testing I tried to do the same using postman and I realized that the view returns a response and postman receives it successfully and shows the rendered template correctly but browser doesn't show it! In my view I'm basically redirecting the result of the POST request to the same url using django sessions. I'm following This tutorial. views.py @csrf_exempt def post(request): if request.method == 'POST': guess = request.POST.get('guess') print(guess) request.session['msg'] = guess return redirect(request.path) else: tmp = request.session.get('msg',False) print(tmp) if(tmp): del(request.session['msg']) print("message flashed") return render(request,'list/response.html',{'message':tmp}) response.html <html> <head> <meta charset="UTF-8"> {% load static %} <link type="text/css" rel="stylesheet" href="{% static"list/styleResponse.css" %}"/> <title>HTTP RESPONSE</title> </head> <body> <h1>heres the output</h1> {% if message %} <ul> {% for s in message %} <li>key:{{s}}</li> {% endfor %} </ul> {% else %} <p>No data is available.</p> {% endif %} </body> </html> and this is the desired output (which postman provides successfully): <h1>heres the output</h1> <ul> … -
Django return image and data in HttpResponse
I have a Django app working as the backend of an Android app. The thing is that the Android app sends an image to the Django server. Then the server makes some calculations and I need to return as the response the image modified and a float value that is calculated in the server. It's pretty clear how to return only the image using HttpResponse: def backend_function(request): img = request.FILES["file"].read() img_res, float_res = some_calculations(img) return HttpResponse(img_res, content_type="image/jpeg") But I don't know how to add that float_res to the HttpResponse. -
Request header field Access-Control-Allow-Headers is not allowed by itself in preflight response in react js
Hello i am using django for getting and posting data , for front end i am using React js...after reading some answers in the stack over flow...i have tried like this....its still throwing the issue of cors orgin...can any one help on this please.... i want to get the some particular fileds to that api... axios.get("https://www.myapi/api/user_wish_courses/", { headers: { 'Access-Control-Allow-Headers': 'Content-Type, Authorization, Accept', 'Authorization': `Token ${this.state.Token.token}`, 'Accept': 'application/json', 'Content-Type': 'application/json', }, -
where is "top level of template tree" in Django?
in Django I want to add a custom 404 page for my site. as Django documentation says I must add a 404.html to top level of my template tree. I want to know where it is? -
How to save and upload image using Ajax and FormData in django
I am trying to save and upload image using Ajax and FormData in django but it is giving me this error: Forbidden (CSRF token missing or incorrect.): /employee/ajax/employee-photo/. So, what will be the solution here? Any help will be highly appreciated. class Employee(models.Model): photo = models.ImageField(upload_to=image_upload_path, null=True) urlpatterns = [ path('ajax/employee-photo/', EmployeePhotoAJAX.as_view(), name="ajax-employee-photo"), ] class EmployeePhotoAJAX(LoginRequiredMixin, View): login_url = '/authentication/login/' def get(self, request): if request.method == 'GET': if request.is_ajax(): id = request.GET.get("id", None) print(id) image = request.FILES.get('profileImage') print(image) employee = Employee.objects.get(id=id) if employee: employee.photo = image # uploaded_image = Employee(img=image) # uploaded_image.save() employee.save() response_data = { 'url': employee.photo.url, } return JsonResponse(response_data) $("#profile_image_input").change(function(e) { e.preventDefault(); // disables submit's default action var data = new FormData($("#ajax").get(0)); console.log(data); $.ajax({ url: '{% url "employee:ajax-employee-photo" %}', type: 'POST', data: { "id": "{{ employee.id }}", "employee_photo": data, "csrfmiddlewaretoken": "{{ csrf_token }}", }, dataType: "json", processData: false, contentType: false, success: function(data) { data = JSON.parse(data); // converts string of json to object $("#photo").empty(); $("#photo").html('<img class="img-responsive avatar-view" src="' + data.url +'"/>'); // $('#photo').html('<img src="'+data.url+ '" />'); } }); return false; }); -
In django-two-factor-auth how to enable OTP on a user programatically
I am writing a django test for logged in users who have OTP enabled. I have user1 who is authenticated as self.client.force_login(user1). I would like to enable OTP on this user so I can test my view. In django-two-factor-auth package, test_admin.py function - self.enable_otp() is used to enable OTP on a user. def enable_otp(self, user=None): if not user: user = list(self._passwords.keys())[0] return user.totpdevice_set.create(name='default') How can I use this in my django test. Thanks -
How to store a very large dictionary variable in Django?
For a function that I will be using across many views, it will have a dictionary variable with lots of keys in it. I'm thinking that the variable is kind of a lot to be stored in views.py with all the other code so is there a way to store this dictionary variable somewhere else or in a more compact state? -
Django. Problems with routing
I have a problem with the routing in my backend in Django. I have two apps belg and api. In belg\urls.py: from django.contrib import admin from django.urls import path from django.conf.urls import include from rest_framework.authtoken.views import obtain_auth_token urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('api.urls')), path('auth/', obtain_auth_token) ] In api/urls.py: from django.urls import path from rest_framework import routers from django.conf.urls import include from .views import UserViewSet, RoomViewSet router = routers.DefaultRouter() router.register('users', UserViewSet) router.register('rooms', RoomViewSet) urlpatterns = [ path('', include(router.urls)), ] When I run the server and access the adress: http://127.0.0.1:8000/api/, I get the following error and traceback: TypeError at /api/ 'str' object is not callable Request Method: GET Request URL: http://127.0.0.1:8000/api/ Django Version: 3.1 Exception Type: TypeError Exception Value: 'str' object is not callable Exception Location: C:\Users\Admin\Belgijka\env\lib\site-packages\rest_framework\views.py, line 278, in <listcomp> Python Executable: C:\Users\Admin\Belgijka\env\Scripts\python.exe Python Version: 3.7.1 Python Path: ['C:\\Users\\Admin\\belgijka', 'C:\\Users\\Admin\\Belgijka\\env\\Scripts\\python37.zip', 'C:\\ProgramData\\Anaconda3\\DLLs', 'C:\\ProgramData\\Anaconda3\\lib', 'C:\\ProgramData\\Anaconda3', 'C:\\Users\\Admin\\Belgijka\\env', 'C:\\Users\\Admin\\Belgijka\\env\\lib\\site-packages'] Server time: Wed, 12 Aug 2020 17:20:26 +0000 Traceback Switch to copy-and-paste view C:\Users\Admin\Belgijka\env\lib\site-packages\django\core\handlers\exception.py, line 47, in inner response = get_response(request) … ▶ Local vars C:\Users\Admin\Belgijka\env\lib\site-packages\django\core\handlers\base.py, line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▶ Local vars C:\Users\Admin\Belgijka\env\lib\site-packages\django\views\decorators\csrf.py, line 54, in wrapped_view return view_func(*args, **kwargs) … ▶ Local vars C:\Users\Admin\Belgijka\env\lib\site-packages\django\views\generic\base.py, line 73, in … -
Django: sidebar with dynamic URLs: how to dynamically create URLs which have dynamic folders in the path
I have a problem with dynamic URLs in sidebar navigation in Django and I hope some of you can help me shed some lights on how to solve it. I have looked for similar questions but I couldn't find an answer for my case. Basically, what I want to achieve is to have a sidebar with links. This sidebar will be reused on many pages, so it sits in a separate sidebar.py file, which is later imported to the pages. <h6 class="sidebar-heading d-flex justify-content-between align-items-center px-3 mt-4 mb-1 text-muted"> <span>Content</span> <a class="d-flex align-items-center text-muted" href="#"> <span data-feather="plus-circle"></span> </a> </h6> <ul class="nav flex-column"> <li class="nav-item"> <a class="nav-link active" href="DYNAMIC LINK HERE"> <span data-feather="home"></span> Status codes</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> <span data-feather="file"></span> Depth </a> </li> </ul> The links I want to display are the following: urls.py path('<id>/<crawl_id>/dashboard/', ProjectDashboard, name="crawl_dashboard"), path('<id>/<crawl_id>/dashboard/status-codes/', StatusCodeDashboard, name="status_code_dashboard"), path('<id>/<crawl_id>/dashboard/url-depth/', UrlDepthDashboard, name="url_depth_dashboard"), As you can see, they are dynamic URLs which take an id and crawl_id. So, for each crawl dashboard I want the sidebar to link to its relative status_code_dashboard page and url_depth_dashboard page. As an example: /22/123/dashboard --> should have a sidebar with links to: /22/123/dashboard/status-code/ /22/123/dashboard/url-depth/ What I tried to do is to … -
Is there a way to pass a list into model.objects.values() in Django?
I want to only display specific columns from my model, I know this way works: Transactionlog.objects.values('column1','column2','column3') But I have a list I need to populate into, I'm using django filters so my code looks like this: filtered_transactions = transactionFilter( request.GET, queryset=Transactionlog.objects.values('column1','column2')) My problem is that I have a dynamic list being populated via a seperate model, and i need to pass this list into values(), but it doesn't take list, from what i can tell anyway. my solution so far ( horrible for large datasets...and small): if len(column_list) == 1: filtered_transactions = transactionFilter( request.GET, queryset=Transactionlog.objects.values(column_list[0])) if len(column_list) == 2: filtered_transactions = transactionFilter( request.GET, queryset=Transactionlog.objects.values(column_list[0],column_list[1])) ... Please tell me there is another way of doing this, becuase this is driving me up the wall! -
Django 1.11 functional tests written using Selenium fail in CircleCI with Address already in use error
We are migrating from Django 1.8 to Django 1.11.29. While doing this I'm experiencing following problems: Running the functional tests (StaticLiveServerTestCase) fails in CircleCI with error - error: [Errno 98] Address already in use. Earlier I used to get this error in my local as well. But then I resolved taking reference from this another SO post here. While I believe it might be due to parallel test runs, I'm not sure how to fix it. Certain tests randomly pass or fail (intermittently), being unable to locate an element on the page in the functional test. This is in local. I've not really reached the stage where I know the behavior on CircleCI. Before these problems, I also ran into these problems: The unit tests were getting stuck. Resolved by replacing fixtures attribute with explicit call_command('loaddata', ...). Not too confident about the approach as functional tests don't have problem with fixtures attribute. Functional tests were all failing with error Django settings doesn't define RESOLVER. Even though I didn't really have an override_settings problem, I followed an advice in this django-assets ticket here and the problem got resolved. I believe there is something that fundamentally changed from Django 1.8 to Django … -
the views.py is not fetching the value from the input box in the template
When I run the following code, it is showing a DoesNotExist error at 'post_connected'. this is my views.py def home(request): user = request.user info = profile.objects.get(user=user) follow1 = Follow.objects.filter(follow_user=user) follow2 = Follow.objects.filter(user=user) follow_by = follow1.count() follow_to = follow2.count() follows = [user] for obj in follow2: follows.append(obj.follow_user) posts = post.objects.filter(author__in=follows).order_by('-date') paginator = Paginator(posts, 10) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) count = posts.count() postid = request.POST.get('post_id') post_connected = post.objects.get(id=postid) mypost = like_post.objects.filter(user=user, liked=post_connected) if mypost.exists(): liked = False else: liked = True context = { 'user':user, 'liked':liked, 'post':posts, 'page_obj': page_obj, 'follow_by':follow_by, 'follow_to':follow_to, } return render(request, 'home.html', context) now, this is my template view {% for posts in page_obj %} <div class="posts"> <img src="{% static 'logo.png' %}" style="width: 17px; height:14px;"> <a href="/users/user/{{posts.author}}/" class="username" style="font-size:18px;">{{posts.author}}</a><br><br> <span style="font-weight:bold; font-size:17px;">{{posts.content}}</span><br><br> <form action="/like/{{posts.id}}/" method="POST"> {% csrf_token %} <input type="text" value="{{posts.id}}" name="post_id" style="display: none;"> <button style="background-color: inherit; border:none; outline:none"> {% if liked %} <i class="fa fa-heart" aria-hidden="true" style="color: red;"></i> {% else %} <i class="fa fa-heart" aria-hidden="true" style="color: lightgrey;"></i> {% endif %} </button> <span style="font-size:12px; float:right"><b>Posted on:</b> {{posts.date | date:"H:i D, d M"}}</span> </form> </div> <br> {% endfor %} I think that the server is not able to fetch the value from the input box. I don't know … -
Django authenitcation middleware interfering with site-wide cache
I'm attempting to get django's site-wide caching to work consistently. My settings.py: MIDDLEWARE = [ # 'debug_toolbar.middleware.DebugToolbarMiddleware', 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', ] CACHE_MIDDLEWARE_SECONDS = 60 CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', 'LOCATION': os.path.join(BASE_DIR, 'cache'), } } I've also tried this with the memcached backend, but it's harder to see whether or not the cache is being generated and has exactly the same behaviour. I'm testing that this is cached by simply putting a {{request.user}} and {% now 'H:i:s' %} timestamp into a template. When I open this page in two different browsers (so that I'm getting distinct sessions), both users are AnonymousUser, but the timestamps are different, showing me that this wasn't cached between anonymous users. In each of the sessions, reloading the page would get the same timestamp as the first load of that session, so the cache is working, but it's making a new cache for every user that visits the site, which essentially destroys the point of having a cache at all for me. When I comment out the 'django.contrib.auth.middleware.AuthenticationMiddleware' and repeat the experiment, the page becomes cached between all sessions, so this is where the issue lies, but I need … -
Why my to-do task app is showing name error
This is the code of my Todo Tasks app which shows the tasks of a user in increasing order of their priorities. However, it is showing "Name Error name "tasks" is not defined'. Please help. My view.py code for To-do tasks app -
Django REST authentication with React/ Redux
I am building a web app with a Django backend and React/Redux frontend running on separate servers. I have begun to try and start working on authentication and I cannot find a tutorial that suits my needs. Every tutorial either uses deprecated modules like drf-jwt (as opposed to simple-jwt) or has a simple mono-server that houses both the backend and the frontend in one directory. The former is useless and I do not want to do the latter as I like having the two separate servers for when I move on to deployment. Now can someone direct me to a good source of knowledge for getting this done? It doesn't have to be a tutorial it can be anything. I am really lost and I do not know how to begin. -
Any way to pass a variable into a django meta class?
I am working on a django app that lets the user create a point on a map. This map needs to be centered at a certain location for ease of use, and this location is variable. I am using a LeafletWidget to let the user create this point. The map can be centered by changing the attributes of the LeafletWidget. Unfortunately this widget is defined inside a Meta class, and as far as I understand you cannot pass a variable into it. Here an example of what I would like to do, somehow passing the variable center into the Meta class. center is a tuple with latitude and longitude values. This example code does not work of course. I don't know if you can somehow pass a variable into a Meta class. class PointModelForm(ModelForm): class Meta(center): model = PointModel fields = ['name', 'point'] widgets = {'point': LeafletWidget(attrs={'settings_overrides': {'DEFAULT_CENTER': center} })} My best bet was defining the widgets attribute in the __init__ function, however Meta classes cannot access these attributes if I am correct. When I run this no widgets are used. class PointModelForm(ModelForm): class Meta: model = PointModel fields = ['name', 'point'] def __init__(self, center): super(PointModelForm, self).__init__() self.widgets = {'point': … -
ajax modal not showing after call on django?
I wanna show an object detail view on a modal via ajax. here's Django project files: the html home page including the ajax code for the modal view index.html <body> <div class="container"> {% for y in all %} <form id="form_have_product_{{y.id}}" method="POST"> {% csrf_token %} <button id="{{y.id}}" "type="button" class="btn btn-warning margin-bottom show_product">Product details</button> </form> {% endfor %} <!-- Modal --> <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <h1 id="name" ></h1> <h1 id="email" ></h1> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> <!-- Modal --> </div> </body> <script> $(function(){ $('.show_product').on('click', function (e) { e.preventDefault(); let product_id = $(this).attr('id'); $.ajax({ url:'detail/', type:'POST', data: $('#form_have_product_'+product_id).serialize(), success:function(response){ console.log(response); $('.show_product').trigger("reset"); openModal(response); }, error:function(){ console.log('something went wrong here'); }, }); }); }); function openModal(product_data){ $('#name').text(product_data.users.name); $('#email').text(product_data.users.email); $('#exampleModal').modal('show'); }; </script> <script type="text/javascript" src="{% static 'js/jquery-3.3.1.min.js' %}"></script> <script type="text/javascript" src="{% static 'js/popper.min.js' %}"></script> <script type="text/javascript" src="{% static 'js/bootstrap.min.js' %}"></script> <script type="text/javascript" src="{% static 'js/mdb.min.js' %}"></script> <script type="text/javascript" src="{% static 'js/main.js' %}"></script> </html> the project's app URL file urls.py from django.urls import path from . import views app_name … -
How can I use DRF permissions on a Django TemplateView?
How can I use DRF permissions on a Django TemplateView? e.g. class ApiBaseView(APIView): permission_classes = (IsAuthenticated, permissions.CanViewEmail) class BaseView(TemplateView): pass How can I use the permission classes of ApiBaseView on BaseView? -
How to change Django Authentication View "PasswordResetView" to send resent link to mobile number and email?
I have a Custom User Model and Custom Backend for authenticating via both mobile number and email. I want to give my users the ability to reset the password via both email and mobile number, i.e., on the PasswordResetView I want to have both options for resetting the password with the reset password link sent on the mobile number and on the email. I have my Django project configured to send messages with Twilio. My question is how to change the PasswordResetView to be able to do that. -
My django web app comment form is not displaying properly
I am trying to add comment function to my blog app and the comment form is not displaying "name, email, body" and the submit button when clicked is showing error 405 page not working... Below is my models.py code class Comment(models.Model): post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=False) class Meta: ordering = ['created_on'] def __str__(self): return 'Comment {} by {}'.format(self.body, self.name) Below also is my forms.py code from django import forms from . import models from .models import Post, Comment class PostForm(forms.ModelForm): class Meta: model = Post fields = ("title", "group", "image") def __init__(self,*args,**kwargs): user = kwargs.pop("user", None) super().__init__(*args, **kwargs) if user is not None: self.fields["group"].queryset = ( models.Group.objects.filter( pk__in=user.groups.values_list("group__pk") ) ) class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('name', 'email', 'body') Also is the views.py codes class PostDetailView(DetailView): model = Post def post_detail(request, slug): template_name = 'post_detail.html' post = get_object_or_404(Post, slug=slug) comments = post.comments.filter(active=True) new_comment = None # Comment posted if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): # Create Comment object but don't save to database yet new_comment = comment_form.save(commit=False) # Assign the current post to the comment new_comment.post = post # Save the … -
When trying to filter out posts by users that aren't in a many to many field ran into error 'method' object is not iterable
So when I try to filter out certain posts in a twitter like application I cannot seem to loop over the many to many field to display the posts. This is the code that is giving me trouble: posts1 = Post.objects.filter(user__username__in=request.user.following.all) I need to call this for my pagination otherwise I could've just done this all inside my template. These are the models I use in this call: class User(AbstractUser): follower = models.ManyToManyField("User", related_name="followers", blank=True) following = models.ManyToManyField("User", related_name="follow", blank=True) class Post(models.Model): user = models.ForeignKey("User", on_delete=models.CASCADE, related_name="users") post = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) like = models.IntegerField() def serialize(self): return { "id": self.id, "user": self.user, "post": self.post, "timestamp": self.timestamp.strftime("%b %-d %Y, %-I:%M %p"), "like": self.like, } Thanks in adavance! -
In Django 3/Python, what is the preferred way to remove orphaned records?
I'm using Django 3 and Python 3.8. I have the following model ... class Coop(models.Model): objects = CoopManager() name = models.CharField(max_length=250, null=False) types = models.ManyToManyField(CoopType, blank=False) addresses = models.ManyToManyField(Address) enabled = models.BooleanField(default=True, null=False) phone = models.ForeignKey(ContactMethod, on_delete=models.CASCADE, null=True, related_name='contact_phone') email = models.ForeignKey(ContactMethod, on_delete=models.CASCADE, null=True, related_name='contact_email') web_site = models.TextField() Note the "phone" and "email" foreign key columns. Is there any Django/Python specific way to automatically remove the ContactMethod records once they become orphaned? That is, if I have my model, in which both columns are populated, and then run coop.phone = None coop.save(update_fields=['phone']) Is there anything that will automatically delete the orphaned records? Or I guess what is the standard way to achieve this? I'm running a MySql 8 db, but i would prefer to exclude DB-specific solutions. -
Django form not submitting on click of Submit button when mutli-select has no value
I'm using the django-taggit library to represent the "questions" field. It is set to blank=True in the model. When I try to submit this form, it works fine if one or more questions are selected in the multi-select field, but it does not submit if that field has nothing selected. The problem is that it does not even throw errors or hit a breakpoint put in the view code, so I can't debug it to figure out what is going wrong. Any ideas? Django Form class: class CreateJob(ModelForm): def __init__(self, *args, **kwargs): selected_questions = kwargs.pop('selected_questions') super(CreateJob, self).__init__(*args, **kwargs) self.initial['questions'] = selected_questions questions = ModelMultipleChoiceField(queryset=Tag.objects.all()) class Meta: model = Job fields = ('name', 'description', 'skills_required', 'submission_deadline', 'participation_ends', 'tagged_freelancers', 'assigned_freelancer', 'questions') widgets = { 'submission_deadline': DateInput(attrs={'data-provide': 'datepicker'}), 'participation_ends': DateInput(attrs={'data-provide': 'datepicker'}) } Django View: def job_edit(request, job_id, template_name='projects/job_create.html'): job = get_object_or_404(Job, pk=job_id) job_form = CreateJob(request.POST or None, instance=job, selected_questions=job.questions.all()) if job_form.is_valid(): job_form.save() return redirect('job_board') return render(request, template_name, {'job_form': job_form, 'is_new': False}) HTML template: <div class="container"> <div class="row justify-content-sm-center"> <div class="col-sm-8"> <div class="mb-3 text-left"> {% if is_new %} <h1>New Job</h1> {% else %} <h1>Update Job</h1> {% endif %} </div> <form method="post" class="form"> {% csrf_token %} {% bootstrap_field job_form.name %} {% bootstrap_field job_form.description %} {% …