Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ManyToManyField Unique item
I am writing a model which is below: class Person(models.Model): name = models.CharField(max_lenght=50) class Group(models.Model): admins = models.ManyToManyField( Person, related_name='group_admins' ) members = models.ManyToManyField( Person, blank=True, related_name='group_members' ) I want a Person Can't join another group if he belongs to a Group. I mean, group members or a Group admin can't join a new group if he/she belongs to in a group. Can anyone help me to make it happen? -
How to send html as Json response in Django?
How can i get the whole data from get_context_data(), and pass it to the template as JSON?I want to send back the html to the template, and to use it's context data in ajax success method. -
Compare values from a form field value and a queryset value
In my app the SignUp form looks like this: Forms.py class EmployeeSignUpForm(UserCreationForm): company = forms.ModelChoiceField(queryset=Company.objects.all(), required=True, label='Select Company') company_code = forms.IntegerField(required=True) class Meta(UserCreationForm.Meta): model = User @transaction.atomic def save (self): user = super().save(commit=False) user.is_employee = True user.save() c_company = self.cleaned_data['company'][0] employee = Employee.objects.create(user=user, company=c_company) return user How can I compare the c_code with the company_code in my models.py and save the form only when both of them matches else throw an error? Models.py class Company(models.Model): company_name = models.CharField(max_length=255, default=0) company_email = models.EmailField(max_length=255, default=0) company_phone = models.CharField(max_length=255, default=0) company_code = models.IntegerField(default=0) def __str__ (self): return self.company_name -
How do I use a jQuery gallery (fotorama) in my Django project?
I've created a page in Django which serves images of a specific car into a gallery slider like this My problem is that it's not even recognizing the fotorama gallery. The <div class="fotorama"></div> shows up in the inspect code, but the images are still spread out in html's default layout. Jquery isn't linked because I've linked to it in the base.html file for bootstrap, so I know it works. I'm hosting the fotorama.js and .css locally since they didn't work when served via CDN. Yes, I've already run collectstatic. <head> ... {% load static %} <link href="{% static 'css/fotorama.css' %}" rel="stylesheet"> <script src="{% static 'js/fotorama.js' %}"></script> </head> ... <div class="container"> <div class="row"> <div class="col justify-content-center"> <div class="fotorama"> <img src="/static/images/placeholder.jpg"> {% for image in car.image_set.all %} <img src="{{ image.image.url }}"> {% endfor %} </div> </div> </div> </div> Just as a quick test, I served a normal image outside of all the other container, row, and col divs. It also didn't make a difference. <div class="fotorama"> <img src="/static/images/placeholder.jpg"> </div> This is what the page looks like: I made a quick page outside my django project, and fotorama works perfectly. Could this be a django-specific issue? Is there an extra plugin/extra code I … -
Proper implementation of Django model inheritance architecture?
I'm building simple Django app for reviews of diffrent objects (restaurants, car services, car wash etc), so I started with the app, but soon I faced first problem, every object have features (but every type of object have different features), for example restaurants have (garden, playground, seats etc, type of kitchen), car washes have (external cleaning, internal cleaning etc). So I started to build typical DB implementation with ManyToMany tables, but then I found Django Model Inheritance, so I implement it in my APP, as you can see: urls.py: from django.urls import path from . import views urlpatterns = [ path('user/<int:pk>/', views.UserObjectsView.as_view(), name='user-objects'), path('add/', views.add_object, name='add-object'), path('<str:category>/<int:pk>/', views.show_object, name='show-object'), path('all/<str:category>/', views.show_all_objects, name="show-all-objects"), ] models.py: from django.db import models from users.models import ProfileUser from django.utils import timezone # Create your models here. class Object(models.Model): author = models.ForeignKey(ProfileUser, on_delete=models.CASCADE) title = models.CharField(max_length=300) address = models.CharField(max_length=300) content = models.TextField() created_date = models.DateTimeField(default=timezone.now) approved_object = models.BooleanField(default=False) admin_seen = models.BooleanField(default=False) def __str__(self): return f"{self.title}" class Restaurant(Object): seats = models.IntegerField() bulgarian_kitchen = models.BooleanField(default=False) italian_kitchen = models.BooleanField(default=False) french_kitchen = models.BooleanField(default=False) is_garden = models.BooleanField(default=False) is_playground = models.BooleanField(default=False) class SportFitness(Object): is_fitness_trainer = models.BooleanField(default=False) class CarService(Object): is_parts_clients = models.BooleanField(default=False) class BeautySalon(Object): is_hair_salon = models.BooleanField(default=False) is_laser_epilation = models.BooleanField(default=False) class FastFood(Object): is_pizza … -
i am suffering with the problem of the message dialog box in the django????Help me out his
I tried the message box code in my django frame work for whenever any action perform on the button it will show the dialog box says data entered or any other messgae like this.But Nothing is appear on the window IN THE VIEWS PANEL:- from django.contrib import messages def form(request): if request.method=="POST": n = request.POST['fname'] fnumber = request.POST['fphonenumbe'] ft = request.POST['ftime'] fgend=request.POST['gender'] fdob = request.POST['fdob'] s= Officers() s.fname=n s.dsg=Designations.objects.get(id=request.POST['desigid']) s.dpt=Departments.objects.get(id=request.POST['departid']) s.pst=Postings.objects.get(id=request.POST["postid"]) s.ftime=ft s.image = request.FILES['photo'] s.fphonenumber=fnumber s.fgender=fgend s.fdob=fdob s.save() messages.success(request,"Officer Added Successfully.") return render(request,'form.html') else: d = Designations.objects.all() dp = Departments.objects.all() p=Postings.objects.all() return render(request,'form.html',{'desig':d,'depart':dp, 'post':p}) FORM PANEL:- <div class="form-group"> <label for="middle-name" class="control-label col-md-3 col-sm-3 col-xs-12">Phone Number</label> <div class="col-md-6 col-sm-6 col-xs-12"> <input name="fphonenumbe" id="" class="form-control col-md-7 col-xs-12" type="text" name="middle-name" placeholder="Enter Phone Number"> </div> -
Django - How to prevent empty record in admin subform?
I am newbie in Django and Python so hope you will be indulgent I've read and read again the Django documentation but for now, some concept still are very abstract for me... I have a database and I use ModelForm and I try to customize this admin forms I currently have a main form with a subform and both forms are customized I noticed 'abnormal' behavior (unwanted): even when no entry is made in the subform, empty record is stored in the table corresponding to the subform in the database how to prevent this? I have compared with other forms/subforms in my app that did not have this behavior but coul not find what is wrong because code seems to be the same... thanks in advance fory your help models.py : class SuiviAppuiCommunitaire(SafeDeleteModel): _safedelete_policy = SOFT_DELETE_CASCADE com_ide = models.AutoField(primary_key=True) pat = models.ForeignKey(Participante, verbose_name='Participante', related_name='community', on_delete=models.CASCADE) com_dat = models.DateField("Date de la demande",null=True,blank=True) com_mot = models.IntegerField("Motif", max_length=1,null=True,blank=True) com_det = models.CharField("Détails", max_length=255,null=True,blank=True) com_com = models.CharField("", max_length=255,null=True,blank=True) log = HistoricalRecords() class Meta: db_table = 'crf_com' verbose_name_plural = '5.1-Appuis / Suivis communautaires(COM)' ordering = ['pat', 'com_dat','com_ide'] def __str__(self): return f"{self.com_ide} / {self.pat.pat_ide_prn_cse} / {self.com_dat}" @property def participante(self): return self.pat.pat_ide_prn_cse participante.fget.short_description = 'Participante' class InterventionCommunautaire(SafeDeleteModel): _safedelete_policy … -
URLConnection hits server twice when downloading file?
After reading HttpURLConnection request being hit twice to the server for downloading file it was very similar and helped, but I still see my server gets two requests for a single download. This is my AsyncTask that I use to download a file from a Django web server. @Override protected String doInBackground(String... sUrl) { String path = "/sdcard/YourApp.apk"; try { URL url = new URL(sUrl[0]); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.addRequestProperty("Authorization", "Token " + authToken); urlConnection.connect(); int fileLength = urlConnection.getContentLength(); // download the file InputStream input = new BufferedInputStream(urlConnection.getInputStream());//url.openStream()); OutputStream output = new FileOutputStream(path); byte data[] = new byte[1024]; long total = 0; int count; while ((count = input.read(data)) != -1) { total += count; //publishProgress((int) (total * 100 / fileLength)); output.write(data, 0, count); } output.flush(); output.close(); input.close(); urlConnection.disconnect(); } catch (Exception e) { Log.e("SVC0", e.getMessage()); } return path; } Then I look at the Django logs and I can see that two requests are present: [09/Oct/2019 02:30:29] "GET /update HTTP/1.1" 301 0 [09/Oct/2019 02:30:35] "GET /update/ HTTP/1.1" 200 19451876 I have tried commenting out many parts but I just can't figure out why it's causing the 301 error. Any help tracking this 'bug' down would be very appreciated. -
How to send dictionary data with redirect function in Django
I'm trying to send a dictionary by the redirect method. But not getting it in the redirected template. I tried to pass the dictionary like it used to pass in the render function but I don't think I am doing this in the right way. I also tried HttpResponseRedirect but that doesn't work too. views.py def index(request): if request.method == "POST": url = request.POST.get('url', '') r = requests.get(url) soup = BeautifulSoup(r.content, features="lxml") p_name = soup.find_all("h2",attrs={"class": "a-size-mini"}) p_price = soup.find_all("span",attrs={"class": "a-price-whole"}) p_image = soup.findAll('img', {'class':'s-image','src':re.compile('.jpg')}) response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="product_file.csv"' for name,price,image in zip(p_name,p_price,p_image): writer = csv.writer(response) row = writer.writerow([image['src'],name.text, price.text,]) name_data = [data.text for data in p_name] price_data = [data.text for data in p_price] image_data = [data['src'] for data in p_image] dec = {'name':name_data, 'price':price_data, 'image':image_data, 'url':url} return redirect('data', dec) return render(request, 'index.html') -
Noob Django question: When do I make an app vs coding something for the whole website?
I want to implement things like user logins for the entire website and not within a specific app. Can someone point me in the right direction/some reference I can look up? I've looked at tutorials for the login, and they all refer to building logins within an app, not the main website. Should I build a "Welcome" or "Registration" app, and then import it into every other app? -
API response time is too slow using DRF
Activity is tourist information and tag (Preference) is tag information (such as Instagram hash tag). Function of Activity ListPreference api: For every activity, check that each activity contains tags from the request list. Only the activities that contain the tags are serialized. But it's too slow. It takes about 1 minute. The api, which returns all activities, only takes 2 seconds. What's the problem? class ActivityListByPreference(APIView): permission_classes = (permissions.AllowAny,) def get(self, request): request_tag = [6, 7, 8] activity_list = [] activity_items = Activity.objects.filter() activity_nums=activity_items.values_list('num', flat=True) b=1 for activity_num in activity_nums: print(activity_num) activity_preference_items = Activity_Preference.objects.filter(activity_num_id=activity_num) activity_tag = [] preference_nums= activity_preference_items.values_list('preference_num_id',flat=True) activity_tag=list(preference_nums) intersection = set([]) intersection = set(request_tag).intersection(set(activity_tag)) inter_list = list(intersection) inter_list.sort() if (request_tag == inter_list): print('포함합니다.') activity_list.append(activity_num) activity_preference_items = Activity_Preference.objects.all() for activity_preference_item in activity_preference_items: activity_tag.append(activity_preference_item.preference_num_id) print('끝') data = Activity.objects.filter(pk__in=activity_list) serializer = ActivitySerializer(data, many=True) print(data) return Response({"ActivityListByPreference" : serializer.data}) -
I keep receiving "No Reverse Matchup" when implementing my urls
I am getting Django error NoReverseMatch when trying my urls, along with "Reverse for 'shop' with keyword arguments '{'product_category': 'badges'}' not found. 1 pattern(s) tried: ['shop/$']" I have tried changing my url patterns and my get_absolute_url method from slug to things as "product_category", and changed the way I call in the template from obj.get_absolute_url to url 'products' slug, but neither works. Here is the get_absolute_url: def get_absolute_url(self): return reverse("shop", kwargs={"product_category":self.slug}) The urls: urlpatterns = [ path('', CategoryView.as_view(), name='shop'), path('<slug:product_category>/', ProductListView.as_view(), name='products'), path('<slug:product_category>/<slug:product>/', ProductDetailView.as_view(), name='detail'), ] The template: <a href="{{ obj.get_absolute_url }}">{{ obj.title }}</a> -
Display queryset count sitewide?
Very easy question yet I can't get it to display. I have the total number of users in the footer of the webpage. The problem is that it only shows on the home page, once I go to any other page on the site it goes away. I don't want to call it in every view. How do I get the user count to stay static in the footer site wide? Main URLs rl(r'^$', views.index, name="home"), Main views.py def index(request): users = Profile.objects.all().count() return render(request, 'layout.html', {'users': users}) layout.html <P>Total Users: ({{users}})</P> -
My images are not showing in the home ppage
Sir can you help me with this questions am very thankful for you -
AttributeError: __enter__ During connection to mysql database
I am getting AttributeError: __enter__ while executing the following code to get connection and cursor. from contextlib import closing def _connect(): return closing(mysql.connect( host=settings.DATABASES['data_base_name'].get('HOST', 'localhost'), user=settings.DATABASES['data_base_name']['USER'], passwd=settings.DATABASES['data_base_name'].get('PASSWORD', ''), db=settings.DATABASES['data_base_name']['NAME'], cursorclass=cursors.DictCursor)) with _connect() as conn, conn as cursor: I have got following error during execution. with _connect() as conn, conn as cursor: AttributeError: __enter__ -
How to execute custom SQL query when deleting a model item in Django?
I want to execute an SQL query, when an item gets deleted in the admin interface. In models.py I do this: from django.db import connection class LList(models.Model): item = models.ForeignKey(Item, models.DO_NOTHING) def delete(self, *args, **kwargs): cursor = connection.cursor() cursor.execute('DELETE FROM some_table where item = %d', [self.item.id]) When I turn debugging on I see all the queries executed. It seems the DELETE FROM query is not executed, I only see (0.000) DELETE FROM `llist` WHERE `llist`.`id` IN (27); args=(27,) Why is the other DELETE FROM query not executed? How can I fix that? -
Reverse for 'book-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['catalog/book/(?P<pk>[0-9]+)$']
My website is working well on my local environment, as well as it has been working well on heroku env until my recent deployment. Code is same on both environments and I referred to all 11 posts related to similar issue,example Reverse for 'todo-user' with arguments '('',)' not found. 1 pattern(s) tried My issue looks different than what I have seen in other posts here, I think it is related to environment settings/variables, which I am not able to identify it yet. But the solutions provided on stack overflow, makes me think like the real problem of this issue is something else. When I try to click on http://127.0.0.1:8000/catalog/mybooks/ link, local website works fine, however, production (heroku), same code throws following exception NoReverseMatch at /catalog/mybooks/ Reverse for 'book-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['catalog/book/(?P[0-9]+)$'] Request Method: GET Request URL: https://.herokuapp.com/catalog/mybooks/ Django Version: 2.2.5 Exception Type: NoReverseMatch Exception Value: Reverse for 'book-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['catalog/book/(?P[0-9]+)$'] Exception Location: /app/.heroku/python/lib/python3.7/site-packages/django/urls/resolvers.py in _reverse_with_prefix, line 673 Python Executable: /app/.heroku/python/bin/python Python Version: 3.7.3 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python37.zip', '/app/.heroku/python/lib/python3.7', '/app/.heroku/python/lib/python3.7/lib-dynload', '/app/.heroku/python/lib/python3.7/site-packages'] Server time: Wed, 9 Oct 2019 04:52:47 +0000 Error during template rendering In template /app/catalog/templates/base_generic.html, error … -
Django writing Middleware to extend self.request
I am very new to writing custom middleware in Django. We know in Django, there is built-in self.request. in self.request, there are too many instances like self.request.user, self.request.data, self.request.authenticator etc I am trying to add self.request.mycustom; in self.request.mycustom, I want to get my models MyCustom instance. This is My Models: from django.contrib.auth.models import User class MyCustom(models.Model): auth_user = models.OneToOneField( User, on_delete=models.CASCADE, related_name='auth_user', ) I am trying to write the middleware but not getting how to write this. this is my attempt to write: class MessMiddleWare(obect): def precess_view(request): mycustom = MyCustom.objects.filter(id=request.user.pk) request.mycustom = mycustom Can anyone help me to achieve this? I just I want to get self.request.mycustom -
Jquery apply callback on OnChange event which call api
Hi i'm trying to apply a callback to use on my dynamic select boxes instead of TimeOut Currently i have 4 select options boxes(3 are dynamic options): City, District(options based on city options), Ward(options based on district options) and Street(options based on district options) It's a search form so the next page form should has the previous form values, i use Django to determined if a previous form values are select , then if so it will add a hidden div with id="value-filter" in the template. And now i use the Jquery to check if that div exists to change the select options If a user click on the city option then it will activate the city onchange event to call an api that populate District options with the corresponding city Id, Ward and Street options are the same but based on District options to call their api in order to populate their options. $(document).ready(function() { //call district api if city option is selected $('select#city').change(function(event) { $.getJSON("/api_get_districts/", { id: $(this).val() }, function(j) { var options = '<option selected disabled>-- District --</option>'; for (var i = 0; i < j.length; i++) { options += '<option value="' + j[i].id + '">' + … -
Return response to download file in Django
I'm new in Django and I'm making an app that can scrap product data from Amazon. I'm able to get the data, now I want to download it as CSV file but my logic is not working. I made two forms in index.html one is to get the data & the other is to download the file. The first form is working properly but doesn't understand what is wrong with download logic or form. views.py def index(request): if request.method == "POST": url = request.POST.get('url', '') down = request.POST.get('download','') r = requests.get(url) soup = BeautifulSoup(r.content, features="lxml") p_name = soup.find_all("h2",attrs={"class": "a-size-mini a-spacing-none a-color-base s-line-clamp-2"}) p_price = soup.find_all("span",attrs={"class": "a-price-whole"}) p_image = soup.findAll('img', {'class':'s-image','src':re.compile('.jpg')}) response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="product_file.csv"' for name,price,image in zip(p_name,p_price,p_image): writer = csv.writer(response) row = writer.writerow([image['src'],name.text, price.text,]) name_data = [data.text for data in p_name] price_data = [data.text for data in p_price] image_data = [data['src'] for data in p_image] dec = {'name':name_data, 'price':price_data, 'image':image_data, 'url':url} if down: return response else: dec = {} return render(request, 'index.html',dec) index.html <div class="col-md-6"> {% if name %} <form action="" method="POST">{% csrf_token %} <input type="text" id="url" name="url" class="form-control" value="{{url}}" placeholder="URL" required autofocus> <p class="mt-1 text-light"> Download Your Scraped File</p> <button type="submit" class=" btn btn-info btn-lg" … -
Django model instance not saving and no errors thrown
The Customer data and the Contact data in the below method is not getting saved and there is no error thrown. Also when I printed the Customer objects after assigning it in the def then it shows the correct data but the same is not reflected in the DB. I have also overridden the save def in the model class and included exception handling but no exception is thrown either. Not sure what else needs to be added. Please advise. views.py @login_required def modify(request, customer_customerid): #print_request(request) customer = get_object_or_404(Customer, pk=customer_customerid) contact = Contact.objects.get(reftable='Customer', refid=customer_customerid) if request.method =='POST': print(request.POST['txtCustomerName'],'Hi') if request.POST['txtCustomerName'] and request.POST['txtCustShortName'] and request.POST['dtMSAStartDate'] and request.POST['dtMSAEndDate'] and request.POST['selCustState'] and request.POST['selCustCountry'] and request.POST['selCustTimeZone']: customer.CustomerName = request.POST['txtCustomerName'] customer.CustomerShortName = request.POST['txtCustShortName'] customer.MSAStartDate = request.POST['dtMSAStartDate'] customer.MSAEndDate = request.POST['dtMSAEndDate'] if request.POST['chkExternalCustomer'] == u'true': customer.ExternalCustomer = True else: customer.ExternalCustomer = False customer.State = request.POST['selCustState'] customer.Country = request.POST['selCustCountry'] customer.TimeZone = request.POST['selCustTimeZone'] if request.POST['chkIsActive'] == u'true': customer.Active = True else: customer.Active = False customer.AllDataSourceRequired = True customer.LastModifiedUTC = timezone.datetime.now() customer.LastModifiedBy = request.user try: print(str(customer.CustomerShortName),'Hello') customer.save(update_fields=["customershortname"]) transaction.commit() print(Customer.objects.values()) except Exception as e: print(e.message()) contact.FirstName = request.POST['txtContactFirstName'] contact.LastName = request.POST['txtContactLastName'] contact.ContactEmail = request.POST['txtCustomerEmail'] contact.save() return redirect('/customers/' + str(customer_customerid)) else: return render(request,'customers/detail.html' ,{'error':'All fields are required.'}) else: detail(request, customer_customerid) models.py from … -
Django ading custom instance in self.request
I am not getting how to extend self.reqeust In Django rest framework or Django view, we can access to many things with self.reqeust like if we want to get authenticated user, then we write self.request.user also, you know there are too many instances of self.request like self.request.user, self.request.data, self.request.authenticator I am trying to extend this and want to get self.request.mycustominstance Can anyone help me where can I extend like this? -
Serving pytorch model with django and uwsgi, how can the system support multi requests concurrency?
If I street-test the API with 10 concurrency requests: using django built-in server, python3 manage.py runserver, the average response time is about 10 times longer than 1 concurrency request using uwsgi to start 10 progress, the average response time is about 5 times longer than 1 concurrency request How can I handle multi requests in instant response time? -
Rename Django User fields
I'm using the default Django User class and authentication for a simple user LogIn. This User model has two important fields: "username" and "password". I want them to be "user" instead of "username", and "pass" instead of "password". I know I can make a RenameField, but that will only change the column name in the database, it won't change how Django asks for the username and password in the body of the POST request. I need to change the keys in the JSON given in the request. from: { "username": "user123", "password": "pass123" } to: { "user": "user123", "pass": "pass123" } And I think I can create a file called serializer and do something there but I'm not sure how, and I didn't found anything in the documentation. If they're useful, these are my files. urls.py: from rest_framework.authtoken.views import obtain_auth_token from django.contrib import admin from catanAPI.catan import views from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), path('users/login/', obtain_auth_token) ] settings.py INSTALLED_APPS = [ #... 'django.contrib.auth', 'rest_framework', 'rest_framework.authtoken' #... ] AUTH_USER_MODEL = 'auth.User' REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ] } I know this question may be stupid or something, but I'm new in Django, and I'm trying to learn. -
How to retrieve validation error in Django CreateView?
I have a model, form, and view that used to work and now that I changed the form to add receiver it is not submitting the form but rather just reloading the form in-place (validation error). How do I find what exactly is causing this error? How do I troubleshoot this for future reference? Models.py class Memo(models.Model): EMPLOYEE_CHOICES = ( ('dealer', 'DEALER'), ('server', 'SERVER'), ('cage staff', 'CAGE STAFF'), ('security', 'SECURITY'), ('casino supervisor', 'CASINO SUPERVISOR'), ('food bev supervisor', 'FOOD BEV SUPERVISOR'), ('cage supervisor', 'CAGE SUPERVISOR'), ('security supervisor', 'SECURITY SUPERVISOR'), ) title = models.CharField(max_length=100) content = models.TextField() date_time = models.DateTimeField(default=timezone.now) sender = models.ForeignKey(User, on_delete=models.CASCADE) receiver = models.CharField(max_length=30, choices=EMPLOYEE_CHOICES, default='dealer') def __str__(self): return self.title def get_absolute_url(self): return reverse('memos-detail', kwargs={'pk': self.pk}) Forms.py class MemoForm(forms.ModelForm): EMPLOYEE_CHOICES = ( ('dealer', 'DEALER'), ('server', 'SERVER'), ('cage staff', 'CAGE STAFF'), ('security', 'SECURITY'), ('casino supervisor', 'CASINO SUPERVISOR'), ('food bev supervisor', 'FOOD BEV SUPERVISOR'), ('cage supervisor', 'CAGE SUPERVISOR'), ('security supervisor', 'SECURITY SUPERVISOR'), ) title = forms.CharField() content = forms.CharField(widget=forms.Textarea) receiver = forms.ChoiceField(choices=EMPLOYEE_CHOICES, widget=forms.CheckboxSelectMultiple) class Meta: model = Memo fields = ('title', 'content', 'receiver', ) Views.py class MemoCreateView(LoginRequiredMixin, CreateView): model = Memo form_class = MemoForm def form_valid(self, form): form.instance.sender = self.request.user form.save() return super(MemoCreateView, self).form_valid(form)