Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Adding Tables In Model AFTER --fake-initial
I had some issues with my database in Django 1.9 where I was getting that ugly relation error no matter what I tried so I had to remove all the tables and start fresh, but I had to hold onto one of the tables. I deleted the migration folders, I deleted the apps entry in django_migrations and all the tables in the DB manually (other than the 1 table I needed to keep). I then ran migrate --fake-initial with the only entry in my models.py being the table I mentioned, and it worked fine. The issue now is when I add existing entries in my models.py and try to migrate, It tries to add the existing table that I faked, and I get a "Error Table Already Exists". Anyone know how I can get around this? -
Multiple image uploads in Django admin?
I have two models(Album, Photo) where they are in 1:N relation. But I have tons of photos, so I want to upload multiple images at a time. I want to implement this in Django admin site. As you can see here, I implemented it with admin.StackedInline but this is not what I want... When choosing files, multiple choosing files should be enabled. I already find it in Google with Django multiple file upload etc, but those are so approximate and summarized... Need your help. Thanks. -
Django - Filtering query by difference of two DateTimeFields
I have a model with two DateTimeFields: starttime = models.DateTimeField(db_column='starttime', blank=False, null=False) endtime = models.DateTimeField(db_column='endtime', blank=False, null=False) In my view I would like to filter this by the difference between them. For example if the difference between start and end is more than 45 seconds. I tried this as a guess: .filter((models.F('endtime') - models.F('starttime')).seconds > 45)\ But that didn't work. Is there a way to do this with the Django ORM? -
slow server response time Amazon EC2
I recently used the pagespeed insight tool because my website was loading slowly and one of the problems was "Reduce server response time. In our test, your server responded in 2.8 seconds." I read through their suggestions, but was not able to reduce the server response time. I am hosting a django web application on my ec2 instance. I don't think there's any issue with my apache configuration, which I put below: <VirtualHost *:80> Alias /static /home/ubuntu/project/static_root_content <Directory /home/ubuntu/project/static_root_content> Require all granted </Directory> <Directory /home/ubuntu/project/fantasy> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess project python-path=/home/ubuntu/project:/home$ WSGIProcessGroup project WSGIScriptAlias / /home/ubuntu/project/fantasy/wsgi.py If I can provide any other additional details, please tell me. Any help is appreciated! -
Why is Django reporting stale value for an instance's attribute?
I have a Django project with many applications and models.. One of my model looks something like this: from caching.base import CachingManager, CachingMixin from mptt.models import MPTTModel, TreeForeignKey class MyClass(CachingMixin, MPTTModel): id = models.BigIntegerField(default=make_id, primary_key=True) parent = TreeForeignKey('self', default=None, null=True, blank=True, related_name="MyClass_parent", ) status = models.CharField(max_length=254, null=False, blank=False) objects = CachingManager() Note that I'm using Django Cache Machine to do DB-query caching. At one point in my program, I have an instance of MyClass named k2. k2.status is initially set to "CREATED" but then changed to "OPEN". But oddly, when I examine its value, it still shows "CREATED". So this code: # Do something here to change k2.status from "CREATED" to "OPEN" logger.info("Checking k2 (%s). DjangoCacheMachine says its %s. DB says %s" % \ (k2.pk, k2.status, MyClass.objects.get(pk=k2.pk).status)) Yields this output: Checking k2 (63083895085066269). DjangoCacheMachine says its CREATED. DB says OPEN Why am I seeing two conflicting values for status in that output?? I suspected that this was a bug in Django Cache Machine, so I removed it completely from this model. But I still observed the same behavior. Might this be a bug in mptt.models? -
Delete Album from table by url - django
I added to the list of my albums - a press button that delete the currnt object mention by "pk"\"id". I show you the code: {% for album in albums %} <a href="{% url 'index' %}{{ album.id }}">{{ album.name }}</a> <form action="{{ album.pk }}" method="post"> {% csrf_token %} <button type="submit">push</button> </form> <br /> {% endfor %} and url.py: url(r'(?P<pk>[0-9])', views.delete.as_view()), and, the Delete view: class delete(DeleteView): model = Album success_url = reverse_lazy('index') when i press the button, its really delete what i need from the table. But i tried to send the id by artificial - just wrote it myself in the url line, and the same action didnt do the same behavior. it sent me to an error page. why those are two differents behaviors in two same actions? -
How can i write unit test for huey scheduled task?
Im writing unit test for schedule task, but the task_id return always None update_task_id = update_delivery_minutes_change.schedule( args=(instance.id,), delay=(60 * 30) ) update_task_id.task.task_id -> None How can i mock or emulate huey for create a test case? -
Django permissions to view
I want to restrict access to certain views based on the current User's email address. Are Permissions the way to go here? My thought is "no" because, as far as I understand, permissions are for model objects. -
django haystack KeyError when using custom search form
So I am trying to use a custom search form so that I could search by several model field separately. (like, search a equipment by asset #, by department, etc.) I have the following codes for now: SEARCH_CHOCIES = (('Asset #','Asset #'), ('Calibrated by','Calibrated by'), ('Department','Department'), ('Description','Description'), ('Expiring soon','Expiring soon'), ('Flagged','Flagged'), ('Manufacturer','Manufacturer'), ('Model','Model'), ('Serial #','Serial #'), ('Test','Test')) class MultipleSearchForm(SearchForm): search_type = forms.ChoiceField(required = False, choices = SEARCH_CHOCIES) search_content = forms.CharField(required = False) def search(self): sqs = super(MultipleSearchForm, self).search() if not self.is_valid(): return self.no_query_found() choice = self.cleaned_data['search_type'] content = self.cleaned_data['search_content'] if choice: if content: if choice == 'Asset #': sqs = sqs.filter(self.cleaned_date['asset_number'] == content) return sqs urls.py: url(r'^search/', search_view_factory(view_class = SearchView, form_class = MultipleSearchForm), name='haystack_search'), Now it only handles searching when you choose to search by asset #. Right I have these following questions: when I tried to use this by going to http://127.0.0.1:8000/calbase/search/ and search by asset #, I got the following error message: AttributeError at /calbase/search/ 'MultipleSearchForm' object has no attribute 'cleaned_date' Environment: Request Method: GET Request URL: http://127.0.0.1:8000/calbase/search/?q=&search_type=Asset+%23&search_content=S2 Django Version: 1.10 Python Version: 3.5.2 Installed Applications: ['calbase.apps.CalbaseConfig', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'haystack', 'whoosh', 'carton', 'adminplus', 'django.contrib.admin.apps.SimpleAdminConfig', 'nested_inline'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: … -
download django 1.10 to python 3.5
How do I download django for python 3.5? When I run my virtual environment and type: pip install Django I get: Requirement already satisfied (use --upgrade to upgrade): django in /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages I noticed the problem when using PyCharm. PyCharm shows Django installed in Python 2.7, but not in 3.5. How do I pip install django into 3.5? My main python package is 2.7. My work uses 2.7, and is migrating towards 3.5. So I'll need both, and would like to keep 2.7 as the default. -
Django testing wsgi request
Im wirting a test suite for testing Django encoding but for some reason the GET request does not encode the request properly. def test_set_encoding(self): payload = FakePayload('name=Hello Günter') request = WSGIRequest({'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'application/x-www-form-urlencoded', 'CONTENT_LENGTH': len(payload), 'wsgi.input': payload}) self.assertEqual(request.POST, {'name': ['Hello Günter']}) request.encoding = 'iso-8859-16' self.assertEqual(request.POST, {'name': ['Hello GĂŒnter']}) # Test for GET request = WSGIRequest({ 'REQUEST_METHOD': 'GET', 'wsgi.input': BytesIO(b''), 'QUERY_STRING': 'name=Hello Günter', }) # request.encoding = 'utf-8' self.assertEqual(request.GET, {'name': ['Hello Günter']}) request.encoding = 'iso-8859-16' self.assertEqual(request.GET, {'name': ['Hello GĂŒnter']}) -
django and internet explorer session loss
I have been trying to find a fix for this all day but no luck. I have a Django 1.9.4 website that works for all major browsers except for IE. I am using eclipse to run the Django site locally for testing. When I log into my site with IE-11 on the local server, it works just fine. When I pull the site onto a production unit (different IP address, over a network), IE seems to lose the session and I am just in an infinite loop on the login page. Below are the two functions that I believe are in context to this issue. "return redirect("myapp:homepage")" goes to a view that is decorated with "@checkLogin" applylogin gets run and when monitoring the network with IE dev tools under cookies I see the following Direction Key Value Expires Domain Path Secure HTTP only Received sessionid pk5svspepe9xk3og6ctnrwqrc56ukgrh Mon, 29-Aug-2016 15:39:03 GMT / No Yes so it appears to have received a session id. @requires_csrf_token def applylogin(request): newUsername = "" password = "" err_username = False err_pass=False if(request.POST.has_key('username')): newUsername=request.POST['username'] if(request.POST.has_key('password')): password=request.POST['password'] try: user = User.objects.get(username=newUsername) if(user.check_password(password)): request.session['login'] = newUsername request.session['userid'] = user.id request.session['useraccess'] = user.access if user.access >= 255: request.session['admin'] = True … -
Multiple many-to-many relations through the same model
I need to connect multiple fields from one model to another using a ManyToManyField through the same relational table. class First(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) foo = models.ManyToManyField( 'Second', related_name='foo', through='RelationModel', through_fields=('first', 'second') ) bar = models.ManyToManyField( 'Second', related_name='bar', through='RelationModel', through_fields=('first', 'second') ) baz = models.ManyToManyField( 'Second', related_name='baz', through='RelationModel', through_fields=('first', 'second') ) class RelationModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) status = models.IntegerField(default=0) first = models.ForeignKey('First') second = models.ForeignKey('Second') class Second(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) This results in the following error: myapp.First: (models.E003) The model has two many-to-many relations through the intermediate model 'myapp.RelationModel'. How do I work around this? Why isn't this allowed? -
UnicodeDecodeError:'ascii' codec can't decode byte 0xc2
Hi I am working with django and idea is to get user input and then modify my file.I have following data in my file: Q9UBD5 NA Show P14151 1.46E+01(fmol/µL plasma) Show I was trying to replace last word 'Show' with 'Hide' in each line based on some condition and following reuslt should: Q9UBD5 NA Hide P14151 1.46E+01(fmol/µL plasma) Hide For 1st line it was working perfectly but in 2nd line it was showing following error: 'ascii' codec can't decode byte 0xc2 Initial code for that error was: views.py: somefile=open("somefile.tsv","r+") somedata = somefile.readlines() somefile.seek(0) for line in somedata: data=line.strip() if some condition: data=data.replace(data[-4:], 'Hide') somefile.write(data+'\n') else: somefile.write(data+'\n') somefile.truncate() somefile.close() And after reading UnicodeDecodeError, I have modified my code and now getting new error: 'ascii' codec can't encode character u'\xb5' My modified code is: views.py: import codecs somefile=codecs.open('somefile.tsv',"r+", encoding='utf-8') somedata = somefile.readlines() somefile.seek(0) for line in somedata: data=line.strip() if some condition: data=data.replace(data[-4:], 'Hide') data=data.decode('utf-8') somefile.write(data+'\n') else: somefile.write(data+'\n') somefile.truncate() somefile.close() -
Django, can't get initial migration to run on new server.
I am trying to deploy a Django app to a new server. I have created the MySQL database. There are a lot of migrations and changes in the application as it is in the initial stages. The end of the stacktrace is: *** [err :: 134.213.122.97] _mysql.connection.query(self, query) *** [err :: 134.213.122.97] django.db.utils.ProgrammingError: (1146, "Table 'matchstaff_staging.jobsite_address' doesn't exist") The stacktrace is long but the relevant other parts are: *** [err :: 134.213.122.97] return import_module(self.urlconf_name) *** [err :: 134.213.122.97] File "/srv/wsgi/matchstaff-staging/shared/python_env/lib/python3.4/importlib/__init__.py", line 109, in import_module *** [err :: 134.213.122.97] return _bootstrap._gcd_import(name[level:], package, level) *** [err :: 134.213.122.97] File "<frozen importlib._bootstrap>", line 2254, in _gcd_import *** [err :: 134.213.122.97] File "<frozen importlib._bootstrap>", line 2237, in _find_and_load *** [err :: 134.213.122.97] File "<frozen importlib._bootstrap>", line 2226, in _find_and_load_unlocked *** [err :: 134.213.122.97] File "<frozen importlib._bootstrap>", line 1200, in _load_unlocked *** [err :: 134.213.122.97] File "<frozen importlib._bootstrap>", line 1129, in _exec *** [err :: 134.213.122.97] File "<frozen importlib._bootstrap>", line 1471, in exec_module *** [err :: 134.213.122.97] File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed *** [err :: 134.213.122.97] File "/srv/wsgi/matchstaff-staging/releases/20160829192208/matchstaff/urls.py", line 7, in <module> *** [err :: 134.213.122.97] from jobsite.views import * *** [err :: 134.213.122.97] File "/srv/wsgi/matchstaff-staging/releases/20160829192208/jobsite/views.py", line 18, in <module> *** [err :: … -
check_object_permissions with CreateAPIView
CommentCreate is a CreateAPIView used to post comments on another "report" model. I need to block anyone who is not the author of the report, or who is not in an assigned group of people who are allowed to post a comment, from using this endpoint to create comments. class CommentCreate(generics.CreateAPIView): serializer_class = CommentSerializer queryset = Comment.objects.none() def check_object_permissions(self, request, obj): if obj.report.creator != request.user: # also check if request.user is in the group of people that can comment raise exceptions.PermissionDenied( detail='You do not have permission') The issue I'm facing is that check_object_permissions gets called, but the exception is not being caught anywhere, so the comment is posted as normal no matter what. What am I missing here? -
Django Query : how do I find the maximum time duration from start and end time fields?
Here is my Django model: class Shift(models.Model): worker = models.OneToOneField('Worker',null=True) date = models.DateField(null=True) shiftTime = models.CharField(max_length=10, default="N/A") timeIn = models.TimeField(null=True) timeOut = models.TimeField(null=True) I need to find a worker who spent the maximum amount of time in the office in a given date range. How do I calculate the time duration from timeIn and timeOut field in Django query? -
Instance of type nameAndAddressType has no bound element for start tag - authnet
I am using authorize.net with python, and I am try to set it up in one of my Django view functions to send the customer's details: first name, last name, address, etc. with the transaction request to authorize.net's api. Whenever I do this however, I get this error. Instance of type {AnetApi/xml/v1/schema/AnetApiSchema.xsd}nameAndAddressType has no bound element for start tag Everything else works fine. Api credentials, payment information, its only when I try and set the billing details of the transaction request. views.py def authorizeNetCharge(request, card_number, exp_date="", price="0", ccv=""): credentials = getattr(settings, 'AUTH_NET', None) merchantAuth = apicontractsv1.merchantAuthenticationType() merchantAuth.name = credentials['login'] merchantAuth.transactionKey = credentials['txn_key'] creditCard = apicontractsv1.creditCardType() creditCard.cardNumber = card_number creditCard.expirationDate = exp_date creditCard.cardCode = ccv payment = apicontractsv1.paymentType() payment.creditCard = creditCard customer = apicontractsv1.nameAndAddressType() customer.firstName = 'John' customer.lastName = 'Smith' customer.address = '1111 Test St.' customer.city = 'Test' customer.state = 'Test' customer.zip = '46282' transactionrequest = apicontractsv1.transactionRequestType() transactionrequest.transactionType = "authCaptureTransaction" transactionrequest.amount = Decimal(price) transactionrequest.payment = payment transactionrequest.billTo = customer createtransactionrequest = apicontractsv1.createTransactionRequest() createtransactionrequest.merchantAuthentication = merchantAuth createtransactionrequest.refId = "MerchantID-0001" createtransactionrequest.transactionRequest = transactionrequest createtransactioncontroller = createTransactionController(createtransactionrequest) createTransactionController.setenvironment(credentials['environment']) createtransactioncontroller.execute() response = createtransactioncontroller.getresponse() pmt_err_msg = '' if response.messages.resultCode == "Ok": print("Transaction ID : %s" % response.transactionResponse.transId) return True else: code = response.messages.message.code.pyval for item in … -
django binary file download corrupted in browsers
I have a view that after authentication/permissions serves a file as saved in a FileField. from django.http import StreamingHttpResponse from rest_framework import viewsets from rest_framework.decorators import detail_route from wsgiref.util import FileWrapper import mimetypes from myapp.models import MyModel class ExampleViewSet(viewsets.ViewSet): # Normal crud (retrive, list, etc.) @detail_route(methods=['GET']) def download(self, *args, **kwargs): pk = self.request.parser_context['kwargs'].get('pk', None) if pk is None: raise exceptions.ParseError('no pk') instance = MyModel.objects.get(pk=pk) filename = instance.file_field.name.split('/')[-1] mime = mimetypes.guess_type(filename)[0] file = instance.file_field.file response = StreamingHttpResponse( FileWrapper(open(file, 'rb'), 10240)) response['Content-Type'] = "{0}; charset=utf-8".format(mime) response['Content-Length'] = file.size response[ 'Content-Disposition'] = 'attachment; filename={0}'.format(filename) return response The file itself is a 3.7MB file jpeg that was previously uploaded by the user. Under the upload directory the file is 3.7MB and opens correctly. when downloaded via the browser (Firefox or Chrome) the file is 7.0MB and corrupted (does not have the correct header for jpegs which should start with two specific bytes) when downloaded from curl or wget the file is 3.7MB and opens correctly The following is curl's output of the response fields using curl -v curl -v http://localhost:3000/api/school_admin/posters/7/download?token=ZXlKaGJHY2lPaUpJVXpVeE1pSXNJblI1Y0NJNklrcFhWQ0o5LmV5SndhR0Z6YUNJNkltSmpjbmx3ZEY5emFHRXlOVFlrSkRKaUpERXlKR2hzVlUxd2QyOWpTM1pMTnk1VlRuSXZPR1ZNVWs5aFJEVjBVbmR2V21FeVVGVlZiWGhxTTJWb1UzZFhla1JNU3k5RmFqZFRJaXdpY0hKdlptbHNaVjl3YXlJNk15d2laWGh3SWpveE5EY3lOalUyTWpFMGZRLmV6OGg5SWVwLUozYjdQcHJLVGJCZWlSSjJPN1JRdnItaFVuLVg0dmdLZGdtRGdQV0s2ZzkzdktialN2Uy1EVTVkM1hRc2hRZ3YxeVZmQlJhUDBBVlhB -o test.jpeg % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 0 0 0 0 … -
How to make a query that computes the difference of two timefield objects/attributes in Django?
Suppose I have a model that has four attributes: name, time in, time out, date. time in and time out are timefield objects. Now, I want to write a django query that tells me who was available in the office for most time duration in a given range. I am not sure how do I calculate the time difference (time out - time in) on the fly. Do I need to put another attribute like time duration? I was hoping to avoid that. -
Django use URL tag in template from app specific urls?
I have the following URLs in my project urls.py urlpatterns = i18n_patterns( url(r'^register/', include('register.urls')), ) So I maintain urls in the register app, so the urls.py in my register app looks like this: urlpatterns = patterns( url(r'^test/$', views.Test, name="register_test"), ) So I have a template that is located outside the register app, is located in the root of the project, and I am trying to use the above url like this: <a href="{% url 'register_test' %}"/>Test</a> But I get the following error: NoReverseMatch at /en/ Reverse for 'register_test' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] -
Can't get Django to work on my Mac
I'm having difficulty getting Django to work on my Mac. I pip installed it, as well as downloading it on PyCharm. I have a feeling it will work on PyCharm if I knew what I'm doing. I dont. haha. It's my first time. I am trying to work off the tutorial that they provide on their site. Here is where I run into trouble. In terminal I type: python -m django --version and I get: /usr/bin/python: No module named django but when I type: pip install Django I get: Requirement already satisfied (use --upgrade to upgrade): Django in /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages The tutorial wants me to type: django-admin startproject mysite and I get this: -bash: django-admin: command not found So to my question. What is going on here? I'm thinking my path to it is different than what is expected, though I'm not fully sure. If you know the startproject mysite could you give it to me? Meaning, if you know the folders and content I think I could get it running on PyCharm. My PyCharm says it's been downloaded, so I think this would be a great way to go into it. Many thanks. -
I have two django authentication backends. How can I put Condition for which one to use on my particular web page.?
What can I write in views or settings.py which auth system to use ?? This is my views.py @require_POST def login_view(request): filled_form = LoginForm(request.POST) if filled_form.is_valid(): user = filled_form.get_user() login(request,user) context = { 'user': user } return render(request,'home.html',context) else: return HttpResponse("Does not Exist") settings.py AUTHENTICATION_BACKENDS = ['accounts.backends.TeacherBackend','accounts.backends.StudentBackend'] backends.py class StudentBackend(object): def authenticate(self, username=None, password=None): print("AT STUDENT BACK") try: student = Student.objects.get(student_id=username) except Student.DoesNotExist: return None if student.check_password(password): return student else: return None def get_user(self, student_id): try: return Student.objects.get(pk=student_id) except Student.DoesNotExist: return None class TeacherBackend(object): print("AT TEACHER BACK") def authenticate(self, username=None, password=None): try: teacher = Teacher.objects.get(email=username) except Teacher.DoesNotExist: return None if teacher.check_password(password): return teacher else: return None def get_user(self, teacher_id): try: return Teacher.objects.get(pk=teacher_id) except UsTeacherer.DoesNotExist: return None Please tell me How can I write code which decides which backend to call ?? Please don't read stack overflow was forcing me to write more description but I was not able to think any so in a way I am writing this dummy text as description. Keep cool. Thanks in advance -
POST two related models by foreign key in Django
Im new at django. I'm triying to POST two models at the same time. One of my models is the user model, this one is related to the model Login, which only stores passwords. Any suggestions? (Sorry for my English) My Models: class Login(models.Model): password=models.CharField(max_length=64) def __str__ (self): return '%d: %s'% (self.id, self.password) class Meta: ordering=('id',) class User(models.Model): name=models.CharField(max_length=50) email=models.EmailField(max_length=30,null=True, unique=True) id= models.OneToOneField(Login,on_delete=models.CASCADE,primary_key=True,) USERNAME_FIELD = 'email' class Meta: ordering = ('name',) The Serializer: class UserSerializer(serializers.ModelSerializer): id = serializers.StringRelatedField() class Meta: model = User fields = ('name', 'email', 'id') class LoginSerializer(serializers.ModelSerializer): class Meta: model = Login fields = ('id','password') And the POST method where I'm having troubles: elif request.method=='POST': login_serializer= LoginSerializer(data=request.data) if login_serializer.is_valid(): login_serializer.save() user_serializer=UserSerializer(data=request.data) user_serializer.id=login_serializer if user_serializer.is_valid(): user_serializer.save() return Response(login_serializer.data, status=status.HTTP_201_CREATED) return Response (login_serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
The href in template doesn't have the
<a href="img/portfolio/fullsize/1.jpg" class="portfolio-box"> <img src="{% static 'otherapp/img/portfolio/thumbnails/1.jpg' %}" class="img-responsive" alt=""> <div class="portfolio-box-caption"> <div class="portfolio-box-caption-content"> <div class="project-category text-faded"> Category </div> <div class="project-name"> Project Name </div> </div> </div> </a> The template can be found in https://blackrockdigital.github.io/startbootstrap-creative/ In the template, the href="img/portfolio/fullsize/1.jpg" will open the image but when I tried it in django it opened http://localhost:8000/img/portfolio/fullsize/1.jpg instead which is expected in django but how can I achieve the image like the template in django?