Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
reactivate virtualenv when returning to a project the next day
I am new to django i started a project in a virtualenv then shutdown the computer when I was done for the day. so How do I return to the same virtualenv the next day to continue with the project? -
i would like to add a row from one table to another table according to the given id in django
i tried django queryset update() but in documentation it says it can only access one database table. i would like to make the condition that the row will be added in table if the another table field verification is true. i am using postgresql for database. class All(models.Model): sn=models.CharField(max_length=100,null=False, blank=False) munID=models.CharField(max_length=100,null=False, blank=False, primary_key=True) fid=models.CharField(max_length=100,null=False, blank=False) ProvinceName=models.CharField(max_length=100,null=False, blank=False) DistrictName=models.CharField(max_length=100,null=False, blank=False) PalikaName=models.CharField(max_length=100,null=False, blank=False) PalikaType=models.CharField(max_length=100,null=False, blank=False) class All_Temp(models.Model): sn=models.CharField(max_length=100,null=False, blank=False) munIDD=models.CharField(max_length=100,null=False, blank=False, primary_key=True) fid=models.CharField(max_length=100,null=False, blank=False) ProvinceName=models.CharField(max_length=100,null=False, blank=False) DistrictName=models.CharField(max_length=100,null=False, blank=False) PalikaName=models.CharField(max_length=100,null=False, blank=False) PalikaType=models.CharField(max_length=100,null=False, blank=False) verification=models.CharField(max_length=100,null=False, blank=False) thank you in advance -
Django Graphene query filtering for foreign key
I have a django model class Person(models.Model): name = models.CharField() address = models.CharField() class Blog(models.Model): person = models.ForeignKey('Person', on_delete=models.CASCADE, blank=False, null=False) text = models.TextField() How do I write a graphene schema that allows query filtering by a foreign key? class Query(graphene.ObjectType): blog = graphene.Field(BlogType) blogs = graphene.List(BlogType, person=graphene.???, #Foreign Key call here text=graphene.String()) def resolve_blog(self, info, id): return Blog.objects.get(pk=id) def resolve_blogs(self, info, person = None, text = None, **kwargs) if person: filter = Q(person__icontains = person.name) #Filter for foreign key return Blog.objects.filter(filter) -
SMTPServerDisconnected error uploading multiple attachment with EmailMultiAlternatives
What I have I'm uploading multiple attachments with EmailMultiAlternatives from admin in Django. works great for one or several lightweight files, but when I try to upload multiple files, say 2 or 3 that are heavy, it keeps loading the page and after a moment it throws the error SMTPServerDisconnected. Custom wrapper function to send mail def send_mail( subject: str, message: str, recipient_list: List[str], from_email: Optional[str] = None, **kwargs: Any, ) -> int: """Wrapper around Django's EmailMultiAlternatives as done in send_mail(). Custom from_email handling, special Auto-Submitted header and optional attachment files. """ if not from_email: if hasattr(settings, "DEFAULT_FROM_EMAIL"): from_email = settings.DEFAULT_FROM_EMAIL else: from_email = "webmaster@localhost" connection = kwargs.get("connection", False) or get_connection( username=kwargs.get("auth_user", None), password=kwargs.get("auth_password", None), fail_silently=kwargs.get("fail_silently", None), ) multi_alt_kwargs = { "connection": connection, "headers": {"Auto-Submitted": "auto-generated"}, } mail = EmailMultiAlternatives( subject=subject, body=message, from_email=from_email, to=recipient_list, **multi_alt_kwargs, ) html_message = kwargs.get("html_message", None) if html_message: mail.attach_alternative(html_message, "text/html") attachments = kwargs.get("attachments", None) if attachments: for attachment in attachments: if isinstance(attachment, MIMEBase): mail.attach(attachment) # type: ignore else: mail.attach(*attachment) return mail.send() Custom admin class MessageFileInlineAdmin(admin.StackedInline): """Edit Message File on the same Message admin page. https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.TabularInline """ model = MessageFile extra = 1 @admin.register(Message) class MessageAdmin(admin.ModelAdmin): """Representation of a Message model in the admin interface.""" inlines = … -
How to integrate Django's oAuth backend with google assistant's webhook intents?
I followed the tutorial on auth0 https://auth0.com/docs/quickstart/webapp/django/ and was able to get a webpage that allows for user creation based on auth0 authentication. It uses social_core.backends.oauth with a middle layer that processes some of the authentication. I've also set up a test for my google home action device that sends an action.devices.SYNC via webhook and it gives me an authorization/bearer key that I should use to send to auth0 to retrieve userinfo that will allow me to access this bearer's account information, so that I can use the email address to access additional info in my server for smart home actions. I see that in the example, by the time it gets to: def dashboard(request): user = request.user auth0user = user.social_auth.get(provider='auth0') that request has a user object that lets me retrieve additional information on the user. How do I do the same thing with my webhook? It does not have a user object, but I'm not sure how to patch that into my existing webhook handler, it uses: class frontEndConsumer(AsyncHttpConsumer): async def http_request(self, request): # processes request object, extracts header and body, etc -
How do I remove a model item and adding a new item in Django?
I am getting this error. django.core.exceptions.FieldError: Unknown field(s) (description) specified for Todo I deleted my migrations folders. I tried migrating my files using the updated items. Originally I had this- class Todo(models.Model): title = models.CharField(max_length=50) description = models.CharField(max_length=100) I tried to change it to this, but it won't let me. class Todo(models.Model): title = models.CharField(max_length=50) completed = models.BooleanField(default=False) What can I do besides starting over? Thank you. How do I remove a model item and adding a new item in Django? -
NameError: name 'Watchlist' is not defined although I defined it
I'm implementing a watchlist page but Im getting this error. This is the line of code that is failing: def watchlist(request, listing_id): watchlist = Watchlist(user=request.user, mylist=listing_id) Why am i getting a name error if I have it defined here? class Watchlist(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) mylist = models.ForeignKey(Listing, on_delete=models.CASCADE) This model is at the end of models.py, so this is not a problem where i am referencing something that I havent previously defined. I also have it imported in admin.py. Any ideas? -
(django)i created a todo app in django but everytime i update the task. It creates a new object
It creates new object everytime i update the task. I tried alot but it still does mot work correctly .Help me please def index(request): task = Task.objects.all().order_by('-created_on') form= TaskForm() if request.method=='POST': form= TaskForm(request.POST) if form.is_valid(): form.save() return redirect ('/') return render(request('task/list.html',{'task':task,'form':form}) def update_task(request,pk): task =Task.objects.get(id=pk) form= TaskForm(instance= task) if request.method=='POST': form= TaskForm(request.POST,instance=task) if form.is_valid(): form.save() return redirect('/') return render(request,'task/update_task.html', {'form': form}) -
how to save the data in unbound ModelForm, after user puts in the missing values in the rendered form, to the database in Django 3.0?
I am a beginner in Django and don't know what I am missing. Here's the issue: I am creating a ModelForm to create an offer on a property where I am putting in initial values to some of the fields such as property's address, offer price, user_id, property_id and leave some fields upto the user to fill in like whether he wants to pay in cash or loan, what's the down payment etc. So after the user makes some changes and presses submit at the bottom of the form, I want the form to save to the corresponding table in the postgres db. Here's the code: #models.py class Offers(models.Model): listing = models.ForeignKey('something.something', on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.CharField(max_length=100) email = models.EmailField() street_address = models.CharField(max_length=200) city = models.CharField(max_length=50) state = models.CharField(max_length=2) and so on... # forms.py from django import forms from .models import Offers class OfferForm(forms.ModelForm): class Meta: model = Offers fields = ['name', 'email', 'street_address', 'city', 'state', 'zipcode', 'offer_price', 'some', 'other', 'fields'] exclude = ['some', 'fields'] #views.py def make_offer(request): if request.method == 'POST': # create a form instance and populate it with data from the request: # I am successfully able to populate these fields with initial values … -
Image not uploading through forms on registration
I am having an issue with my forms, I've been trying to upload an image when a user registers but it does not submit because an error message is sent which says "This field is required". I'm not too sure where the issue is but I have tried to do this "a_form=InformationForm(request.POST, request.FILES)". But I still got the error message("This field is required") upon registration of the user, even though I have selected the image to be uploaded with the user when registering. I would like to know if a solution could be proffered. The image and code snippet show the issue too. Thanks FORMS from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Information class UserRegisterForm(UserCreationForm): email = forms.EmailField(widget=forms.TextInput(attrs={'placeholder': 'Email'})) username = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Username'})) first_name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'First name'})) last_name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Last name'})) password1 = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password'})) password2 = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Confirm'})) class Meta: model = User fields = ['username','first_name','last_name', 'email', 'password1', 'password2'] class InformationForm(forms.ModelForm): #sex=forms.ChoiceField(choices=CHOICES) department = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Department'})) majors = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Majors'})) nationality = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Nationality'})) date_of_birth = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'yyyy/mm/dd'})) passport_number = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Passport number'})) phone_number = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Phone number'})) student_passport = forms.ImageField() class Meta: model=Information fields=['department','majors','degree','years','nationality','date_of_birth','passport_number','phone_number','sex','student_passport'] class UserUpdateForm(forms.ModelForm): email = … -
How to create a link between Posts List View and Items List View of the same User
I am creating a project where there are Posts and Items, 2 different models in 2 different apps and each has a user who can be the same. I have created a page for each user to post all related posts called Userpost List view, and I want to add an if statement or a queryset to show a button to link the items related to the same user called Designerpost List view. I don't know how to proceed as I can fix the NoReverse Error Here is the models.py class Post(models.Model): designer = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100) Here is the views.py class UserPostListView(ListView): model = Post template_name = "user_posts.html" context_object_name = 'posts' queryset = Post.objects.filter(admin_approved=True) paginate_by = 6 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(designer=user, admin_approved=True).order_by('-date_posted') Here is the template user_posts.html {% if item %} <a class="primary btn-lg" href="{% url 'core:designer-posts' item.designer %}" role="button">Go to items</a> {% else %} <a href="{% url 'core:designer-posts' item.designer %}"> <button type="button" class="btn btn-primary btn-lg btn-block">Go to items</button> </a> {% endif %} here is the item models.py class Item(models.Model): designer = models.ForeignKey( User, on_delete=models.CASCADE) title = models.CharField(max_length=100) here is the designerlist views.py that I am trying to link to from the user … -
CSRF samesite header in django
Hello I am attempting to use csrf tokens in Django, however I am getting this error, when I submit forms: CSRF verification failed. Request aborted. You are seeing this message because this HTTPS site requires a “Referer header” to be sent by your Web browser, but none was sent. This header is required for security reasons, to ensure that your browser is not being hijacked by third parties. If you have configured your browser to disable “Referer” headers, please re-enable them, at least for this site, or for HTTPS connections, or for “same-origin” requests. If you are using the <meta name="referrer" content="no-referrer"> tag or including the “Referrer-Policy: no-referrer” header, please remove them. The CSRF protection requires the “Referer” header to do strict referer checking. If you’re concerned about privacy, use alternatives like <a rel="noreferrer" …> for links to third-party sites. Here are relevant settings I have configured in django: HOST_SCHEME = "https://" X_FRAME_OPTIONS = 'DENY' SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_HSTS_INCLUDE_SUBDOMAINS = True SECURE_HSTS_SECONDS = 15768000 SECURE_FRAME_DENY = True SECURE_REFERRER_POLICY = "same-origin" SECURE_BROWSER_XSS_FILTER = True SECURE_CONTENT_TYPE_NOSNIFF = True How do I fix this? Thanks so much for the help! -
How to store thumbnails in the same folder with Django ImageKit?
Does anyone have experience using ImageKit to manage thumbnails? I currently have the following in my models.py: class Item(models.Model): id = models.AutoField(primary_key=True) owner = models.ForeignKey( get_user_model(), on_delete=models.SET_NULL, null=True, blank=True ) image = ProcessedImageField( upload_to=image_upload, blank=True, validators=[validate_image], format='JPEG', help_text="Max file size is 3 MB." ) image_thumbnail = ImageSpecField( source='image', processors=[ResizeToFill(50, 50)], format='JPEG', options={'quality': 60} ) I'd like to rename the thumbnail and store it in a particular folder (not the CACHE/images/ folder that ImageKit defaults to), but can't figure out how to do that (and adding an "upload_to" to the thumbnail gives me an error). All help greatly appreciated! Thank you! -
Django Form Validation Error When Filtering by Count
I'm utilizing Django Forms for my web application's server-side filter functionality, and I've made a few customizations so that the checkboxes are rendered in the template with custom labels to include dynamic counts (representing # of student paper submissions), as follows: [x] Doug Funny (5) [ ] Skeeter Valentine (3) [x] Patti Mayonnaise (1) [ ] Roger Klotz (0) Right now, the field's queryset will return Student names for students who haven't submitted any papers (count = 0). As this is a bit too expensive from a page loading / performance perspective (there's a lot of student names, and a lot of paper submissions), I've decided to tweak the queryset so as to not include Student names with 0 counts in the list. To make this change, I've simply added a new filter to the query (.filter(count__gt=0)). students = Student.objects.annotate( num_papers=Coalesce( Subquery( Paper.objects.filter(student=OuterRef('pk')) .values('student') .annotate(cnt=Count('pk')) .values('cnt') ) ,0) ).filter(count__gt=0) This succesfully removes student's who haven't submitted any papers from the filter list. But now, once I select any other name in the list to filter on, I receive the following error: {'studentCheckbox': [ValidationError(['Select a valid choice. 588 is not one of the available choices.'])]} It seems that the form.is_valid() call … -
Why is Django not rendering all HTML elements?
I installed TinyMCE in my Django project so I can write a post with formatting such as bulleted lists, tables, etc. When I try to render the text box, it some elements (like a bullet) is missing, and has no formatting. TinyMCE is indeed working, as I can get a code block with syntax highlighting, but for some reason bulleted lists and even bold just appear as normal text. I put the safe flag as well. -
Get all months and years in a range
I am writing a django application where I have records stored on the basis of datetimefield. first_record = MyModel.objects.filter().order_by('-added').first() first_record = (first_record.added.month, first_record.added.year) last_record = MyModel.objects.filter().order_by('-added').first() last_record = (last_record.added.month, last_record.added.year) Now I want to make a list of all months/year between the first record and last record. A rough idea is: for i in range(first_record, last_record): # do something Where the range function is supposed to give me a list to iterate over which looks like this: [(01,2018),(02,2018),(03,2018),....,(11,2020),(12,2020)] Any ideas how do I do that? Also is (last_record.added.month, last_record.added.year) the right way to get a tuple containing month and year. Note that I want months in the format 01 instead of 1 for first month for example. -
How to make django channels group_send() send to everyone connected after a time.sleep() delay?
I have a consumers.py class method that sends a message to everyone in the channels group with group_send(), and it works great. My issue is that I have a separate, independent class method where I want to call group_send(), then time.sleep(), then group_send() again. For example: self.returnState() time.sleep(5) self.returnState() It's working (kind of) right now, but the issue is that it sends the message to everyone in the group EXCEPT the person who initially triggered the event (sent a message from the front end to consumers.py). I have no idea why this would be happening, as I would expect that if group_send() was triggered and the message was sent to one person in the group immediately, it should be sent to all. I understand asyncio.sleep() might be a more robust solution, but that would require me changing my entire consumers.py class to async. I'm very lost and any feedback would be greatly appreciated. -
Jquery script in Django project isn't detecting form submission
I'm creating a website using Django, and using Ajax to prevent site reload after submitting a form. Right now, I have orders being displayed on the site with an x button beside each order. Clicking the x cancels the order on the database (a post request that changes a value rather than simply deleting it) and also reloads the div in which the orders are housed. I have other forms on this website that are working correctly (they do have fields, though and use crispyforms). The problem I'm facing is that the script isn't detecting that the form is submitted. Here are the pertinent parts of my project: views.py class CancelForm(ModelForm): class Meta: model = Order fields = ['Filled'] ... def cancelorder(request, pk): form = CancelForm(request.POST) if request.is_ajax and request.method == "POST": order = Order.objects.get(pk=pk) order.Filled = "C" instance = order.save(update_fields=["Filled"]) return JsonResponse({"canceled": pk}, status=200) return JsonResponse({"error": ""}, status=400) urls.py urlpatterns = [ path('', views.orderpage, name="order-index"), path('cancel_order/<int:pk>/', views.cancelorder, name="cancel_order"), path('post/ajax/order/', views.postorder, name = "post_order"), path('yourorders/', views.yourorders, name="your_orders"), path('allorders/', views.allorders, name="all_orders"), ] orderpage.html (this is my main page, with the div that is to be reloaded on yourorders.html) <div class="container-fluid ActiveOrderInfoDiv" id="YourOrdersDiv"> {% include 'order/yourorders.html' %} </div> yourorders.html <form action="{% url … -
Why does it shows error in the log in form in Django?
I'm trying to create a website with a log in and registration form in django, the registration works well, it saves the accounts in the database, but when I try to log in, it doesn't work at all, here's the code: views.py from django.shortcuts import render from .forms import UserForm from django.contrib.auth import authenticate, login, logout from django.urls import reverse from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect, HttpResponse # Create your views here. def index(request): return render(request, 'app1/index.html') @login_required def user_logout(request): logout(request) return HttpResponseRedirect(reverse('index')) def register(request): registered = False if request.method == "POST": user_form = UserForm(data=request.POST) if user_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() registered = True else: print(user_form.errors) else: user_form = UserForm() return render(request, 'app1/register.html',{'user_form':user_form, 'registered':registered}) def user_login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password = password) if user: if user.is_active: login(request, username) return HttpResponseRedirect(reverse('index')) else: return HttpResponse("Account Not Active") else: print("Someone tried to login and failed") print(f"Username: {username} and password {password}") return HttpResponse ("Invalid Login details supplied") else: return render(request, 'app1/login.html') models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class UserProfileInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) forms.py from django import forms from django.contrib.auth.models import User from … -
Creating a function to Specify Directory for Uploaded Images Location
I have created a function for my items model where there are images to be uploaded according to the name of the user and the title of the item. Now I am trying to add more images to this item and there is a foreign key with the image, but now instead of creating randomly uploading the new images to another folder, I want to upload these images to the same folder that was previously determined according to the same item. I have tried to alter the previous function but it returned with an error upload_design_to() takes 1 positional argument but 2 were given I assume because i didn't add self to the function but I don't know what to replace it with. The functions below will be more descriptive: Here is the models and the function where the images is uploaded to a location as per the users name and the title of the item: class Item(models.Model): def upload_design_to(self, filename): return f'{self.designer}/{self.title}/{filename}' designer = models.ForeignKey( User, on_delete=models.CASCADE) title = models.CharField(max_length=100) image = models.ImageField(blank=False, upload_to=upload_design_to) Now I have created a new an Image model to add more images to this item and want them to be uploaded to the very … -
JavaScript Event Listeners not running
I a currently taking CS50w and I am working on the project mail. Most of the code provided is distributed code and I have to add specific features to complete the assignment. I am currently trying to do the following specification "Send Mail: When a user submits the email composition form, add JavaScript code to actually send the email. You’ll likely want to make a POST request to /emails, passing in values for recipients, subject, and body. Once the email has been sent, load the user’s sent mailbox." In order to achieve that I have added an Eventhandler that will listen when the form is submitted and run the sent_email function. However, it is not working and automatically runs the load_mailbox('inbox') function. However, I don't want to remove that line because it was provided but I am at a loss on how to get it run my sent_email function. https://cs50.harvard.edu/web/2020/projects/3/mail/ document.addEventListener('DOMContentLoaded', function() { // Use buttons to toggle between views document.querySelector('#inbox').addEventListener('click', () => load_mailbox('inbox')); document.querySelector('#sent').addEventListener('click', () => load_mailbox('sent')); document.querySelector('#archived').addEventListener('click', () => load_mailbox('archive')); document.querySelector('#compose').addEventListener('click', compose_email); // Get data document.getElementById('compose-form').onsubmit = () => { sent_email(); } // By default, load the inbox load_mailbox('inbox'); }); async function sent_email(){ try { const response = … -
Checked radio button in Django form
I'm trying to render in template two radio button. But one of them must be checked initialy. My form.py: class ChangeAddressForm(forms.Form): CHOICES = [('current', ''), ('new', '')] address = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect) This is the way I'm writing in template to show them up: {{ address_form.address.0 }} {{ address_form.address.0 }} How can I have the first radio button checked, please? Thank you! -
Including an Item Context to a Post Model to activate if statement in Django
I am trying to add an Item to a list view, the UserPost list view has already a Post context. In my project, a user can add a post and add an item each is a different app with different models. So In my UserPost list view, I have my Posts looped related to a specific user related to it. What I am trying to do is check if this post.user has an item filtered by the same user and if it does exist a button show appears in the page linking to another page with this list of items related to this user. To be more descriptive I want to check for Item for the designer__post and link to this page which is {% url 'core:designer-posts' item.designer %} I hope this clears my question if there are any more clarifications required or code please let me know to add it. I tried to use make use of an Exists subquery [Django-doc] but I didn't succeed it perfecting it Here is the models.py class Post(models.Model): designer = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100) Here is the views.py class UserPostListView(ListView): model = Post template_name = "user_posts.html" context_object_name = 'posts' queryset = Post.objects.filter(admin_approved=True) … -
Adding a Field to AbstractUser results in an Operationalerror: no such column
I added this field to AbstractUser: class User(AbstractUser): listed = models.IntegerField(blank=True, null=True) Then I did python makemigrations python migrate And it says that no changes were detected, dont'really know why. I've just added a field Then I refreshed my localhost and I get the following error: no such column: auctions_user.listed And the error points to this line of code if request.user.is_authenticated: If i delete the field, everything goes back to normal, but i dont know why im getting this error -
How to display image from Django form ImageField input without models/database
I'm trying to display an image from a form ImageField on my template once the user has actioned the form. All the previous examples I have read about revolve around saving the image as a static file. Is this necessary? Is it possible to pass the image from the form through a view back onto a template without interaction with the database? I am not using any models and instead, my goal is to send the image to a restful API for classification and display it. ### forms.py from django import forms class FileForm(forms.Form): image = forms.ImageField(help_text="Upload image: ", required=False) ### home_template.py <h2>Tower Predictor</h2> <form method="post" enctype='multipart/form-data'> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> # Display image {% if image %} <img src="{{ image.url }}" alt="img"> {% endif %} ### views.py from django.shortcuts import render import requests from .forms import FileForm def home(request): if request.method == 'POST': form = FileForm(request.POST, request.FILES) if form.is_valid(): image = request.FILES['image'] form = FileForm() context = {'form': form, 'image': image} return render(request, 'web_ui/home.html', context) else: form = FileForm() return render(request, 'web_ui/home.html', {'form': form})