Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django; how to load static files that are created by ManifestFileMixin
I'm trying to use ManifestFileMixin for cache busting in Django project. I was successful in uploading the static files on S3. But seems like the files are not loaded on html. Old files are still loaded. How can I fix this? I tried to use replace <script src="{% static 'js/file.js' %}></script> with @import url("js/file.js") but it still doesn't work. The purpose of using ManifestFileMixin is because I want to load new static files immediately after I update the files on S3. The changes cannot be reflected on html unless the users clean the browser cache. Is there a way to reflect changes on s3 quickly? -
Do custom template tags cause a database query?
I am using 5 - 6 custom template tags. Each one of them is similar to the following: @register.filter(name = 'time_left') def time_left(obj): if not obj: return -1 if not obj.has_offer_expired(): return obj.time_left() return None I have this in my models.py: def has_offer_expired(self): return self.end_time <= timezone.now() def time_left(self): return int((self.end_time - timezone.now()).total_seconds()) Whenever the template tag is used, {{ offer | time_left }}, will it cause a database query? Or, offer is passed to the template tag function and its attributes are used without causing any extra db query? A detailed explanation of the working of template tags behind the scenes would be much appreciated! Thank you. -
How can I not save child models to parents at ForeignKey?
There are two models of Factory and Pipeline. When creating objects, they are passed over the websocket to the client. Due to the fact that the ScenarioExist and PipelineTwo models are associated with Factory and Pipeline, they are also immediately transferred to the client. Is it possible to make sure that the objects created in ScenarioExist and PipelineTwo are not redirected to the client, but they belong to Scenario? models.py(Scenario, ScenarioExist, PipelineTwo) class Scenario(models.Model): title = models.CharField(max_length=200) class ScenarioExist(models.Model): scenario = models.ForeignKey('Scenario', related_name='scenario_exist', on_delete=models.CASCADE) factory = models.ForeignKey(Factory, related_name='factory', on_delete=models.CASCADE) class PipelineTwo(models.Model): scenario = models.ForeignKey('Scenario', related_name='scenario_pipeline', on_delete=models.CASCADE) pipeline = models.ForeignKey(Pipeline, null=True, on_delete=models.CASCADE, related_name='point_two') models.py(Factory) class Factory(models.Model): OBJECT_CHOICES = ( ('Factory', 'Завод'), ('Sump', 'Вышка'), ('Storage', 'Хранилище'), ('Petrol', 'АЗС') ) title = models.CharField(max_length=200) choice = models.CharField(max_length=15, choices=OBJECT_CHOICES, default='') address = YmapCoord(max_length=200, start_query=u'Россия', size_width=500, size_height=500, unique=True) Pipeline is about the same -
How to render json data from a function?
I am using a tutorial on Django sessions, where there is a function written to delete session on logout url call, but i want to use Ajax to call that function but problem is ajax giving error as im returning HttpResponse instead of any json response so can i know how to convert this function to render some json response? views.py def logout(request): try: del request.session['username'] except: pass return HttpResponse("<strong>You are logged out.</strong>") url.py url(r'^logout/', 'logout', name = 'logout') -
Celery periodic task not accessing module variables
I have a celery well configured and working with django. On post_save signal, I send a new record to a set using a task and using another periodic task, I m trying to consume that set. from __future__ import absolute_import, unicode_literals from celery import shared_task class Data(): def __init__(self): self.slotshandler = set() global data data = Data() @shared_task def ProcessMailSending(): #This is a periodic task, running every 30 seconds global data #This variable is always empty here while slotshandler: slot_instance = slotshandler.pop() print("sending mail for slot } to {} by mail {}".format(slot_instance .id,slot_instance .user,slot_instance .user_mail)) @shared_task def UpdateSlotHandler(new_slot): #This is called by save_post django signal global data data.slotshandler.add(new_slot) #filling the set at each new record The problem is that this task doesn't see my newly added time slots. note that this django app is run on a micro service for sending reminder mails to users. -
upload django site to the web hosting service
Hello im about the finish my first ever django website and I dont know how to upload it to the internet Bcuz I want to buy a web hosting service and to run django server I need to run a command python manage.py runserver and how is the web hosting service gonna do it? how should I upload my django website? -
Django; ManifestFilesMixin doesn't overwrite the old static files
I was trying to use ManifestFilesMixin for cache busting. But it doesn't overwrite the old files and create a bunch of static files. Is this default? How can I fix this? storage_backends.py is like this class StaticStorage(ManifestFilesMixin, S3Boto3Storage): location = settings.STATICFILES_LOCATION But this error happened so I tried like this as one of the answers on the issue. class CustomS3Boto3Storage(ManifestFilesMixin, S3Boto3Storage): def _save_content(self, obj, content, parameters): content.seek(0, os.SEEK_SET) content_autoclose = SpooledTemporaryFile() content_autoclose.write(content.read()) super(CustomS3Boto3Storage, self)._save_content(obj, content_autoclose, parameters) if not content_autoclose.closed: content_autoclose.close() class StaticStorage(CustomS3Boto3Storage): location = settings.STATICFILES_LOCATION It fixed the error but the static files cannot be overwritten. -
Read information about a directory and it's sub-directories using python
I'm working on a python(3.6) project in which I need to clone a GitHub repo which will have the directory structure as: |parent_DIR |--sub_DIR |file1.... |file2.... |--sub_DIR2 |file1... Now I need to get the following info: 1. Parent directory name 2. How many subdirectories are 3. names of subdirectories Here's how I'm cloning the GitHub repo: from views.py: # clone the github repo tempdir = tempfile.mkdtemp() saved_unmask = os.umask(0o077) out_dir = os.path.join(tempdir) Repo.clone_from(data['repo_url'], out_dir) -
Ingress and Ingress controller how to use them with NodePort Services?
I have a single service running on a NodePort service. How do i use ingress to access multiple services. deployment.yml apiVersion: apps/v1 kind: Deployment metadata: name: auth spec: replicas: 1 selector: matchLabels: app: auth template: metadata: labels: app: auth tier: backend track: dev spec: containers: - name: auth image: [url]/auth_app:v2 ports: - name: auth containerPort: 3000 service.yml apiVersion: v1 kind: Service metadata: name: auth spec: selector: app: auth tier: backend ports: - protocol: TCP port: 3000 targetPort: auth type: NodePort ingress.yml apiVersion: extensions/v1beta1 kind: Ingress metadata: name: test-ingress spec: backend: serviceName: auth servicePort: 8080 I followed step by step from the this repo. I could not get it working for my port config. I'm a beginner and would like some resources for the same. -
Django - retrieve url from HttpResponse object?
In Django test cases, how do you get the url from a HttpResponse object? If I have the following Django app: urls.py from django.urls import path from . import views urlpatterns = [ path('httpresponse/', views.http_response, name='http_response'), ] views.py from django.shortcuts import render def http_response(request): return render(request, template_name='home.html') tests.py from django.test import TestCase from django.urls import reverse http_response = reverse('http_response') class TestTemplateResponse(TestCase): def test_http_response(self): response = self.client.get(http_response) self.assertEqual(response.url, http_response) The unit test fails with the following message: AttributeError: 'HttpResponse' object has no attribute 'url'. Is there any way to get the client to return a Response object, instead of HttpResponse? -
Django - TypeError: expected str, bytes or os.PathLike object, not NoneType
i am having a problem when i run any manage.py command it show me this error -
In Django, unable to use related_name to fetch username from User class
class Topic(models.Model): subject = models.CharField(max_length=255) last_updated = models.DateTimeField(auto_now_add=True) board = models.ForeignKey(Board, on_delete = models.CASCADE, related_name='topics') starter = models.ForeignKey(User, on_delete = models.CASCADE, related_name='topics') views = models.PositiveIntegerField(default=0) I need to get the starter full name in a query. I have written the following query in shell and it is giving an error print(Topic.objects.all().values('board__description','subject','user__username')) The error is : Cannot resolve keyword 'user' into field. Please could you help and thanks in advance. -
Send html email with images in django
I am using django 1.8 and trying to send HTML Email with Inline Images according to this article my code is shown in blew: html_content = render_to_string( settings.TEMPLATE_ROOT + "/foo.html", ) msg = EmailMultiAlternatives('hello', html_content, 'John Foo <john@foo.com>', ['john@foo.com']) msg.attach_alternative(html_content, "text/html") msg.mixed_subtype = 'related' for f in ['logo.jpg']: fp = open(os.path.join(os.path.dirname(__file__), f), 'rb') msg_img = MIMEImage(fp.read()) fp.close() msg_img.add_header('Content-ID', '<{}>'.format(f)) msg.attach(msg_img) msg.send() and in html file i include image like: <html> <img src="cid:logo.jpg" alt="logo"></html> but the image not shown in received email. Am i missing something? -
Pyhton: Test Mixpanel locally > SSL error
I am trying to test Mixpanel locally but always run into this SSL error: MixpanelException at /register/D66Ly6ngyQ3I5boSQc9lBlrwiC2m3qbFAc5uMy3mstsZZcpFGXbi9TMUJf9hsGyh/ <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:833)> Now I found here an explanation how to solve this with Ruby: # config/initializers/mixpanel.rb if Rails.env.development? # silence local SSL errors Mixpanel.config_http do |http| http.verify_mode = OpenSSL::SSL::VERIFY_NONE end end However, I can't find any solution for Python. Do you have any ideas how to test Mixpanel locally? -
Semantic search on PostgreSQL
I know PostgreSQL has trigram trigram similarity search and even indexing optimized for it (CREATE INDEX trgm_idx ON table USING gist (column gist_trgm_ops);), which can be used directly from Django (web framework): Model.objects.filter(attribute__trigram_similar=query_string) But what if, instead of surface similarity, I wanted to perform semantic similarity query on database objects? Good example would be Google's universal sentence encoder, where I would convert all strings into 512 dimensional embedding vectors (using the library) and perform query by calculating normalized dot product (cosine similarity) and yield the object with highest similarity (or perhaps few objects with similarity >=0.50). Simplest thing to do is to iterate (at framework level) on the objects, but this is highly inefficient (especially if database is large), therefore I would rather to find a way where I could perform query on the database level (and perhaps if possible set up appropriate indexing?). What would be the best way to perform this custom similarity search on the database? (what if I save already vectorized data and then define some SQL function that performs, say cosine similarity?) Thank you! -
Django cannot run server
image I just started learning Django and it's stopping me from the beginning. as you can see from the image, whenever I try to runserver Errno 11001 comes in. So I googled it and seemed like proxy problem so I tried everything I could find but nothing fixed it. (environmental variables, trying different proxys, etc..) Can anybody helpme plzzzz -
UNIQUE constraint failed Django models
I'm working on a Django webapp. I'm trying to create a user from signup form. I made sure that there is no user in DB with that username and entered data in signup form and hit enter. There is a default language field that is populated with txt in User user model. I'm using the following function to populate that field. def get_default_language(): lang=Language.objects.get_or_create( name='Plain text', lang_code='text', slug='text', mime='text/plain', file_extension='.txt', ) return lang[0].id But it's giving me the below error IntegrityError at /signup/ UNIQUE constraint failed: djangobin_language.lang_code Here is the code for Language model class Language(models.Model): name=models.CharField(max_length=100) lang_code=models.CharField(max_length=100, unique=True, verbose_name="Language Code") Isn't it supposed to get or create the row in Language table? Why am I getting this error? -
Django : who to use a tag to destroy session with ajax?
I am not getting result, its calling the function but showing error as internal error.ajax call is working but not calling the function. views.py def logout(request): try: del request.session['username'] except: pass return HttpResponse("<strong>You are logged out.</strong>") urls.py path('logout',logout ,name = 'logout') html <li role="separator" class="divider"></li> <li><a href="#"><img src="{% static 'images/order.png' %}" class="icons">My Order</a></li> <li><a href="#"><img src="{% static 'images/account.png' %}" class="icons">Account Settings</a></li> <li><a href="#"><img src="{% static 'images/support.png' %}" class="icons">Support</a></li> <li role="separator" class="divider"></li> <li><a id="logout-anchor" href="/logout"><img src="{% static 'images/logout.png' %}" class="icons">Logout</a></li> </ul> ajax <script> $(document).ready(function(){ $('#logout-anchor').click(function(event){ event.preventDefault() console.log('hi-you are logged out') $.ajax({ method: 'GET', url: '/logout', success: function(res) { var response = $.parseJSON(res); window.location = "http://localhost:8000"; } }) }) }) </script> -
search based on location
I am trying to create search function based on location field. if anyone can help me then it would be great. models.py class demo(models.Model): name = models.CharField(max_length=100) city = models.CharField(max_length=100, null=True,) def __str__(self): return self.name View.py def search(request): if request.method == 'GET': srch = request.GET['srh'] if srch: match = demo.objects.filter(Q(name__icontains=srch)| Q(city__icontains=srch)) if match: return render(request, 'listing-search.html', {'sr':match}) else: print('no result found') else: return HttpResponseRedirect('') return render(request, 'listing-search.html') def home_view(request): return render(request, 'home-v3.html') def list(request): return render(request, 'listing-search.html') HTML.py <form action="search/" method="get"> <input type="text" name= "srh" class="form-control" placeholder="Type Name" aria-describedby="basic-addon1" list="find"> <input type="text" name="srh1" class="form-control" placeholder="Ex: Ambala" aria-describedby="basic-addon2" list="suggest-location"> <button class="btn btn-default" type="submit"><i class="fa fa-search" style="font-size: 25px"></i></button> </form> I have 2 input fields. Actualy, i want auto detect for location and search based on nearest results according to location. But i haven't reached that level yet. so, for now, i would like to know. how can i make function for both input. Name and location. it should match both input name and location at a same time. if name or it contains some letter of the name and city match then it should show the result. if input is only city name then it should show all the results related to … -
JSONDecodeError at / Expecting value: line 1 column 1 (char 0)
i am having such error which i cant debug from .services import GetList,GetAPIkey,GetAPIurl class ApiListView(TemplateView): def get(self, request): list_view = GetList().get_list_data() movie_list= list_view.json() if self.request.session.has_key('email'): email = self.request.session['email'] context = { 'movie_list':movie_list, 'email':email } else: context = {'movie_list':movie_list} return render(request, 'home-index.html', context) traceback error shows error is showing error is here - movie_list= list_view.json() -
Connect Mysql with Django framework
I have already installed MySQL ,Django ,mysqlclient , dajngo-mysql and change the setting.py file but I see the error when I want to run the server, Did you install mysqlclient? and when I want to run makemigrate command I also see this error. -
Can we store image in Django without using forms?
Is there a way to save Image file without using Models or ModelForm? -
Django - Annotation not showing in termplate
I'm trying to get annotations showing in my templates. I have two models (model1 and model2) and I want to show the number of model2's related to model1. Here is my views.py: def model2_count(request, pk): model2count = models.Model1.objects.filter(pk=model1.pk).annotate(title_count=Count(‘model2__title')) return render(request, 'model1/_model1.html', {‘m2c’: model2count}) Here is the template (model1/_model1.html): I tried this: {% for object in m2c %}</h3> {{ object.title }} {{ object.title_count }} {% endfor %} And tried this: {% if m2c.title_count %} {{ m2c.title_count }} {% endif %} I've been pulling my hair out over this for a couple days and can't figure it out. The following has been largely unhelpful: Django - Annotating Weighted AVG by Group Django: Annotation not working? Django templates are not showing values of annotations Django annotated value in template What's frustrating is that I can't even say why applying these solutions hasn't worked. Any input is appreciated. -
Limitations of Parse server for Django-web application
We are currently working on Django web application for which we want to use Parse server. What can be the possible drawbacks or limitations of parse which we can face while working on Django. It will be great help to know about limitations before we start working on it. -
DRF: How to validate a nested serializer's fields?
I have serializers.py as below: class PurchasedItemPOSTSerializer(serializers.ModelSerializer): class Meta: model = PurchasedItem fields = ('item', 'quantity', 'rate') def validate_quantity(self, value): if value==0 or value is None: raise serializers.ValidationError("Invalid quantity") return value def validate_rate(self, value): if value==0 or value is None: raise serializers.ValidationError("rate?? Did you get it for free?") return value class PurchaseInvoicePOSTSerializer(serializers.ModelSerializer): purchased_items = PurchasedItemPOSTSerializer(many=True) class Meta: model = PurchaseInvoice fields = ('invoice_no','date','purchased_items') def validate_purchased_items(self, value): if len(value)==0: raise serializers.ValidationError("atleast one item is required.") return value @transaction.atomic def create(self, validated_data): purchased_items_data = validated_data.pop('purchased_items') purchase_invoice = self.Meta.model.objects.create(**validated_data) for purchased_item in purchased_items_data: PurchasedItem.objects.create(purchase_invoice=purchase_invoice, **purchased_item) return invoice The data sent through POST is: { "invoice_no": "123", "date": "2018-07-13", "purchased_items": [ {"item":1, "quantity":0, "rate":0}], } As you can see from the data above no error is raised by validate_quantity when quantity=0 and neither by validate_rate when rate=0 for the item in purchased_items.