Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django admin.ModelAdmin autocomplete_fields on select fill an other field?
This is setup via de models.py and admin.py For simplicity, I got 3 models: Order, OrderRow (admin.TabularInline) and Product. The OrderRow has a price and Product also has a price. OrderRow is a admin.TabularInlinem and added (via inlines) to Order, and OrderRow has a relationship with Product. I can now add new Order, then add OrderRows and select a Product, works great. But what I want is that when the user selects a Product it also copies the price to the OrderRow (which can then overwritten by the user). Was gooien to the Django docs, but couldn't really find what I was looking for. Before I go built something myself that might be implemented already, what's would be the best way to do this? Any callback I can register or some hook I can use? Thanks! -
Implement search by two forms django
I want to implement search by two parameters form: home.html <form action="{% url 'search_results' %}" method="get"> <input name="q" type="text" placeholder="Search..."> <select name="q2" class="form-control" id="exampleFormControlSelect1"> <option>All locations</option> <option>RU</option> <option>Ukraine</option> <option>USA</option> </select> <button> Search </button> </form> When I click to "search" it's OK (I go to http://127.0.0.1:8001/search/?q=mos&q2=RU) But when I click "next", I receive http://127.0.0.1:8001/search/?city=2&q=mos&q2= but I need http://127.0.0.1:8001/search/?city=2&q=mos&q2=RU How can I fix this? <a href="/search?city={{ page_obj.next_page_number }}&q={{ query }}&q2= {{query}}">next</a> Full code: search_results.html <h1>Search Results</h1> <ul> {% for city in object_list %} <li> {{ city.name }}, {{ city.state }} </li> {% endfor %} </ul> <div class="pagination"> <span class="page-links"> {% if page_obj.has_previous %} <a href="/search?city={{ page_obj.previous_page_number }}&q={{ query }}">previous</a> {% endif %} <span class="page-current"> Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}. </span> {% if page_obj.has_next %} <a href="/search?city={{ page_obj.next_page_number }}&q={{ query }}&q2= {{query}}">next</a> {% endif %} </span> </div> views.py from django.shortcuts import render from django.views.generic import TemplateView, ListView from .models import City from django.db.models import Q from django.shortcuts import render, get_object_or_404 class HomePageView(ListView): model = City template_name = 'cities/home.html' paginate_by = 3 page_kwarg = 'city' def city_detail(request, pk): city = get_object_or_404(City, pk=pk) return render(request, 'cities/city_detail.html', {'city': city}) class SearchResultsView(ListView): model = City template_name = 'cities/search_results.html' paginate_by = 3 page_kwarg = 'city' … -
How can I stop Django server via command in cmd without click "CTRL + C"?
Im writing my desktop app on PySide2(its not important) for control Django project (run server and stop server on buttons). I realized only start server, but i cant add stop server, because stop server is click on buttons "CTRL + C" in cmd and i dont now how to interpret clicks on buttons into code or any answers for this question(( Here is an example for "RUN server" and I need some help for "STOP server" os.chdir(ui.lineEdit.text()) # Change directory os.system("python manage.py runserver") # Run server in this -
Django cannot delete custom field class; makemigrations throws AttributeError
Lead-up: I subclassed django.db.models.fields.CharField. Then used that custom field called myapp.models.QueryStringField in a model and made my migrations and migrated successfully. Then I changed my mind and decided to replace it with a normal CharField in my model, which I did (again with successfull migration). Problem: When I then deleted the QueryStringField class entirely from myapp.models and did makemigrations, it threw the following error (last lines shown here): File "C:\...\migrations\00....py", line 17, in Migration field=myapp.models.QueryStringField(max_length=255), AttributeError: module 'myapp.models' has no attribute 'QueryStringField' What can I do to fix this? I understand that this is technically correct, since the migration references a class that is not present, but surely this can be solved somehow. I am a little nervous about just deleting migration files. -
How can I give an error when someone edits there profile and changes the email to an email that already exists using django?
I want to give an error that an account with a email already exists, but it doesn't seem to work when a user edits there profile. Also, if the email isn't valid when submitting the form it it gives a value error: "The view accounts.views.edit_profile didn't return an HttpResponse object. It returned None instead." Here is the code: {% extends 'base.html' %} {% block head %} <link href="\static\accounts\css\forms.css" rel="stylesheet"> {% endblock %} {% block body %} <h3 style="text-align: center">Edit profile</h3> <form id="login-form" method="post"> {% csrf_token %} <input placeholder="Email" id="id_email" name="email" type="text" class="form-control" value="{{ user.email}}"> <input placeholder="First name" id="id_first_name" name="first_name" type="text" class="form-control" value="{{ user.first_name}} "> <input placeholder="Last name" id="id_last_name" name="last_name" type="text" class="form-control" value="{{ user.last_name}}"> {% if form.errors %} {% for field in form %} {% for error in field.errors %} <p class=" label label-danger"> <div style="text-align: center"> {{ error }} </div> </p> {% endfor %} {% endfor %} {% for error in form.non_field_errors %} <div class="alert alert-danger"> <strong>{{ error }}</strong> </div> {% endfor %} {% endif %} <div style="text-align:center;"> <button type="submit" class="btn btn-outline-dark centerbutton">Save edits</button> </div> </form> {% endblock %} -
Strange looking Swedish characters in generated PDF
I am building backend for a system in Django and I am generating PDF files using ReportLab. Please notice that the dots and circle above some letters are moved to the right for some reason. Why does this occur? Font is Times New Roman. -
Delete/destroy method in django
I have a generic api view that I would like to use for both put, delete (and eventually, update) of records for a certain model, but I am fairly confused about the best practice for deleting a record in Django. Should I use the built-in delete method, or do I define my own? Do I process it as a DELETE or 'destroy' method on a GenericAPIView. I don't want to allow just anyone to delete a record, so I need to first validate that they are the same user that created the record. By some accounts, it sounds like Django allows you to delete a record with just authentication and the id. If true, how do I disable this behavior? Thanks for any code or guidance on these various questions. frontend.js const deleteRow = (id) => { alert(id) fetch(`${SERVER_URL}/api/v1/requirements/related_files/${id}`, { method: 'DELETE', credentials: 'include', headers: { Accept: 'application/json, text/plain, */*', 'Content-Type': 'application/json', Authorization: `Token ${token}`, }, views.py class CommentsView(GenericAPIView): authentication_classes = (TokenAuthentication,) serializer_class = CommentsSerializer def post(self, request): request.data['user'] = request.user.id comment = CommentsSerializer(data=request.data) if comment.is_valid(): comment.save() return Response(comment.data, status=status.HTTP_201_CREATED) return Response(comment.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self,request): ???? what do I do here ???? -
Trying to write a custom template tag in Django that finds a phone number in text and converts it to a link
I want to convert this string tel:123-456-7890.1234 to a a link in html. The final output would be <a href="tel:1234567890,1234">123-456-7890 ext 1234</a> I'm not great with Regex and I'm REALLY close, but I need some help. I know that I'm not all the way there with the regex and output. How do I change what I have to make it work? import re @register.filter(name='phonify') @stringfilter def phonify(val): """ Pass the string 'tel:1234' to the filter and the right tel link is returned. """ # find every instance of 'tel' and then get the number after it for tel in re.findall(r'tel:(\d{3}\D{0,3}\d{3}\D{0,3}\d{4})\D*(\d*)', val): # format the tag for each instance of tel tag = '<a href="tel:{}">{}</a>'.format(tel, tel) # replace the tel instance with the new formatted html val = val.replace('tel:{}'.format(tel), tag) # return the new output to the template context return val I added the wagtail tag as I've seen other solutions for this in Wagtail and is something needed for Wagtail, so this might be helpful to others. -
Serializing a model as Json in Django and parse it with JavaScripts JSON.parse
I am afraid I don’t understand what "serializing" means. If someone can explain I’d be grateful. I am serializing a Django model in Json as explained in the Django Docs: data = serializers.serialize("json", MyModel.objects.all()) In my HTML/JS I access the data as recommended: {{ data|json_script:"data" }} var myData = JSON.parse([document.getElementById('data').textContent]); But instead of being an Object myData is a string. So I guess somehow I serialize twice or something. I found a solution, JSON.parse works as expected on my data now: data = json.loads(serializers.serialize("json", CoursePage.objects.child_of(self).live().public())) But I guess I still don’t understand the meaning of "serializing" properly. The Python docs say about json.loads(s): "Deserialize s (a str instance containing a JSON document). Why do I have to deserialize before JSON.parse works? The description for JSON.parse states: "The JSON.parse() method parses a JSON string"? Which I thought Djangos serializer would gave me in the first place. I am confused. -
Django bulk create and primary keys
So I have a model in my Django app (Unit, many to one to Property relationship) that is added in bulk via UI. The numbers of instances added could vary between 1 and 1000+ (but usually not much higher than that). Adding it in a loop using the model save() method seems inefficient (over a thousand separate db queries). So I learned about the bulk_create() method, but then learned that it doesn't populate the primary key field (AUTOFIELDS). So being new to Django, here are some options I can think of to implement this: Just bite the bullet and do it the slow way, using Model save(). Do bulk_create() to add these without a primary key, and just manage them in the app by their other fields (unit name, property). Implement a complex bulk_create method generating my own pks and using db locking. Approximate pseudocode below: break the list of units to create into digestible blocks for each block lock the unit table using SQL (to prevent pk from changing) get the current max pk of the table use an iterator to assign pks to unit instances use bulk_create to insert all the intances into db with assigned pks unlock … -
How to get an input value from template (datetimepicker input) and use it into the views.py in a function view
Hello guys I am startin with Django and I have a question about filter data. I want to export data from a model using import_export module with a button in the template ( no form in the template is in the listview template) : <a class="dropdown-item" href="{% url 'cmp:export' %}" role="button">Exportar Proveedores</a>` datepicker input: <div class="input-group date" data-target-input="nearest"> <input type="text" id="{{fecha_exportacion}}" name="fecha_exportar" class="form-control datetimepicker-input datepicker" data- target="#datetimepicker"/> <div class="input-group-append" data-target="#datetimepicker1" data- toggle="datetimepicker"> <div class="input-group-text"><i class="fa fa-calendar"></i> </div> </div> urls.py: path('proveedor_export',export,name='export') views.py def export(request): **date = request.GET.get('fecha_exportar')** user_selected_date = datetime.strptime(date, '%Y %m, %d') proveedor_resource = ProveedorResource() queryset = Proveedor.objects.filter(fc=user_selected_date) dataset = proveedor_resource.export(queryset) response = HttpResponse(dataset.csv, content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="proveedores.csv"' return response But I do not know how retrieve the datepicker input value and pass it to the views for the variable date. I tried with request.GET.get('fecha_exportar') but the result is None. -
Django/Python/MongoDB: How to update part of the web page/form
I have successfully coded and launched an internal site with Python+Django+MongoDB backend. Works great! But I would like to improve the user experience. There is a form where I pull up some data from MongoDB (by aggregation, counting etc.) and show it on a table (Table1). Now if a user clicks on a particular count on a table row I would like to send another HTTP request to add a section in the same page with more information (Table2). Currently I am sending query with extra parameter to the same "form" element which does bring the "more information" for that table row and create the Table2 but it also sends the same MongoDB query to re-create the first table (Table1) (basically rendering the whole page). This part I want to avoid... I do not want to re-do the first query and would like to fill only Table2 part of the webpage. I know it can be done in Angular - I worked very briefly with Angular where I was calling REST API to connect to MSSQL server and that brings the JSON result payload and then I was using Javascript/Angular to fill certain parts of the website as needed without … -
File uploader is not showing in Swagger Django Rest-Framwork
I have created Rest API using Django rest-framework, when I am trying to test in with Swagger, it is not supporting FileField. in place of file uploader, it is showing text field. Here What I did - models.py class Document(models.Model): IS_DELETED = ( (True, True), (False, False), ) project = models.ForeignKey(Project, null=False, blank=False, on_delete=models.CASCADE) document_file = models.FileField(upload_to=PROJECT_DOC_PATH, null=False, blank=False) is_deleted = models.BooleanField(choices=IS_DELETED, default=False) created_by = models.CharField(max_length=500, null=True, blank=True) created_on = models.DateTimeField(null=False, blank=False, default=timezone.now) updated_by = models.CharField(max_length=500, null=True, blank=True) updated_on = models.DateTimeField(null=True, blank=True) serializers.py class DocumentSerializer(serializers.ModelSerializer): class Meta: model = DocumentTbl fields = ('project','document_file') views.py @method_decorator(csrf_exempt, name='dispatch') class Document(generics.CreateAPIView): renderer_classes = (JSONRenderer,) parser_classes = (FormParser, MultiPartParser,) permission_classes = (permissions.AllowAny, IsAuthenticated) serializer_class = DocumentSerializer def post(self, request): try: serializer = DocumentSerializer(data=request.data) if serializer.is_valid(): serializer.create(serializer.validated_data) return Response({ messages.RESULT: messages.SUCCESS, messages.MESSAGE: messages.SUCCESSFULLY_DATA_SAVE, }, status=status.HTTP_200_OK) else: return Response({ messages.RESULT: messages.FAIL, messages.RESPONSE_DATA: serializer.errors, messages.MESSAGE: messages.INVALID_DATA, }, status=status.HTTP_400_BAD_REQUEST) except Exception as ex: return Response({ messages.RESULT: messages.FAIL, messages.MESSAGE: messages.SERVER_ERROR + ', due to {}'.format(str(ex)), }, status=status.HTTP_500_INTERNAL_SERVER_ERROR) urls.py urlpatterns = [ path('document/', Document.as_view(),name='document'), ] req.txt Python==3.x Django==2.2.5 django-cors-headers==3.1.0 django-rest-swagger==2.2.0 djangorestframework==3.10.3 djangorestframework-simplejwt==4.3.0 I have tried Django REST Framework + Django REST Swagger + ImageField but didn't solve my issue. Output -
Django: Is there a way to cancel an receiver triggering for a particular model signal?
I have a post_save signal receiver for a model in my domain. This receiver is triggered by many routines that run a save on that model (therefore I can't delete that receiver yet). I would like to cancel its triggering for a particular method that manipulates my model. Is that possible? I'm using Django 1.7 with Python 2.7 -
How to automatically update ForeignKeys to have ", on_delete=models.PROTECT"
I'm updating old code to the latest Django version. The ForeignKeys need ", on_delete=models.PROTECT". There are almost a hundred of them. How do I automatically add ", on_delete=models.PROTECT" to each one? -
How to change a value from in a django model while its foreign key?
Cart_Items , Cart , Order models .i want for my shopping website , that after a ordering a product , a value increased , but i cant access it . i tried to get it by pr=Products.objects.all() ci=Cart_Items.filter(product_id=pr) my models.py: order model: class Order(models.Model): user = models.ForeignKey(User,blank=True,null=True,on_delete=models.CASCADE) order_id = models.CharField( max_length=120,default="ABC",unique=True) cart = models.ForeignKey(Cart,on_delete=models.CASCADE) statu = models.CharField(max_length=120,choices=STATUS_CHOICES,default="Started") product model: class Products(models.Model): title = models.CharField(max_length=250) order_qty = models.IntegerField(default=0) Cart_Items model: class Cart_Items(models.Model): cart = models.ForeignKey('Cart',null=True,blank=True,on_delete=models.CASCADE) product_id = models.ForeignKey(Products,null=True,blank=True,on_delete=models.CASCADE) cart model : class Cart(models.Model): total = models.IntegerField(default=0) timestamp = models.DateTimeField(auto_now_add=True,auto_now=False) date = models.DateTimeField(auto_now_add=False,auto_now=True) isPaid = models.BooleanField(default=False) my views.py: def add(request): cart_items=Cart_Items.objects.all() for item in cart_items: print(item.product_id.order_qty) item.product_id.order_qty +=1 render(request,"home.html",{}) i want after ordering a product , order_qty , increased , how can i do that ? i must do it by Cart_items ? or there is another ways ? plz help. -
How to get related objects
I have 2 models : -products -review Every product have one or more revies/ Question : How i can get this related object's in view and pass him into template def product_detail(request, id, slug): product = get_object_or_404(Product, id=id, slug=slug, available=True) cart_product_form = CartAddProductForm() reviews = Review.objects.filter() template = 'shop/product/detail.html' return render_to_response(template, {'product': product, 'cart_product_form': cart_product_form, 'reviews': reviews}) class Review(models.Model): RATING_CHOICES = ( (1, '1'), (2, '2'), (3, '3'), (4, '4'), (5, '5'), ) product = models.ForeignKey(Product, on_delete=models.CASCADE, default=None) user = models.ForeignKey(User, on_delete=models.CASCADE, default=None) created = models.DateTimeField(auto_now_add=True, auto_now=False) text = models.TextField(max_length=500, blank=False) rating = models.IntegerField(choices=RATING_CHOICES, default=5) def __str__(self): return "%s" % self.user -
Is there a way to concatenate 2 model field names in the "list display" to display as one column in Django Admin?
In the Django Admin area, rather than have two separate columns for "first_name" and "last_name" to display, I'd like to concatenate those to create one column. I want to avoid creating a separate model field to get this done. One solution could be to return self, but that seems to not work either. The code below gets me "This site cannot be reached." admin.py from django.contrib import admin from .models import Agent class RealtorAdmin(admin.ModelAdmin): list_display = ('MLS_number', 'first_name' + 'last_name', 'email', 'phone', 'hire_Date') -
Exporting a field from another model, using foreign key
I've just set up the whole import-export thing and I just can't make it export a field from another model, using the foreign key. models.py from django.db import models from django.contrib.auth.models import User from datetime import date from .validators import validate_file_size # Create your models here. class CORMeserii(models.Model): CodCOR = models.CharField(max_length=25, primary_key=True, unique=True) MeserieCor = models.CharField(max_length=50, unique=True) def __str__(self): return str(self.CodCOR + " - " + self.MeserieCor) class Meta: verbose_name_plural = "CORuri" class Oferta(models.Model): solicitant = models.ForeignKey(User, on_delete=models.CASCADE) cor = models.ForeignKey(CORMeserii, on_delete=models.CASCADE) dataSolicitare = models.DateField(default=date.today) locuri = models.IntegerField() agentEconomic = models.CharField(max_length=50) adresa = models.CharField(max_length=150) dataExpirare = models.DateField() experientaSolicitata = models.CharField(max_length=200) studiiSolicitate = models.CharField(max_length=200) judet = models.CharField(max_length=20) localitate = models.CharField(max_length=25) telefon = models.CharField(max_length=12) emailContact = models.EmailField(max_length=40) rezolvata = models.BooleanField(default=False) def __str__(self): return str(self.cor) admin.py from django.contrib import admin from .models import Oferta, CORMeserii from import_export import resources from import_export.admin import ImportExportMixin, ImportExportModelAdmin import tablib # Register your models here. class CorImEx(resources.ModelResource): class Meta: model = CORMeserii class CorAdmin(ImportExportMixin, admin.ModelAdmin): list_display = ('CodCOR', 'MeserieCor') resource_class = CorImEx class CorImExAdmin(ImportExportModelAdmin): resource_class = CorImEx class OferteImEx(resources.ModelResource): class Meta: model = Oferta fields = ('id', 'solicitant', 'cor', 'oferta.cor.MeserieCor') class OfertaAdmin(ImportExportMixin, admin.ModelAdmin): list_display = ('id', 'solicitant', 'dataExpirare', 'dataSolicitare') resource_class = OferteImEx class OferteImExAdmin(ImportExportModelAdmin): resource_class = OferteImEx … -
Bootstrap Tabs preventing django model from saving
When I have the exact same code outside of a bootstrap tab, the model will save correctly, when I put the code into a tab, it stops saving the model. the post.request is showing all of the correct information in the correct format and when I loop through the request, I see all of the correct information. But it will not save the model's information to the database. I have tried only having one tab (with just the card information in it) and that doesn't work. I've tried having two tabs (and the first one, with different information, saves correctly) but the card information won't save. I've tried putting them in the same tag, and different ones, I've tried putting them all in the same form, and not in the same form. in the app/views.py settleCard = SettlementCard.objects.create( owner = client, cardNumber = request.POST.get('cardNumber'), nameOnCard = request.POST.get('cardName'), cardCvv = request.POST.get('cardCvv'), cardExpDate = request.POST.get('cardExpDate'), address1 = request.POST.get('address1'), address2 = request.POST.get('address2'), city = request.POST.get('city'), state = request.POST.get('state'), zipCode = request.POST.get('zipCode'), country = request.POST.get('country'), ) sellCardCount = SettlementCard.objects.filter(owner__pk=request.session.get('authId')) if sellCardCount == 0: settleCard.isPrimary = True settleCard.save() Not working HTML <div class="jumbotron"> <div class="container log-in" align="center"> <div class="tab" align="center"> <button class="tablinks" onclick="openTab(event, 'Card')">{% trans … -
How to delete existing image while uploading new image in django
Let say I have a model which has a profile pic image field.As a user I uploaded a profile pic.When I upload a new profile pic, old profile has to get deleted. How to handle this scenario in development and production stage -
How to check that Django model instance have preselected related data
Before Django 2.X I use this function for checking that ForeignKey and OneToOneField were prefetched to the Django model instance. def ensure_related(obj, field): field_obj = obj._meta.get_field(field) if hasattr(obj, field_obj.get_cache_name()): return True return False So for example In [1]: permission = Permission.objects.last() SELECT "auth_permission"."id", "auth_permission"."name", "auth_permission"."content_type_id", "auth_permission"."codename" FROM "auth_permission" INNER JOIN "django_content_type" ON ("auth_permission"."content_type_id" = "django_content_type"."id") ORDER BY "django_content_type"."app_label" DESC, "django_content_type"."model" DESC, "auth_permission"."codename" DESC LIMIT 1 In [2]: ensure_related(permission, 'content_type') Out[2]: False In [3]: permission = Permission.objects.prefetch_related('content_type').last() SELECT "auth_permission"."id", "auth_permission"."name", "auth_permission"."content_type_id", "auth_permission"."codename" FROM "auth_permission" INNER JOIN "django_content_type" ON ("auth_permission"."content_type_id" = "django_content_type"."id") ORDER BY "django_content_type"."app_label" DESC, "django_content_type"."model" DESC, "auth_permission"."codename" DESC LIMIT 1 SELECT "django_content_type"."id", "django_content_type"."app_label", "django_content_type"."model" FROM "django_content_type" WHERE "django_content_type"."id" IN (1) In [3]: ensure_related(permission, 'content_type') Out[4]: True But since Django 2.X this method always return True. My questions is: how since Django 2.X implement this check? -
How to retrieve a list of all available schedulers (django celery)?
Hi i want to create tasks from a fontend application. I want to retrieve a list of possible schedulers. By the celery documentation: schedule The frequency of execution. This can be the number of seconds as an integer, a timedelta, or a crontab. You can also define your own custom schedule types, by extending the interface of schedule. So i want a list of the default schedules (integer, timedelta, crontab) plus the user created ones that extends the schedule interfase. -
How to send an error message from the server to the client using django and print it to the console?
I have a server request that is supposed to find a file, if it doesn't find that file, in need to print in the js console a custom message saying "I couldn't find file x". I have tried raising exceptions, raising Http errors, sending custom requests.... But I have no idea how to send both an error (e.g 400, 404...) and a custom message associated with that error. The purpose of this is, when the XMLHttpRequest() object gets a response, if the status isn't 200, that;s when the error ought to be printed. I have no interest as to whether this is good practice or not, I just need to be able to do it somehow. -
Upload Multiple Images: Can't upload multiple images
I have been trying to code a Multi Upload for Images, my code only uploads 1 image even though more than 1 is selected, I don´t understand why request.FILES.getlist('picture') doesn´t work. I basically trying to use the code that appear in the Django documentation. models.py class Images(models.Model): session = models.CharField(max_length=50, blank=True) picture = models.ImageField(upload_to='photoadmin/pictures') created_date = models.DateTimeField(default=timezone.now) forms.py class UploadImages(forms.ModelForm): class Meta: model = Images fields = ('picture',) widgets = {'picture': forms.ClearableFileInput( attrs={'multiple': True})} views.py class Upload(FormView): form_class = UploadImages template_name = 'photoadmin/upload.html' success_url = 'photoadmin/' def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) files = request.FILES.getlist('picture') if form.is_valid(): for f in files: form.save() return render(request, 'photoadmin/index.html') else: return self.form_invalid(form) html {% extends 'base.html' %} {% block content %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Upload</button> </form> <p><a href="{% url 'index' %}">Return to home</a></p> {% endblock %} This code only uploads one image. thanks for your help.