Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
VSCode + remote dev + django: avoiding forwarding ports
I'm using VSCode remote development to run and debug a django project inside a Docker container. In my devcontainer.json I forwarded the port 8000 "forwardPorts": [8000], and this is my launch.json { "version": "0.2.0", "configurations": [ { "name": "Python: Django", "type": "python", "request": "launch", "program": "${workspaceFolder}/myapp/manage.py", "args": [ "runserver", "0.0.0.0:8000" ], "django": true } ] } When I start the debug with such a configuration, I see 4 ports forwarded: port 8000 and other 3 rendom high ports 8000 -> localhost:8000 (the only one I'd expect to see) 34075 -> 127.0.0.1:34075 37301 -> 127.0.0.1:37301 42129 -> 127.0.0.1:42129 I'm wondering the reason why those three ports are forwarded and how I can avoid it. -
Add link on a web page to export tables2 data in Django
I'm trying to include a link on a webpage to download a tables2 table to csv. I got the commented out piece below from the documentation, and I think it might just need a simple tweak to get it to work with my code. Any thoughts? views.py class PlatListView(SingleTableMixin, FilterView): model = Plat template_name = 'blog/filtertable.html' filter_class = PlatFilter def get_context_data(self, **kwargs): context = super(PlatListView, self).get_context_data(**kwargs) query = Phase.objects.all().select_related('plat','plat__community') f = PlatFilter(self.request.GET, queryset=query) t = PlatTable(data = f.qs) RequestConfig(self.request, paginate=False).configure(t) context['filter'] = f context['table'] = t ''' export_format = self.request.GET.get("_export", None) if TableExport.is_valid_format(export_format): exporter = TableExport(export_format, query) return exporter.response("query.{}".format(export_format)) ''' return context filtertable.html {% extends "blog/base.html" %} {% block content %} {% load querystring from django_tables2 %} <div style = 'padding-top: 24px'> <a href="{% querystring '_export'='csv' %}">Download CSV</a> </div> {% load render_table from django_tables2 %} {% load bootstrap4 %} {% if filter %} <form action="" method="get" class="form form-inline"> {% bootstrap_form filter.form layout='inline' %} {% bootstrap_button 'filter' %} </form> {% endif %} {% render_table table 'django_tables2/bootstrap4.html' %} {% endblock content %} -
Highcharts range selector buttons and input filter not working
I've created a chart using Highcharts in Django but the range selector buttons do not work and input range starts from 1970 instead of my first date. I guess it's something to do with dates formatting but I can't figure it out ... I'm reading a JSON file content with dates entry formatted in milliseconds, ex: 1527465600000. The chart is displayed just fine, the range selector at the bottom of the chart works just fine as well, and dates on the X-axis are nicely formatted as expected. What I want is for the range selector buttons to work, and for the range selector input filter to start from my first date instead of starting from the 1st of Jan 1970. Here's my highcharts code: {% block javascripts %} {% load static %} <script src="https://code.highcharts.com/stock/highstock.js"></script> <script> fetch("{% static 'highcharts_1.json' %}") .then(response => response.json()) .then(mydata => { console.log(mydata.sample1,mydata.dates) Highcharts.chart('mychart_1', { chart: { zoomType: 'x', type: 'spline', }, xAxis: { type: 'category', categories: mydata.dates, labels:{ formatter: function() { return Highcharts.dateFormat('%d %b %Y', this.value); }, align: 'right', rotation: -90, }, }, yAxis: { min: 0, max: 1, tickInterval: 0.1, title: { text: 'Score' } }, legend: { layout: 'vertical', align: 'right', verticalAlign: 'middle' }, … -
How do I get a perticular subcategory that has the same name under the other category in Django?
I have a shop-application and theres categories and subcategories, I have 3 categories and under each one of those there's a subcategory called Other and when I click on the url for it I get this error: MultipleObjectsReturned at /categories/subcategory/Other, get() returned more than one SubCategory -- it returned 3! I do realise that using filter is not an option since it would return 3 values and a url cant accept a queryset as an argument, could I perhaps somehow also use the subcategorys category title` to filter the query or do you have any other ideas? Here is the code: urls.py path('subcategory/<str:title>/', views.subcategory, name='subcategory'), views.py def subcategory(request, title): subcategory = SubCategory.objects.get(title=title) products = Product.objects.filter(subcategory=subcategory) return render(request, 'subcategory.html', {'subcategory': subcategory, 'products': products}) -
Separating Django REST back from Front end
This is a bit of a different question. I've tried researching the information for a few hours now and I can't seem to find what I am looking for. I have a Django REST backend that I set up. Its very simple REST API that has one Model Model.py from django.db import models # Create your models here. class Hero(models.Model): name = models.CharField(max_length=60) alias = models.CharField(max_length=60) def __str__(self): return self.name I'm able to post to via the REST api interface see image below I'd like to have the Django server running in the background while I create a front end whose files (index.html, main.css, app.js ect....) are separate from the django project. I would then use Axios to GET, POST data to the database using the following url http://127.0.0.1:8000/api/heroes/ Below is the code from my front end import axios from "axios"; export default class SuperHero { constructor() { this.superHeroForm = document.querySelector("#superHeroForm"); this.events(); } events() { this.superHeroForm.addEventListener("submit", e => this.onSubmit(e)); } onSubmit(e) { e.preventDefault(); console.log("onSubmit ran"); this.name = document.querySelector("#name").value; this.alias = document.querySelector("#alias").value; axios .post("http://127.0.0.1:8000/api/heroes/", { name: this.name, alias: this.alias }) .then(res => { console.log(res); }) .catch(e => { console.log(e); }); } } However I am getting a CROS error Access to … -
How to index into a django model's attribute?
I am making a blog and have a model for an article: class Article(models.Model): title = models.CharField(max_length=200) author = models.CharField(max_length=120) content = models.TextField(db_index=True) committee = models.CharField(max_length=50) likes = models.IntegerField(default=0) I am working on a method of truncating posts and need to access the first few characters of the content attribute. I tried {{article.content[40]}} (article has been passed in as context in my view function) but that threw this error: Could not parse the remainder: '[0:40]' from 'article.content[0:40]' Does anyone know how to index into an attribute like this? Thanks! -
Copied and modified Django project stills show old templates
I copied and pasted a project developed with Django to modify it. However, after modifying one of the templates a little (the home.html), no modification appears. Is it because this project is not original? Do I have to recreate it from the beginning? For example, I changed the name of the template "home.html" to "homes.html". Then the first one should not be called and all that should result in an error. But as you can see there is no error and the home.html continues to be called Even after following this answer about renaming a Django project, I can't see my modifications being taken into account. -
Starting a django project with pipenv
I was trying to make a django project so I changed the directory to the specific folder and installed django there, but after running 'pipenv shell' someting weird happened. instead of lunching the virtual environment in the directory it jumped to other directory. how can I fix it? here is the picture -
django retrieving all objects from one to many model relationship in shell
how can I get all tasks that are inside one board? (every user can create a board and inside that board the user can create tasks) I've tried "Board.objects.get(pk=1).title.title" but that doesn't seem to work. (code: https://pastebin.pl/view/a479e227) -
Django Form Not Adding to SQLite3 Database
I have the following Django form that is purposed to create a new item in my database. It is returning a 'false-positive' in that it shows a green 'Done' after I hit submit but the record is not actually added to the database. Any ideas what is causing this? html <form method="POST"> {% csrf_token %} {{form}} <div style="color:green">{{info}}</div> <div style="color:red">{{error}}</div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Submit</button> </div> </form> views.py def creator(request): if request.method == "POST": form = CommunicationsForm(request.POST) if form.is_valid(): form.save() return render(request,'polls/creation.html',{"form":CommunicationsForm,"info":"Done"}) else: return render(request,'polls/creation.html',{"form":CommunicationsForm}) forms.py class CommunicationsForm(forms.ModelForm): class Meta: model = Communications fields = "__all__" widgets = { 'project':forms.TextInput(attrs={'class': 'form-control','placeholder':'Enter your Project Name'}), 'title':forms.TextInput(attrs={'class': 'form-control','placeholder':'Enter a short Title'}), 'intent':forms.Textarea(attrs={'class': 'form-control','placeholder':'Describe the intent and desired outcome of the communication'}), 'date':forms.TextInput(attrs={'class': 'form-control','placeholder':'Select a Date'}), 'channel':forms.Select(attrs={'class': 'form-control','placeholder':'Select a Channel'}), 'content_type':forms.Select(attrs={'class': 'form-control','placeholder':'Select a Content Type'}), 'audience':forms.TextInput(attrs={'class': 'form-control','placeholder':'Enter the Audience(s)'}), 'status':forms.Select(attrs={'class': 'form-control','placeholder':'Select the Status'}), } models.py class Communications(models.Model): project = models.CharField(max_length=200) title = models.CharField(max_length=200) intent = models.CharField(max_length=200) date = models.CharField(max_length=200) channel = models.CharField(max_length=200) content_type = models.CharField(max_length=200) audience = models.CharField(max_length=200) status = models.CharField(max_length=200) def __str__(self): return self.communication -
Django - Create User with Additional Profile Fields
I've got a view where I collect user data and save it to the backend. def register(request): if request.method == 'POST': form = UserSignUpForm(request.POST) if form.is_valid(): form.save() return redirect('additional_info') else: form = UserSignUpForm() return render(request, 'users/signup.html', {'form': form}) Once this is complete, I redirect the user to another page where they can provide additional info in another form for their profile like their dob, profile pic etc. This uses the following code for the view: def additionalInfo(request): if request.method == 'POST': form = ProfileForm(request.POST) if form.is_valid(): form.save() return redirect('app-home') else: form = ProfileForm() return render(request, 'users/addInfo.html', {'form': form}) The problem is when I try to save the second form I get the exception: NOT NULL constraint failed: users_profile.user_id I'm guessing this is because I have this defined in my Profile model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) meaning I need to supply the user for which I want to create this profile. How do I obtain the info of the user who was just registered using the register view and make it available in the additionalInfo view? -
django single app multiple dbs: same tables get created in all dbs
I am test-developing a django project with a single app (app_name) where I want to have 2 models (say: model_A and model_B), with their instances stored in separate DBs (say: DB_A.sqlite3, DB_B.sqlite3). I also have third DB (DB_users.sqlite3) for storing anything related to auth, sessions etc. I am trying to implement multiple dbs as per django documentation, with database routing etc., but I noticed at migrations that in each of those 3 DBs irrelevant tables get created for both models. For example, DB_A would have my_app_model_A as well as my_app_model_B table created. But the thing is my_app_model_B should only be stored in DB_B. What can be the reason for this / how to ensure that only relevant tables get created in correct DBs? -
AttributeError: type object 'EmailCrawler' has no attribute '__annotations__' in Celery
A very quick question. I'm trying to install Celery. The installation proceeded correctly, because when I run the Celery event, it runs correctly, although I'm trying to put the @shared_task method in a Email Crawler so that it can go faster. But the following error jumps out whenever I try to set the @shared_task: Error: C:\Users\user\Desktop\leadfinder>celery -A leadfinder worker -l info -P eventlet Traceback (most recent call last): File "c:\users\user\appdata\local\programs\python\python39\lib\runpy.py", line 197, in _run_module_as_main return _run_code(code, main_globals, None, File "c:\users\user\appdata\local\programs\python\python39\lib\runpy.py", line 87, in _run_code exec(code, run_globals) File "C:\Users\user\AppData\Local\Programs\Python\Python39\Scripts\celery.exe\__main__.py", line 7, in <module> File "c:\users\user\appdata\local\programs\python\python39\lib\site-packages\celery\__main__.py", line 15, in main sys.exit(_main()) File "c:\users\user\appdata\local\programs\python\python39\lib\site-packages\celery\bin\celery.py", line 213, in main return celery(auto_envvar_prefix="CELERY") File "c:\users\user\appdata\local\programs\python\python39\lib\site-packages\click\core.py", line 829, in __call__ return self.main(*args, **kwargs) File "c:\users\user\appdata\local\programs\python\python39\lib\site-packages\click\core.py", line 782, in main rv = self.invoke(ctx) File "c:\users\user\appdata\local\programs\python\python39\lib\site-packages\click\core.py", line 1259, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "c:\users\user\appdata\local\programs\python\python39\lib\site-packages\click\core.py", line 1066, in invoke return ctx.invoke(self.callback, **ctx.params) File "c:\users\user\appdata\local\programs\python\python39\lib\site-packages\click\core.py", line 610, in invoke return callback(*args, **kwargs) File "c:\users\user\appdata\local\programs\python\python39\lib\site-packages\click\decorators.py", line 21, in new_func return f(get_current_context(), *args, **kwargs) File "c:\users\user\appdata\local\programs\python\python39\lib\site-packages\celery\bin\base.py", line 132, in caller return f(ctx, *args, **kwargs) File "c:\users\user\appdata\local\programs\python\python39\lib\site-packages\celery\bin\worker.py", line 320, in worker worker = app.Worker( File "c:\users\user\appdata\local\programs\python\python39\lib\site-packages\celery\worker\worker.py", line 94, in __init__ self.app.loader.init_worker() File "c:\users\user\appdata\local\programs\python\python39\lib\site-packages\celery\loaders\base.py", line 111, in init_worker self.import_default_modules() File "c:\users\user\appdata\local\programs\python\python39\lib\site-packages\celery\loaders\base.py", line 105, in import_default_modules … -
How to send email and get model object in celery task?
If I remove the line object = MyModel.objects.get(pk=pk) it works as I excepted. But After trying to get the object in my task I got this error django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. I want to get the model object in my celery task while sending email for the purpose of context. tasks.py @shared_task def send_email(subject, body, from_email, to_email, pk): print(pk, subject, from_email) object = MyModel.objects.get(pk=pk) if object: context = {'object':object} else: context = {} email = EmailMultiAlternatives(subject, body, from_email, [to_email]) email.content_subtype = 'html' email.mixed_subtype = 'related' pdf = render_to_pdf( 'invoice.html', context=context ) email.attach('invoice.pdf',pdf) email.send() views send_email.delay(sub, body, from_email, user.email, obj.pk) -
How can I set up my Django function to run in the background from button onclick?
I have a Django project and one of the functions currently runs onclick of my html - def follow(request): api = get_api(request) followers = tweepy.Cursor(api.followers_ids, wait_on_rate_limit=True).items() for x in followers: try: api.create_friendship(x) except Exception: pass return render(request, "followed.html") The function runs and follows the followers of the authorised user. My issue is that when deployed on my pythonanywhere web app the function will load in the browser and then timeout after around 10 minutes. I have tested on users up to 100 followers and it all works. This would be fine but the Twitter API has a rate limit and so for some users who have large followings this function will take a long time to complete. Is there a way of diverting to the followed.html and keeping the function running in the background until it is completed? I have added the oauth functions just in case they are needed too - def auth(request): # start the OAuth process, set up a handler with our details oauth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) # direct the user to the authentication url # if user is logged-in and authorized then transparently goto the callback URL auth_url = oauth.get_authorization_url(True) response = HttpResponseRedirect(auth_url) # store the … -
Reverse for 'sales' with no arguments not found. 1 pattern(s) tried: ['sales/(?P<pk>\\d+)/$']
I have seen a lot of relatable questions and answers, I just haven't understood even after tweaking my code why it doesn't seem to respond. I am new to django, I am hoping someone can point me in the right direction. Views.py @login_required def add_user_sales(request , pk): current_user = request.user context = {} context["data"] = MadeSale.objects.get(id=pk) profiles = UserProfile.get_profile() for profile in profiles: if profile.profile_name.id == current_user.id: if request.method == 'POST': form = SalesForm(request.POST) if form.is_valid(): upload = form.save(commit=False) upload.posted_by = current_user upload.profile = profile upload.save() messages.success(request, f'Hi, Your data has successfully been updated' ) return redirect('addProduct') else: form = SalesForm() return render(request,'addProduct.html',{"user":current_user,"form":form}, context) linked url <nav class="navbar" style="margin-left: auto;"> <ul class="ul" style="margin-left: auto;"> <li class="li"><a href="{% url 'user' %}">Home</a></li> <li class="li"><a href="{% url 'sales'add_user_sales.pk %}">Sales</a></li> ***(This line is the culprit)*** <li class="li"><a href="{% url 'total' %}">Total</a></li> <li class="li"><a href="{% url 'margin' %}">Margin</a></li> <!-- For DevelopmentPurposes --> <li class="li"><a href="http://127.0.0.1:8000/admin/">Admin Dashboard</a></li> <li class="li"><a href="{% url 'monthlyTotal' %}">Total</a></li> </ul> </nav> my url url(r'sales/(?P<pk>\d+)/$', views.add_user_sales, name='sales'), -
Hi I have injected Tinymce using JavaScript file into django got 404 page not found error
My Code In setting Stat files are set as below>> In admin i i rejistered it like below>>>JS file mentioned below STATICFILES_DIRS= [os.path.join(BASE_DIR, 'static'), ]``` ```@admin.register(Blogpost) class BlogpostAdmin(admin.ModelAdmin): class Media: js = ('blog/tiny.js',)``` ``` var script = document.createElement('script'); script.type = 'text/javascript'; script.src = "https://cdn.tiny.cloud/1/no-api-key/tinymce/5/tinymce.min.js"; document.head.appendChild(script); script.onload=function () { tinymce.init({ selector: '#id_content',``` -
Django Admin Customization (Change list display by the user)
At Django Admin, we can use "list_display" to choose which column to show. I want to customize Django admin so that we can decide which column to show dynamically (Not using "list_display) I want the user to be able to use something like a checkbox. Again, not by changing Python codes. I tried the following but it seems nothing to do with the display of listing. Dynamic fields in Django Admin It seems I need to override/extend some Django template using JavaScript but I am not so sure. Any comment would be greatly appreciated. (I much prefer to implement it in admin rather than outside of admin, though.) Many thanks, -
Django send mail from docker container how to expose port
The mail sending works fine without the docker container. I think I actually opened the SMTP Port. Here is my docker-compose file: version: "3.9" services: db: <some postgres setup> api: build: . command: python manage.py runserver 0.0.0.0:8000 --settings=api.settings.production volumes: - .:/code ports: - "8000:8000" - "587:587" - "25:25" expose: - 587 - 25 env_file: - ./.env.dev depends_on: - db entrypoint: /entrypoint.sh mail: build: . command: python manage.py qcluster --settings=api.settings.production depends_on: - api It doesn't work to send mails no matter if I send it as an async task with django q or directly with django.core.mail.send_mail Here is my mail settings.py: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'mail' EMAIL_HOST_PASSWORD = 'password' EMAIL_USE_TLS = True EMAIL_USE_SSL = False I get an OSError OSError: [Errno 99] Cannot assign requested address -
Get current post's category
So as the title says, i need to get the current post's category to use it in a "related posts" section, more precisely what to put in cat_posts = Post.objects.filter(Category=????) (don't mind the comments variable since i removed part of my PostView from this post) here's my code views.py def PostView(request, slug): template_name = 'post-page.html' post = get_object_or_404(Post, slug=slug) comments = post.comments.filter(active=True) cat_posts = Post.objects.filter(Category=Post.Category) cat_posts = cat_posts.order_by('-Date')[:3} return render(request, template_name, {'post': post, 'cat_posts':cat_posts}) models.py class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return str(self.name) class Post(models.Model): title = models.CharField(max_length=120) Category = models.CharField(max_length=120, default='None') Thumbnail = models.ImageField(null=True, blank=True, upload_to="images/") Text = RichTextField(blank=False, null=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE) Overview = models.CharField(max_length=400) Date = models.DateTimeField(auto_now_add=True) main_story = models.BooleanField(default=False) def __str__(self): return str(self.title) def get_absolute_url(self): # return reverse('about', args=(str(self.id))) return reverse('home') -
HTML to PDF also with keeping the CSS & bootstrap styling in Django
I am trying to render an HTML page into PDF in Django by following this GitHub tutorial link. My views.py: def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None class ViewPDF(View): def get(self, request, *args, **kwargs): pdf = render_to_pdf('app/pdfpage.html', data) return HttpResponse(pdf, content_type='application/pdf') #Automaticly downloads to PDF file class DownloadPDF(View): def get(self, request, *args, **kwargs): pdf = render_to_pdf('app/pdfpage.html', data) response = HttpResponse(pdf, content_type='application/pdf') filename = "Invoice_%s.pdf" %("12341233") content = "attachment; filename='%s'" %(filename) response['Content-Disposition'] = content return response However I almost copy all the code from that tutorial link except pdfpage.html, I put there my custom made HTML page also with bootstrap and CSS styling. Now my problem is after converting and saving this pdf, it lost all the styling and bootstrap styling stuff, but those are also important for me. how can I solve this problem? -
Geonode Error: ModuleNotFoundError: No module named 'geonode.local_settings'
Hi I'm installing geonode in Ubuntu 20.04 I followed the steps in this guide, but I have an error when I want to install the webserver (Step 6) https://docs.geonode.org/en/master/install/advanced/core/index.html#postgis-database-setup Traceback (most recent call last): File "./geonode/wsgi.py", line 30, in application = get_wsgi_application() File "/home/xrdpuser/.virtualenvs/geonode/lib/python3.8/site-packages/django> django.setup(set_prefix=False) File "/home/xrdpuser/.virtualenvs/geonode/lib/python3.8/site-packages/django> configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/home/xrdpuser/.virtualenvs/geonode/lib/python3.8/site-packages/django> self._setup(name) File "/home/xrdpuser/.virtualenvs/geonode/lib/python3.8/site-packages/django> self._wrapped = Settings(settings_module) File "/home/xrdpuser/.virtualenvs/geonode/lib/python3.8/site-packages/django> mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.8/importlib/init.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) ModuleNotFoundError: No module named 'geonode.local_settings' What am I doing wrong? This is my geonode.ini is the same as that of the guide by changing this virtualenv = /home/xrdpuser/.virtualenvs/geonode Thank you Regards Abel Quesi -
Adding a redirect to CreateAPIView
I want to redirect the user to the AddQuestionsView after the user creates a quiz(after adding title). My CreateQuiz class CreateQuizzView(CreateAPIView): serializer_class = CreateQuizSerializer My serializers.py file class CreateQuizSerializer(serializers.ModelSerializer): class Meta: model = Quizzer fields = ['title'] def create(self, validated_data): user = self.context['request'].user new_quiz = Quizzer.objects.create( user=user, **validated_data ) return new_quiz Can i add redirect by adding any Mixin or change need to change the GenericView. -
Django feeding file data to a model
If you got a form that asks the user for a file upload and the file after some preprocessing gets a data dict which is fed to the model. How is the preprocessing step is to be done in this case? In the subclassed FormView's is_valid method one can do form.files to get the file obj, read it , preprocess it there and then feed the data to a model instance. But I think this would block the thread. What's the correct way? -
Modal Form Not Showing in Django
I have the the following modal that I am trying to use as a Create/Edit form for my SQLite3 data but nothing ever appears. I can connect this form to it's own URL and that works fine, but I am looking to include it within the same /communications url just as a pop-up (enabling the user to stay on the same screen and quickly fill out the form). Any clue as to why this is not working? models.py class Communications(models.Model): team = models.CharField(max_length=200) title = models.CharField(max_length=200) date = models.CharField(max_length=200) def __str__(self): return self.communication forms.py class CommunicationsForm(forms.ModelForm): class Meta: model = Communications fields = '__all__' urls.py path('communications/', views.CommunicationsView.as_view(), name='communications'), views.py class CommunicationsView(generic.ListView): template_name = 'polls/communications.html' context_object_name = 'comms_list' def get_queryset(self): """Return the last five published questions.""" return Communications.objects.order_by('id') def CommCreation(request): form = CommunicationsForm() context = {'form':form} return render(request, 'polls/communications.html', context) polls/communications.html: <div class="modal-body"> <form method="POST"> {% csrf_token %} {{form}} <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Save changes</button> </div> </form> </div>