Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Datatable integration with Django
I am new in web development so, I do not have any idea about how to use dataTable in a Django project. I have json data and I want to display the data into a table using DataTable Created a Django project and Django set up and all is working fine. I look into some source but, couldn't find any blog or other website to integrating DataTable for beginners. I would be a great if any help to find the same for beginners. -
how to convert string into django ORM query
I defined a string and and adding values in while loop and creates Django query. When i'm going to save in database it says 'str' object has no attribute 'save' caste = request.POST.getlist("caste") caste_name = ['GOPENS','GSCS','GSTS','GVJS','GNT1S','GNT2S','GNT3S','GOBCS','LOPENS','LSCS','LSTS','LVJS','LNT1S','LNT2S','LNT3S','LOBCS'] print(len(caste)) cast_counter=0 cut_off = "cut_off(" for i in range(len(Courses)): j=0 while(cast_counter<len(caste)): cut_off += caste_name[j] +"="+ caste[cast_counter] if(j!=15): cut_off += "," if(j == 0): cast_counter += 1 j += 1 continue if(j%15 == 0): cut_off += ")" cast_counter += 1 break j += 1 cast_counter += 1 cut_offf=cut_off cut_offf.save() OUTPUT of cut_of string: cut_off(GOPENS=1,GSCS=2,GSTS=3,GVJS=4,GNT1S=5,GNT2S=6,GNT3S=7,GOBCS=8,LOPENS=9,LSCS=10,LSTS=11,LVJS=12,LNT1S=13,LNT2S=14,LNT3S=15,LOBCS=16) and i want to store it database That's why I written like this cut_offf=cut_off cut_offf.save() but it says 'str' object has no attribute 'save' so any other method?? -
Permission to edit exact instance's subclesses in Django admin page
I need to show user only instances of subclassconnected to exact class instance/ I am learning Django by creating a website for university. Website wiil be used for checking homework. I want to give monitirs of every group in university acces to admin page in order to add/adit/delete subjects they learn and tasks for every subject. I simply don't know where to start so I need your advice. views.py class Group(models.Model): group_name = models.CharField(max_length=20) class Subject(models.Model): group = models.ForeignKey(Group, on_delete=models.CASCADE) subject_name = models.CharField(max_length=200) class Task(models.Model): subject = models.ForeignKey(Subject, on_delete=models.CASCADE) task_name = models.CharField(max_length=200) About expected result. I need that every group monitor could see and edit only subjects of his Group instance, while I am able to edit all of them. -
Problems with Django Url Patterns
I am having some difficulty with Django url patterns. I am relatively new to Django. So, I am trying to get used to best practices when it comes to building apps using Django. Now, here is my problem. Often time I did notice when two of my urls have kind of similarity, Django often confuses them and I have to make one of the url extremely distinct so that it can work. Why is that ? Even though I have explicitly mentioned as to which url a specific form should be posted. Here is a bug that I am facing url(r'book/collection/read/$', ReadBookList.as_view(), name='read_book_list'), url(r'book/(?P<pk>\w+)/$', BookDetail.as_view(), name='book_detail'), <li class="nav-item active"> <a class="nav-link" href="{% url 'library:read_book_list' %}"> <i class="fa fa-check-circle"></i> <span>Books You Read</span></a> </li> Now, when I navigate to that link, it keeps going to detailview instead of the other url. What could I be doing wrong ? And what is a better way to work with url patterns so that Django doesn't confuse mapping to a wrong url. E.g list of urls in my library app # Book urlpatterns url(r'book/$', BookList.as_view(), name='book_list'), url(r'book/add/$', BookCreate.as_view(), name='book_create'), url(r'book/(?P<pk>\w+)/$', BookDetail.as_view(), name='book_detail'), url(r'book/(?P<pk>\w+)/edit/$', BookUpdate.as_view(), name='book_update'), url(r'book/(?P<pk>\w+)/delete/$',BookDelete.as_view(), name='book_delete'), url(r'book/collection/read/$', ReadBookList.as_view(), name='read_book_list'), url(r'book/mark/read/$', book_mark_read, name='mark_read'), url(r'book/search/results/$',BookSearch.as_view(), name='book_search'), … -
How to use PUT to update something in Vue using Django REST framework
I am new to Vue but have experience with Django. I am using this boilerplate from Github: https://github.com/gtalarico/django-vue-template I really like the structure of that boilerplate because it is not overwelming at all and not a lot of code is written to succesfully interact with the back-end API of Django. It has GET, POST & DELETE already pre-installed and connected to Django REST. So far so good. However I try to add a PUT method to it so I can update models. I try to follow the same structure but I can't get it to work. My productService.js: import api from '@/services/api' export default { fetchProducts() { return api.get(`products/`) .then(response => response.data) }, postProduct(payload) { return api.post(`products/`, payload) .then(response => response.data) }, deleteProduct(proId) { return api.delete(`products/${proId}`) .then(response => response.data) }, updateProduct(proId) { return api.put(`products/${proId}`) .then(response => response.data) } } The updateProduct is the new code I added. Then in store --> products.js: const actions = { getProducts ({ commit }) { productService.fetchProducts() .then(products => { commit('setProducts', products) }) }, addProduct({ commit }, product) { productService.postProduct(product) .then(() => { commit('addProduct', product) }) }, deleteProduct( { commit }, proId) { productService.deleteProduct(proId) commit('deleteProduct', proId) }, updateProduct( { commit }, proId) { productService.updateProduct(proId) commit('updateProduct', … -
jquery code from base.html not working in other pages
I am working on a django application. The application contains multiple html template pages. I used a base.html page which will contain all the common code that I want in other pages. for example, the base template holds the code for a navbar that is common for all the pages in the website. base.html {% load staticfiles %} <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <!-- bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> <!-- fonts --> <link href="https://fonts.googleapis.com/css?family=Anton|Open+Sans&display=swap" rel="stylesheet"> <!-- base.css --> <link rel="stylesheet" href="{% static 'css/base.css' %}"> <!-- base.js --> <script src="{% static 'js/base.js' %}"></script> <title>{% block title %}base{% endblock %}</title> {% block header %}{% endblock %} </head> <body> {% block content %} {% endblock content %} <!-- navbar --> <nav class="navbar fixed-top navbar-expand-lg"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse justify-content-center" id="navbarSupportedContent"> <ul class="navbar-nav"> <li class="nav-item active"> <a class="nav-link hover_effect" href="{% url 'home' %}">Home</a> </li> <li class="nav-item active"> <a class="nav-link hover_effect" href="{% url 'about' %}">About Us</a> </li> <li class="nav-item"> <a class="nav-link hover_effect" href="{% url 'contact_us' %}">Contact Us</a> </li> </ul> </div> </nav> </body> </html> base.js $(document).ready(function() { $('.nav-link').css('color', … -
Is the django documentation wrong here?
https://docs.djangoproject.com/en/2.2/ref/models/expressions/#aggregate-expressions It seems to mention aggregate functions but then use annotations as an example, am I going crazy or is there something I'm missing here? I'm having a hell of time trying to figure it out! -
Serializers vs views to retrieve object by foreign key field
I'd like to allow users to perform POST request to create a blog post, and to use the topic name instead of the topic id as a foreign key. A minimal model might look as follows. models.py class Topic(models.Model): name = models.CharField(max_length=30, unique=True) description = models.CharField(max_length=100) class Post(models.Model): name = models.CharField(max_length=30) topic = models.ForeignKey(Topic, on_delete=models.PROTECT) created_on = models.DateTimeField(blank=True, auto_now_add=True, editable=False) Now there are 2 possible approaches that I've considered: 1) Keep the views simple. views.py class PostList(ListCreateAPIView): queryset = Topic.objects.all() serializer_class = PostSerializer serializers.py class PostSerializer(serializers.ModelSerializer): topic_name = serializers.CharField() class Meta: model = Topic fields = ('name', 'topic_name', 'created_on') read_only_fields = ('created_on',) def validate_topic_name(self, value): """Verify that the topic exists.""" if not Topic.objects.filter(name=value).exists(): raise serializers.ValidationError("Specified Topic Name does not exist!") else: return value def create(self, validated_data): """Create a Post.""" topic_name = validated_data.pop('topic_name', None) topic = Topic.objects.get(name=topic_name) return Post.objects.create(topic=topic, **validated_data) 2) Keep the serializers simple. views.py class PostList(ListCreateAPIView): queryset = Post.objects.all() def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) if not serializer.is_valid(): return Response( serializer.errors, status=status.HTTP_400_BAD_REQUEST) topic = get_object_or_404(Topic, name=serializer.data['topic_name']) post = Post.objects.create( name=serializer.data['name'], topic=topic) return Response({'name': serializer.data['name'], 'description': serializer.data['topic_name']}, status=status.HTTP_201_CREATED) serializers.py class PostSerializer(serializers.ModelSerializer): topic_name = serializers.CharField() class Meta: model = Topic fields = ('name', 'topic_name', 'created_on') read_only_fields = ('created_on',) My … -
related_name argument required
I've recieved the following error and I'm not sure how to handle this in my model. HINT: Add or change a related_name argument to the definition for 'UserCart.state_tax' or 'UserCart.fed_tax'. userorders.UserCart.state_tax: (fields.E304) Reverse accessor for 'UserCart.state_tax' clashes with reverse accessor for 'UserCart.other_tax'. models.py class UserCart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=None) state_tax = models.ForeignKey(Tax, on_delete=models.SET_NULL, null=True) fed_tax = models.ForeignKey(Tax, on_delete=models.SET_NULL, null=True) -
Looking for a good chat in Django
I'm looking for a good chat in Django. I would like to get the following features: old-skool smilies with images (I really don't like unicode emojis that look different on different devices) channels ... that's about it. -
Data not storing in database for choice field for UserRegsitrationForm django
I have extended the UserCreationForm of Django to add extra fields : Email and Choice field. Now when I am filling those details in the registration form and submitting it. Only the email is stored in the database and not the choice field(i.e status in the code). However when I am viewing the fields of my form in the console the choice field is showing. But when I am accessing the attribute using the django shell I am getting an error from django.contrib.auth.models import User users = User.objects.all() users[6].email Output : masterhimanshupoddar@gmail.com # success users[6].status Error: AttributeError Traceback (most recent call last) <ipython-input-7-c9d2701fa919> in <module>() ----> 1 users[6].status AttributeError: 'User' object has no attribute 'status' Here is my forms.py from django.contrib.auth.forms import UserCreationForm from django import forms from django.contrib.auth.models import User class SignUpForm(UserCreationForm): STATUS_CHOICES = ( (1, ("CEO")), (2, ("Dev Manager")), (3, ("Testing Manager")), (4, ("Developer")), (5, ("Test Engineer")) ) email = forms.EmailField(required=True, label='Email', error_messages={'exists': 'Oops'}) status = forms.ChoiceField(choices = STATUS_CHOICES, label="Designation", initial='Developer', widget=forms.Select(), required=True) class Meta: model = User fields = ("username", "email", "password1", "password2", "status") def save(self, commit=True): user = super(UserCreateForm, self).save(commit=False) user = super(UserCreateForm, self).save(commit=False) user.email = self.cleaned_data["email"] user.status = self.cleaned_data["status"] if commit: user.save() return user Why … -
Django check username at sign-up against a regex of allowed usernames
i would like to check the username upon signup against a regex (which is currently not a regex, see code below). I don't want a new user to use usernames like "admin, supporter, staff" etc. I just try'd to write myself a validator for this but sadly i didn't work with regex or a validation like this before as i'm quite new to coding, maybe smb. can help me out on this: models.py class User(AbstractBaseUser): ... user = models.CharField(verbose_name='Username', max_length=20, unique=True, validators=username_filter) ... validators.py from django.core.exceptions import ValidationError from django.core.validators import RegexValidator def username_filter(value): invalid_username_regex = RegexValidator( regex=("admin", "staff", "supporter", "support") ), if value in invalid_username_regex: raise ValidationError(u'Its not possible to signup with a username like this, please try a different one') but currently i get the following error: user = models.CharField(verbose_name='Username', max_length=15, unique=True, validators=username_filter) File "/venv/lib/python3.7/site-packages/django/db/models/fields/init.py", line 1039, in init app | super().init(*args, **kwargs) File "/venv/lib/python3.7/site-packages/django/db/models/fields/init.py", line 171, in init app | self._validators = list(validators) # Store for deconstruction later TypeError: 'function' object is not iterable thanks in advance -
Allow maximum number of choices of m2m field in viewset
I want to allow users pick maximum 2 genres. I tried add in models.py, but there was an error. Now, I am thinking of adding code to check the number of picked genres in views.py, or may be in Serializer if it's possible. class Story(models.Model): genre = models.ManyToManyField(Genre) class StorySerializer(serializers.ModelSerializer): genre = GenreSerializer(read_only=True, many=True) ... class StoryView(viewsets.ModelViewSet): queryset = Story.objects.all() serializer_class = StorySerializer def perform_create(self, serializer): serializer.save(author=self.request.user) -
Posting GeoJSON with DRF causes "function st_geomfromewkb(bytea) does not exist"
I set up a Django Rest Framework (DRF) API using django-rest-framework-gis. It works fine to post data from the API's interface, as long as I keep the geometry field to null. But as soon as I try including a GeoJSON in the geometry field (as below)... { "gmlid": "this is a test from DRF interface", "name": "", "envelope": { "type": "Point", "coordinates": [ 5.000000, 23.000000 ] }, "creation_date": null, "xml_source": "" } ...I get the following error: ProgrammingError at /en/api/cityobject/ function st_geomfromewkb(bytea) does not exist LINE 1: ...atest_from_browser', '', '', '', '', ST_Transform(ST_GeomFro... ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. Request Method: POST Request URL: http://127.0.0.1:8000/en/api/cityobject/ Django Version: 2.2 Exception Type: ProgrammingError Exception Value: function st_geomfromewkb(bytea) does not exist LINE 1: ...atest_from_browser', '', '', '', '', ST_Transform(ST_GeomFro... ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. Exception Location: /home/me/dj-workspace/my-venv/lib/python3.6/site-packages/django/db/backends/utils.py in _execute, line 84 Python Executable: /home/me/dj-workspace/my-venv/bin/python Python Version: 3.6.8 Python Path: ['/home/me/dj-workspace/myapp', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/home/me/dj-workspace/my-venv/lib/python3.6/site-packages'] Server time: Sat, 5 Oct 2019 07:49:35 +0000 What may be causing this error? My code looks like this: models.py class Cityobject(models.Model): … -
In Django Admin drop-down list action, is there any function to go to page of other app in the same project when i cilick on GO button
`python def create_estimator_observation(ModelAdmin, request, queryset): url = reverse('admin:estimator_estimator_change', args=[new_estimator.id]) try: link = '%s' % (url, new_estimator.id) except AttributeError: link = 'No Such Estimator' import ipdb; ipdb.set_trace() return format_html(url) ` This code is used to create the create estimator action, and at the stage, i want to go to the change estimator page when i click go. When i click 'go', page url='127.0.0.1:8000/admin/observation/observation/' I'd like to show the page, page url='127.0.0.1:8000/admin/estimator/estimator/f55556bf-1f1b-448b-bf4e-4f6a237f7d58/change/' -
I'm getting 'TypeError' in whenever I edit any entry through forms in Django
Every time I try to edit any entry through a form, it gives Type Error. I have only one model that is BlogPost models.py from django.db import models # Create your models here. class BlogPost(models.Model): """ A title and text for a blog entry""" title = models.CharField(max_length=200) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """ return a string representation of the model.""" return self.title This is views file views.py from django.shortcuts import render, redirect from .models import BlogPost from .forms import BlogPostForm def edit_post(request, blog_id): """ edit an entry""" title = BlogPost.objects.get(id=blog_id) post = title.text if request.method != 'POST': form = BlogPostForm(instance=entry) else: form = BlogPostForm(instance=entry, data=request.POST) if form.is_valid(): form.save() return redirect('blogs:index', blog_id=title.id) context = {'title': title, 'post': post, 'form': form} return render(request, 'blogs/edit_post.html', context) This is edit post file edit_post.html {extends 'blogs/base.html'} {% block content %} <p>Edit Form:</p> <p>{{ title }}:</p> <form action="{% url 'blogs:edit_post' title.id %}" method="POST"> {% csrf_token %} {{ form.as_p }} <button name="submit">Save changes</button> </form> {% endblock content %} base.html <p> <a href="{% url 'blogs:index' %}">Home</a> - <a href="{% url 'blogs:new_post' %}">Add Post</a> </p> <br> {% block content %}{% endblock content %} This is index/home page file index.html {% extends 'blogs/base.html' %} {% block content … -
i'm having trouble with my django code while i deleting the data from the table form on click of the delete button
But it will showing an error which is (TypeError at /deletecase deletecase() missing 1 required positional argument: 'pk') please help me out this Here is the url link of the page: ```path("deletecase",views.deletecase,name="deletecase")``` THE VIEW FILE FUNCTION: ``` def policcasesdetails(request): cases=Case.objects.all() return render(request,'policeside/policcasesdetails.html',{'cases':cases}) def deletecase(request,pk): obj=Case.objects.get(id=pk) obj.delete() return HttpResponse("Data is Deleted") ``` AND THE FORM IS:- <div class="container"> <div class="content-middle"> <div class="col-md-12 sed-in"> <h3>Cases Details</h3> {% for i in cases %} <div class="col-md-4 sed-top"> <div class="top-sed"> <!-- <img src="{{ i.image.url }}" class="img-responsive" alt=""> --> <!-- <label><span>{{ i.oname }}</span></label> --> </div> <h4> Case Number- <a>{{i.casenumber}}</a> </h4> <p>Case Name- <a href="#">{{i.casename}}</a></p> <p>Case Result- <a href="">{{ i.caseresult }}</a></p> <p>Case Conclusion- <a href="">{{ i.casecoclusion }}</a></p> <p><a href="{% url 'deletecase' i.id %}"> <button type="submit" value="delete" class="btn btn- danger">Delete</button> </p> </div> {% endfor %} <div class="clearfix"> </div> </div> <div class="clearfix"> </div> </div> </div> -
Unable to download a pdf file in a django app?
I've made a django app and there is a file I want user would be able to download on clicking a button. But I'm unabale to download it even though everything seems to be correct. Here's a section my index.html <h3>Download your file here-</h3> <button>Download <a href="/my_website/my_webapp/static/my_webapp/pictures/bill/bill.pdf" download='bill'></a> </button> On clicking the button the file doesn't get downloaded. Can anyone help? -
Applying union() on same model is not recognising ordering using GenericRelation
I have an Article model like this from django.contrib.contenttypes.fields import GenericRelation from django.db import models from hitcount.models import HitCountMixin, HitCount class Article(models.Model): title = models.CharField(max_length=250) hit_count_generic = GenericRelation( HitCount, object_id_field='object_pk', related_query_name='hit_count_generic_relation') when I do Article.objects.order_by('hit_count_generic__hits'), I am getting results.but when I do articles_by_id = Article.objects.filter(id__in=ids).annotate(qs_order=models.Value(0, models.IntegerField())) articles_by_name = Article.objects.filter(title__icontains='sports').annotate(qs_order=models.Value(1, models.IntegerField())) articles = articles_by_id.union(articles_by_name).order_by('qs_order', 'hit_count_generic__hits') getting error ORDER BY term does not match any column in the result set How can i achieve union like this? I had to use union instead of AND and OR because i need to preserve order. ie; articles_by_id should come first and articles_by_name should come second. -
permission denied error while running collectstatic command
I'm deploying my django project on digitalocean.While it runs correctly in my development machine but on running on server, it's not showing static files. not showing static files my settings for static files is, STATIC_URL = '/static/' STATIC_ROOT='/home/gagan_sapora/myprojectdir/saporawebapp/static/' for troubleshooting, i run collectstatic command but it's showing permission denied error. -
How to add urls of two apps in urls.py single project in django?
enter image description here Project1 contains app1 amd app1.. but i dont understand how to put urls of both apps App1 views ----------->>urls at project1 level App2 views------------->>urls at project1 level -
how to filter with multiple values from checkboxes in Django?
I have this Patient model with fields: company, sex, is_alive... In the patient search page, I have checkboxes for these fields. So if users want to search all male alive patient in a company ... they will tick on the checkbox. Then in the backend, in views.py, I collect values of checkboxes and put into a list called "value_list". Next, I do the query search like this: patient_list = Patient.objects.all() if "abc" in value_list: company = Company.objects.get(name="abc") patient_list = patient_list.filter(Q(company=company)) if "alive" in value_list: company = Company.objects.get(name="alive") patient_list = patient_list.filter(Q(company=company)) if "male" in value_list: company = Company.objects.get(name="male") patient_list = patient_list.filter(Q(company=company)) My question is if this way of filtering is efficient and good practice. Please advise. Thank you. -
How to assign objects to groups in django
I need to be able to create a Memo and specify which group(s) can view this specific Memo. One thing I want to avoid doing is using GenericForeignKeys as I have read a lot about how they are costly during database look-ups, etc. I also need to set notifications for this Memo so that a user can mark as read, unread, etc. The notifications will be handled by Django-notifications so that is not and issue unless the answer to the next question can knock out both of these tasks in one swipe.. My question is: how do I create a Memo model with a CharField of group choices and use the user selected choice to assign which group can view this Memo? Somewhat linking objects to groups. I see this post and it seems that it may do what I want but the questions would then be: I am assuming Group in groups = models.ForeignKey(Group, on_delete=models.CASCADE) is the standard Group model in Django being referenced here. How do I add the ability for the user to select which group the Memo applies to? -
How to erase previously set one-time default value
In my django app, I had to set a one-time default value for one of the fields when I tried to migrate. When I did this, however, I accidentally set a wrong value. Ever since then, the same error pops up when I try to migrate: ValueError: invalid literal for int() with base 10: '123e4567-e89b-12d3-a456-426655440000' This is despite the fact that I rectified the issue in my code - it seems like this issue is stuck forever. Anything I can do to fix this? -
Invalid URL '': No schema supplied. Perhaps you meant http://? - Django
I'm a beginner in Django. I'm making a data scraping project, I've made this code but facing problem to download the CSV file. I used The function 'Download' in the file but not getting the desired result. Instead, I'm getting this error Invalid URL '': No schema supplied. Perhaps you meant http://? Here is my code 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"}) 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([name.text, price.text,image['src']]) 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} if down: return response else: dec = {} return render(request, 'index.html',dec) When i remove this "if down:" it downloads my csv file correctly, when i keep the if condition it throws error : Invalid URL '': No schema supplied. Perhaps you meant http://? index.html <div class="container"> <div class="row justify-content-md-center"> <div class="col-md-4"> <form method="POST" action="">{% csrf_token %} <h1 class="mb-3 display-4">Amazone Scraper</h1> <input type="text" id="url" name="url" class="form-control" placeholder="URL" required …