Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Safe HTML escaping
Ive been using Django builtin template filter safe to display some HTML code from a view. It's been working ok, but now it behaves strangely and I'm not sure what is to blame, if the HTML has changed or if the filter tag has changed in a django update. The Html code is delivered from the application mediainfo and looks like this... b'<html>\r\n' b'\r\n' b'<head>\r\n' b'<META http-equiv="Content-Type" content="text/html; charset=utf-8" /></head>\r\n' b'<body>\r\n' b'<table width="100%" border="0" cellpadding="1" cellspacing="2" style="border:1px solid Navy">\r\n' b'<tr>\r\n' b' <td width="150"><h2>General</h2> In the template I am using the safe filter as per the documentation to display the html. {% for line in htmlcode %} {{ line|safe }} {% endfor %} The resulting HTML now displays like this - b'\r\n' b'\r\n' b'\r\n' b'\r\n' b'\r\n' b'\r\n' b'\r\n' b' \r\n' b' \r\n' b' \r\n' b' \r\n' b' \r\n' b' \r\n' b' \r\n' b' \r\n' b' \r\n' b' \r\n' b' \r\n' b' \r\n' b' \r\n' b' \r\n' b' \r\n' b' \r\n' b' \r\n' b' \r\n' b' \r\n' b' \r\n' b' \r\n' b' \r\n' b' \r\n' b' \r\n' b' \r\n' b' \r\n' b' \r\n' b' \r\n' b' \r\n' b' \r\n' b' \r\n' b' \r\n' b' \r\n' b' \r\n' b' \r\n' b' \r\n' b' … -
Django request.user is becoming empty after login using angularjs
I have Django and angularjs app running separately. I am able to login to system by using angularjs. however after login request.user in django gives empty data. Login code: @csrf_exempt def login_for_new_design(request, *args, **kwargs): if request.method == "POST": temp=json.loads(request.body) username = temp.get("username", None) password = temp.get("password", None) user = authenticate(username=username, password=password) response_data = {} if user: login(request, user) response_data['success'] = True response_data['message'] = 'Login was succesfull!' else: # invalid case response_data['success'] = True response_data['message'] = 'Login was Failure!' response = HttpResponse(json.dumps(response_data)); response["Access-Control-Allow-Origin"] = "*" response["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS" response["Access-Control-Max-Age"] = "1000" response["Access-Control-Allow-Headers"] = "*" return response ajax method: $http({ method:'POST', url:uri, datatype:"json", data:payload, headers: { 'Content-Type': undefined }, }).then(function(result){ console.log(result) localStorage.setItem("username", $scope.username); $state.go('app.main', {showLeftnav: true}); },function(error){ console.log(error) }) Above two methods works fine. But when I want test for if user is logged in or not using below method, @csrf_exempt def isAuthenticated_user(request): userdic = {}; userdic['username'] = request.user.username print userdic response = HttpResponse(json.dumps(userdic)); response["Access-Control-Allow-Origin"] = "*" response["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS" response["Access-Control-Max-Age"] = "1000" response["Access-Control-Allow-Headers"] = "*" return response var csrftoken = $cookies.get('csrftoken') authPromise = $http({ 'method': "POST", 'url': "http://localhost:8000/isAuthenticated_user/", headers:{ "X-CSRFToken": csrftoken, 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' // 'withCredentials':true }, }) request.user gives empty data. Kindly let me know where I … -
Django + React: Can I still use django template tags in React code?
I am designing a website based on Django, Django Rest Framework and React. Now I'm in the planning process and curious about if I will be able to use Django native template tags in React code. So, will it work or I need to find another way to check permissions, get data form views and etc? I'm working with Django and how can I make multiple react app for a single website inside Django framework? -
Hot to get unique values from a column that contains comma seperated data in django?
I have a table like this | Id | Name | skills | |---- |---------|-----------------------------| | 1 | John | python, java, c++ | | 2 | Mike | c++, javascript | | 3 | Smith | java, ruby, vuejs, python | I need to find all the unique values for the column skills. -
Model beetween multiple apps django
i search through internet but I did not find the answer. I try using contenttype and genericforeignkey but that's not exacly what I wanted. I have app name Categories and i want it to work with many applications, for example: Blog, Events page, Video page etc. When I try with genericforeign key i don't have new field in post form called category. Post form screenshot My code: from django.db import models from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType class Category(models.Model): title = models.CharField(max_length=250) slug = models.SlugField(max_length=250) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') class Meta: verbose_name = "Kategorie" def __str__(self): return self.title Blog.models from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.contrib.contenttypes.fields import GenericRelation from categories.models import Category class Post(models.Model): STATUS_CHOICES=( ('draft', 'Roboczy'), ('published', 'Opublikowany'), ) image = models.ImageField(upload_to='images/blog') title = models.CharField(max_length=250) slug = models.SlugField(max_length=255) category = GenericRelation(Category) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') class Meta: ordering = ('-publish',) def __str__(self): return self.title -
View nodes and relationship from Neo4j in a Django template
I am trying to retrieve data from a Neo4j database in a Django template via Neomodel. Here is an example of the information I have in Neo4j: So here are my model.py: from django.db import models from django.utils import timezone from neomodel import (config, install_all_labels, StructuredNode, StructuredRel, StringProperty, IntegerProperty, UniqueIdProperty, Relationship, RelationshipTo, RelationshipFrom, DateProperty) config.DATABASE_URL = 'bolt://neo4j:mypassword@localhost:7687' class CodeListRelation(StructuredRel): From = IntegerProperty() To = IntegerProperty() class CodeList(StructuredNode): OID = StringProperty(unique_index=True) Name = StringProperty() EnumeratedItems = RelationshipTo('EnumeratedItem', 'Has_EnumeratedItem', model = CodeListRelation) class EnumeratedItem(StructuredNode): CodedValue = StringProperty() nciodm_ExtCodeID = StringProperty() CodeLists = RelationshipFrom(CodeList, 'Has_EnumeratedItem', model = CodeListRelation) Then in my view.py file, I have the following: from django.shortcuts import render def get_codelists(request): local_codelist = CodeList.nodes.order_by('nciodm_CDISCSubmissionValue') context = {'codelists': local_codelist} return render(request, 'lgcdfn/codelists.html', context) And here is my html file (called here codelist.html): {% for codelist in codelists %} <br><a id="{{ codelist.Name }}"></a> <div> <table> <caption><span>{{ codelist.Name }}</span></caption> <tr class="header"> <th scope="col">Ext Code ID</th> <th scope="col">Coded Value</th> <th scope="col">Validity dates</th> </tr> {% for enumerateditem in codelist.EnumeratedItems %} <tr> <td>{{ enumerateditem.nciodm_ExtCodeID }}</td> <td>{{ enumerateditem.CodedValue }}</td> <td>From: {{ enumerateditem.CodeLists.From }}<br/>To: {{ enumerateditem.CodeLists.To }}</td> </tr> {% endfor %} </table> </div> {% endfor %} So with the following code, I get the following html page: So my … -
Django RuntimeWarning: DateTimeField error in my django python model
I have created in models a class with a DateTimeField whcih I believe is causing an error in my project class Job(models.Model): category_id = models.ForeignKey(Category, on_delete=models.CASCADE) number_of_bids = models.IntegerField() time_starting = models.DateTimeField() time_ending = models.DateTimeField() The error returned is as below C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django-2.1.1-py3.7.egg\django\db\models\fields\__init__.py:1421: RuntimeWarning: DateTimeField Job.time_ending received a naive datetime (2018-10-25 10:03:58.889072) while time zone support is active. RuntimeWarning) Any tips on fixing -
Django export objects to .xlsx file with xlsxwriter
I'm using xlsxwriter library to export Django objects to .xlsx file. It seems to partially work, because I'm getting an issue when the file is downloaded. I open it with Excel and this issue appears in a window popup : An error occurred while sending a command to the program Then, if I reopen the file with Excel loaded, it works. So why it doesn't work the first time ? My excel works fine because I don't have any issue with .xlsx file from internet or somewhere else. This is my code which let to generate the excel file : def export_categories_xls(request): output = io.BytesIO() book = xlsxwriter.Workbook(output) sheet = book.add_worksheet('Category List') row = 0 sheet.write(row, 0, 'name') objects = Category.objects.all() row += 1 for item in objects: print(item) sheet.write(row, 0, item.name) row += 1 book.close() # construct response output.seek(0) response = HttpResponse(output.read(), content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") response['Content-Disposition'] = "attachment; filename=test.xlsx" return response Thank you ;) -
Get request triggered by js
I will explain what functionality I need in my django app on this example: User see list of cars and click "detail" button next to nice Mazda3, this action redirects him to the other page with URL like www.myapp.com/cars/detail/mazda3 where he can see additional information about car loaded from database. Also if he access this URL directly it should work without previous js call. I'm begginer and my plan after some search is to in js function trigger GET request, including car model in url in urls.py map base of this url '/cars/detail/' to view function in views.py parse car model from url and render page Problem is that I'm not sure this is correct way or if I should choose different approach. Also is GET request necessary (I've read that synchronous request should not be triggered in js) or should I just redirect to wanted url? -
How to update django sql database with a python script running locally?
I am currently working on a project for which I have to publish constantly changing data though my application programming interface. I have set up the django rest-framework, the model required for the sql database, the serializer and everything is working perfectly. I have seen that new database entries may be made through the python shell. I have a local algorithm running which is constantly calculating new analytics. I would like to make the algorithm update the database like it can be done manually through the shell. I have searched the web and the official documentation but could not find any instructions on how I could write a python script which updates the database. Does anyone know how to do this and may point me to suiting documentation or a tutorial? Thanks a lot for your help. Kind regards Marcel -
Django rollback not working after second objects.create fails to create a record
Here is the snippet code ofthe view: @transaction.atomic() def insert_in_sample_table(request): try: with transaction.atomic(): insert_obj = SampleTable1.objects.create(fld_id=2, fld_name='abc') insert_obj2 = SampleTable2.objects.create(fld_id=1, fld_name='xyz') return HttpResponse("SUCCESS") except IntegrityError: return HttpResponse("DB ERROR") There are two models: 1)SampleTable1 2)SampleTable2 The record for SampleTable2 i,e (1,'xyz') already exists in the database so it shows me IntegrityError.(which is true as the fld_id is primary key). But the rollback of SampleTable1 for (2,'abc') is not happening.(2,'abc') gets inserted in the SampleTable1 I removed the @transaction.atomic() and checked it still does not rollback. How to make the first database transaction rollback. -
find object instance of model between two dates
i want the records of my purchase items. when i added the purchase items in purchase model, that data are shown in my another app records have date time field start date to end date. if we added the two dates all the purchase data we purchase between these dates are shown in records. this below code is my project app name purchase, model name is Purchase. so please help me. thank you. from django.db import models from stock.models import * class Purchase(models.Model): product_name = models.CharField(max_length=100, blank=False) quantity = models.IntegerField() price = models.DecimalField(max_digits=12, decimal_places=2) #status = models.CharField(max_length=10, default='Purchased') def save(self): if not self.pk: Stock.objects.create(product_name=self.product_name, quantity=self.quantity, price=self.price) super().save() def __str__(self): return 'Product name:{0} Quantity:{1} Price:{2}'.format(self.product_name, self.quantity, self.price) class Meta: ordering = ['product_name'] and this my views.py of app purchase from django.shortcuts import render,redirect,get_object_or_404 from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from .models import * from stock.models import * from .forms import * def display_purchase_report(request): items_list = PurchaseReport.objects.all() query = request.GET.get("q") if query: items_list = items_list.filter(product_name__icontains=query) paginator = Paginator(items_list, 5) page = request.GET.get('page') try: items = paginator.page(page) except PageNotAnInteger: items = paginator.page(1) except EmptyPage: items = paginator.page(paginator.num_pages) context = { 'object_list': items, 'items': items_list, 'header': 'PURCHASED ITEMS' } return render(request, 'index3.html', context) def … -
Django prefix_default_language=False will return 404 to the homepage without prefix
Hello on development when i go to 0.0.0.0:8000 will automatically change the url to 0.0.0.0:8000/en/ But on staging if i go to my_website.staging.example.com wont change the url to /en/ and will show the 404 page Im using nginx and django -
nested for loops for formset inside templates
models.py class Task(models.Model): level = models.ForeignKey(Level, on_delete=models.CASCADE) todo = models.ForeignKey(ToDo, on_delete=models.CASCADE) student = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=150) content = models.TextField() timestamp = models.TimeField(auto_now=True) datestamp = models.DateField( auto_now=True) like = models.ManyToManyField(User,related_name='user_likes', blank=True) is_verified=models.BooleanField(default=False, blank=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('student:task-detail', kwargs={'pk': self.pk}) objects = PostManager() @property def comments(self): instance = self qs = Comment.objects.filter_by_instance(instance) return qs @property def get_content_type(self): instance = self content_type = ContentType.objects.get_for_model(instance.__class__) return content_type class Images(models.Model): post = models.ForeignKey(Task, default=None,on_delete=models.CASCADE) image = models.ImageField(verbose_name='Image',blank=True) def __str__(self): return self.post.title I have two models Task and Images. Im storing multiple images for a task saved ugnfg formsets. I want to display the list of tasks using pagination and also images inside each task. views.py: @login_required(login_url='/account/login/') @page_template('student_dash_page.html') def StudentDashView(request,template='student_dash.html', extra_context=None): if not request.user.is_authenticated: return redirect('accounts:index') task = Task.objects.all().order_by('timestamp') images = Images.objects.filter(post=task) notifications = Notification.objects.filter(receiver=request.user).order_by('- timestamp') page = request.GET.get('page', 1) paginator = Paginator(task, 10) try: tasks = paginator.page(page) except PageNotAnInteger: tasks = paginator.page(1) except EmptyPage: tasks= paginator.page(paginator.num_pages) context = { 'notifications': notifications, 'nbar': 'home', 'task': tasks, 'images': images } if not request.user.is_client: return HttpResponse("You are in trainer account") if extra_context is not None: context.update(extra_context) return render(request, template, context) How do i get the images to display correctly inside the template … -
Django giving error when save json data in models
I will tried this code to save my json data to my model that is Mvouchar but getting this error i easily get data through cmd but i try to save this in my model then i get error why this happen i think am doing some minor mistake but cant catch please help if u get my point. #views.py @csrf_exempt def jsdata(request): table_data = json.loads(request.POST.get('MyData')) print(table_data) for data in table_data: b_no = request.POST['billno'] b_details = request.POST['billdetails'] at = request.POST['amount2'] record = Mvouchar(bill_no = data.b_no, bill_details = data.b_details,am=data.at) record.save() return render(request, 'cheque/mvouchar.html', {'msg': 'Data Saved.'}) #models.py class Mvouchar(models.Model): related = models.ForeignKey(Signs, on_delete=models.CASCADE, null=True, blank=True) bill_no = models.CharField(max_length=80, null=True, blank=True) bill_details = models.CharField(max_length=1000, null=True, blank=True) am = models.CharField(max_length=30, null=True, blank=True) vouchar_no = models.CharField(max_length=1000, null=True, blank=True) #urls.py url(r'jsondata/$', views.jsdata, name='jsondata'), #script <script> $("#btnjson").click(function () { var array1 = []; $("tbody tr").each(function () { var firstTableData = {}; firstTableData.BillNo = $(this).find('td').eq(0).text(); firstTableData.BillDetails = $(this).find('td').eq(1).text(); firstTableData.Amount = $(this).find('td').eq(2).text(); array1.push(firstTableData); //} }); alert(JSON.stringify(array1)); $.ajax({ type: "POST", url: "/jsondata/", dataType: 'json', data: {MyData: JSON.stringify(array1)}, success: function(msg){ alert(msg); } }); return false; } ); }); </script> -
Deploying Django on VPS but getting nginx 502 Bad Gateway: recv() failed (104: Connection reset by peer) while reading response header from upstream
I'm trying to deploy a Python3 Django project on a Digital Ocean droplet using one-click install for Django. I've uploaded everything and changed the files to what they should be (to my knowledge) but when I go to my site in my web browser, I get a page that says '502 Bad Gateway' from nginx. When I look in my error log, I get the following error: recv() failed (104: Connection reset by peer) while reading response header from upstream I'm not sure what this means exactly, so I'm hoping someone here can help. I have however changed the python command to run python3 because it was set up for python2 and an older version of Django. I've updated Django and dependencies. Are the any config files I should edit? Perhaps a python path for nginx? I'm a bit in over my head here, so any help is appreciated. Thanks! -
How to use Django VersatilemageField on a Boostrap Modal and make PPOI works?
i try to used Django Versatilimagefield on a Boostrap Modal, but the PPOI doesn't work ... enter image description here Here my code <div class="row"> <!-- Modal add image--> <div class="modal fade" id="image_modal" tabindex="-1" role="dialog" aria-labelledby="add_imageLabel" > <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title" id="myModalLabel">Ajouter/Editer une image</h4> </div> <div class="modal-body" style="margin:10px;"> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Fermer</button> </div> </div> </div> </div> </div> And Form is injected from javascript function <script> $(document).ready(function(){ $('.openPopup').on('click',function(){ var dataURL = $(this).attr('data-href'); $('.modal-body').load(dataURL,function(){ $('#image_modal').modal({show:true}); }); }); }); </script> who inject this form code on the Modal body <form role="form" action="/intranet/laboutique/product/image/editer/{{tab_data.pk_product}}/{{tab_data.pk_image}}/" method="post" enctype="multipart/form-data" name="add_image_form"> {% csrf_token %} <div class="row"> <div class="form-group" id="image_form"> {{tab_data.image_form.media}} {{tab_data.image_form}} </div> <input id="url_next" name="url_next" type="hidden" value="{{request.path}}"> <button type="submit" class="btn btn-danger" name="submit_save_image">Sauvegarder</button> </div> </form> All works well except the PPOI, i can't move the Point, and Double Click doesn't works as well... I think it's a Dom problem... Thx for help -
How to implemet django bulk update?
def populateAdcuratioDb(upload_type, obj_list): """ populate Adcuratio table with Vtr data, Supermarket data and latam data :param upload_type: :param obj_list: :return: """ upload_type_dict = {"super_market": SuperMarketData, "latam": LatamAirData, "vtr": Vtr} upload_model = upload_type_dict.get(upload_type) adcuratio_data_create_list = [] if not obj_list: return "data already saved" for obj in obj_list: new_obj = AdcuratioData() if not AdcuratioData.objects.filter(email=obj.email.lower()): new_obj.email = obj.email.lower() new_obj.synthetic_id = "adc"+(str(uuid.uuid4())) upload_type_data = upload_model.objects.filter(email=obj.email.lower())[0] setattr(new_obj, upload_type, upload_type_data) adcuratio_data_create_list.append(new_obj) else: # we'll have to think about bulk update option here new_obj = AdcuratioData.objects.filter(email=obj.email.lower())[0] upload_type_data = upload_model.objects.filter(email=obj.email.lower())[0] setattr(new_obj, upload_type, upload_type_data) new_obj.save() AdcuratioData.objects.bulk_create(adcuratio_data_create_list) In the else condition, I'm saving each object one buy one which is taking hell lot of time. I need something like bulk_create or any suggestion on how to implement that? Thanks in Advance! -
Load Angular 2+ files inside Django template
Is there any way I can load Angular files on Django template? So I can host Angular on localhost:8000. I can do this on ASP.NET Core MVC with loading angular files on MVC View. All I nedd is to include angular scripts and app.component selector: @section Scripts{ <script src="~/clientapp/dist/inline.bundle.js"></script> <script src="~/clientapp/dist/polyfills.bundle.js"></script> <script src="~/clientapp/dist/styles.bundle.js"></script> <script src="~/clientapp/dist/vendor.bundle.js"></script> <script src="~/clientapp/dist/main.bundle.js"></script> } <employees></employees> app.component: import { Component } from '@angular/core'; import { Router, Event } from '@angular/router'; @Component({ selector: 'employees', templateUrl: "./app.component.html", styles: [] }) export class AppComponent { title = 'Employees'; } After doing this on Django I get this error in console: The selector "employees" did not match any elements at DefaultDomRenderer2.push.../node_modules/@angular/platform-browser/fesm5/platform-browser.js.DefaultDomRenderer2.selectRootElement -
Cannot connect to websocket
I want to run daphne and gunicorn separetly. Here is Nginx config. server { if ($host = `server_name`) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; server_name `server_name`; location ^~ /.well-known { root /home/dev/app/; } } server { listen 443 ssl; server_name `server_name`; proxy_set_header Host $http_host; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-For $remote_addr; proxy_redirect off; keepalive_timeout 0; proxy_read_timeout 60s; proxy_send_timeout 60s; send_timeout 60s; resolver_timeout 60s; client_body_timeout 60s; client_body_buffer_size 100k; location /static { alias /home/dev/app/static_collected; expires 365d; } location /wss/ { proxy_pass http://localhost:9000; proxy_set_header Upgrade $http_upgrade; proxy_set_header Cannection "upgrade"; proxy_http_version 1.1; proxy_read_timeout 86400; proxy_redirect off; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } server_tokens off; client_max_body_size 10000M; location /media { alias /home/dev/app/media; expires 365d; } location = /favicon.ico { alias /home/dev/app/static/img/favicon.ico; } location / { proxy_pass http://localhost:8005; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } ssl_certificate ... # managed by Certbot ssl_certificate_key ... # managed by Certbot } Supervisor config for daphne: [program:asgi] directory=/home/dev/app command=/home/dev/.local/bin/pipenv run daphne numprocs=1 user=svalee autostart=true autorestart=true stdout_logfile=/home/dev/logs/asgi.log redirect_stderr=true I'm running daphne with command daphne -b 0.0.0.0 -p 9000 config.asgi:application Supervisor works and my site it published but I can't … -
Django will i18n throws error when visiting the homepage without language prefix
Hello on development when i go to 0.0.0.0:8000 will automatically change the url to 0.0.0.0:8000/en/ But on staging if i go to my_website.staging.example.com wont change the url to /en/ and will show the 404 page Im using nginx and django my urls urlpatterns = i18n_patterns( url(r'^$', views.home, name='home'), path('admin/', admin.site.urls), url(r'^logout/$', views.disconnect_user, name='logout'), path('ckeditor/', include('ckeditor_uploader.urls')), url(r'^login/$', auth_views.login, name='login'), url(r'^oauth/', include('social_django.urls', namespace='social'), name='fb-login'), # <-- url(r'^i18n/', include('django.conf.urls.i18n')), url(r'^', include('manager.urls')), -
Image not showing in Gmail - Using django python-postmark
I've used django python-postmark for mailing. Now my problem is that my static images are not shown on Gmail. Gmail prepends a url proxy to the src of the images. if the prepended url proxy is removed, the image will show perfectly. What am I missing here? or how do I fix this? thanks These are my code for the image. this supposed to result to src="https://mysite_here.com/static/img/img.png" {% load static %} {% load custom_tag %} <img src="{% site_url %}{% static 'img/img.png' %}"> But upon showing on gmail, the src is now prepended which causes the image to not show. <img src="https://ci3.googleusercontent.com/proxy/rYDcSW7inrn8_vlXhcrSojT1T06pKEKyrzmXgb5cje_JCc9ze25emLbFDuBub3CWP_ASqgUXbqn6RureN5Fy0Nd-eFdllL14aq16UQ_rXrB4-dWp=s0-d-e1-ft#https://mysite_here.com/static/img/img.png" class="m_-186473825407072632logo CToWUd"> -
Problem with downloading file in DRF+Angular
I am doing project on DRF+Angular. Currently on localhost I can download file with action: @action(methods=['get'], detail=True) def download(self, *args, **kwargs): instance = self.get_object() file_handle = instance.file.open() response = FileResponse(file_handle.read(), content_type='application/file') response['Content-Length'] = instance.file.size response['Content-Disposition'] = f'attachment; filename="{instance.file.name}"' file_handle.close() return response It works on localhost, but when front-end tries to get the same file under the same url on server - I get a redirection to a DRF template with HTTP 401 Unauthorized. But I have already entered my credentials. What is going wrong? -
How to create a recommendation given ratings using Django
I want to create a recommendation engine on my application. I can rate a post but i have been able to create a recommendation engine which recommends to a user similar posts with almost similar ratings in the application. I have a RESTAPI already. How do i solve this? This is my models.py from django.db import models from django.contrib.auth.models import User from django.db.models import Avg from tinymce.models import HTMLField import numpy as np # Create your models here. class Profile(models.Model): profile_photo = models.ImageField(upload_to ='prof_pictures/') bio = HTMLField() phone = models.IntegerField(default=0) user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) def save_profile(self): self.save() def delete_profile(self): self.delete() @classmethod def get_profile(cls,id): profile = Profile.objects.get(user = id) return profile @classmethod def filter_by_id(cls,id): profile = Profile.objects.filter(user=id).first() return profile # @classmethod # def search_profile(cls,name): # profile = Profile.objects.filter(user__username__icontains = name) # return profile class Project(models.Model): photo = models.ImageField(upload_to ='prof_pictures/') project_name = models.CharField(max_length = 100) project_caption = models.CharField(max_length = 100) user_profile = models.ForeignKey(User, on_delete=models.CASCADE, related_name='projects', default="") def save_project(self): self.save() def delete_project(self): self.delete() @classmethod def search_project(cls,search_term): projects = cls.objects.filter(project_name__icontains=search_term) return projects @classmethod def get_project(cls, id): project = Project.objects.get(pk=id) return project @classmethod def get_images(cls): projects = Project.objects.all() return projects @classmethod def get_profile_image(cls,profile): projects = Project.objects.filter(user_profile__pk=profile) return projects def design_rating(self): all_designs =list( map(lambda x: … -
django auth: increasing max_length group name field
in jdnago 1.8 the max_length of name field for Group model in auth app is by default 80 characters. I need to increase this limit without extending the default group model.