Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Heroku Django, templatedoesnotexist error
So after couple late night works, I finally had my app deployed onto the Heroku, but now a different issue, and sleepless night, the template does not exist error, I'm using Django.1.11, so my setting is as following; INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'storages', 'photos', ] and my TEMPLATES is as following, as from the doc, the installed app, with APP_DIR set to be true, would look for the templates folder within the apps. TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] And finally my app structure; mysite photos --templates ----photos ------templates ---------index.html when I load the page, I can see from the log; Using engine django: django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python2.7/site-packages/django/contrib/admin/templates/photos/index.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python2.7/site-packages/django/contrib/auth/templates/photos/index.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/photos/templates/photos/index.html (Source does not exist) The last line, shows the correct path, but somehow, it cannot be found, I really dont know why, can someone shed some lights ! Thanks Jimmy -
How to change a value in django on button click in HTML
I am trying to implement a function in which when I click on Activate button, the value in my Django database for this field changes to 'Active' and is displayed on the HTML page as active. If deactivate is clicked, the text changes to deactive along with it's value in the django database. This is my current HTML page: <div class="col-sm-5"> <div class="panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title">Job activation status</h3> </div> <div class="panel-body"> <b>Status</b>: Active <span style="padding-left:20px;"></span> <button type="button" class="btn btn-primary">Activate</button> <button type="button" class="btn btn-primary">Deactivate</button> <button type="button" class="btn btn-primary">Dissolve</button> </div> </div> </div> And my models.py is as follows: class Job(models.Model): def __unicode__(self): return self.name name = models.CharField('Job Name',max_length=128) # when the job was created date_created = models.DateTimeField('Date Created', auto_now=True) # what entity/organization needs this job? client_organization = models.CharField('What organization do you represent?', max_length=64) # short description description = models.TextField('Job Description', max_length=256) # end product to be delivered deliverable = models.TextField('Deliverable', max_length=256) # when Job is due for completion duedate = models.DateTimeField('Date Due') # all persons who may be affected by project #stakeholders = models.TextField('Stakeholders') # important technical requirements #additional_information = models.TextField('Additional Information', blank = True) # budget estimate #budget = models.CharField('Budget', max_length=64) # file attachments #attachments = models.FileField(upload_to='job', blank = … -
Django best practice for join mysql tables
I have two model like this in my Django project. class Product(models.Model): name = models.CharField(max_length=100) category = models.ForeignKey(ProductCategory, on_delete=models.CASCADE) sub_category = models.ForeignKey(ProductSubCategory, on_delete=models.CASCADE) comment = models.TextField() size = models.CharField(max_length=60) price = models.FloatField(default=0) class ProductImage(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) alt = models.CharField(max_length=200) picture = models.FileField() Of course a product can have 2 or more picture. How can I get a all products with all related every single image in my view and pass the result as a context to the template. also I searched and tried these: prefetch_related, select_related, raw sql query and couple of suggested ways. but cannot get the result. I am newbie in Django and any solutions would helped me. Thanks in advanced. -
Django Static files URL,ROOT,DIR confusion
I am using Django v1.11.In the setting file I have set like this STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "e","static","static_root") STATICFILES_DIRS = [ os.path.join(BASE_DIR, "e","static","static_dir"), ] Firstly I copied all my css,js,img file in static_dir folder.Then I run the command python manage.py collectstatic Which copied all the files from static_dir to static_root.As I can understand now all my css files should be loaded from static_root. But I can see that css files are being loaded from static_dir. So can anyone please explain it to me what is happening ? Why should I use static_root ? I can not find any use of static_root -
What to choose for YouTube/FB type heavy content based web application - RAW Coding or Framework?
I want to develop a huge content based web application. The application will be a combination of youtube & facebook features. Users will upload their videos & pictures. Visitors will watch those and give vote/rate the artist. There will be artist hiring facility also. Estimated users may be 0.5 million & simultaneous hits may be 30,000 during peak hours.. What should I do - Go for RAW coding (PHP, PYTHON, ASP.Net)? Or choose any Framework/Theme Template??? If Framework/Theme, then which one- WordPress, Laravel, or anything else??? -
How does django handle ManyToOne relationships with possible nulls?
I'm working on app that is supposed to help users catalog information. Application will be collecting Quote for bonds one of its functionalities will be to display information about the quoted Bond. That being said I'm expecting to receive a lot of Quotefor Bond not in my database. As I understand if describe relationship with ForeignKey lets call that variable bond_pkey inside Quote model then bond_id can never be empty and when I try to create a quote for a Bond that is not in my database transaction will fail. So how can one describe in django a relation ship where each Quote has zero to one Bond and each Bond has zero to many Quote? Is it better that I don't describe this in model and use QuerySet.filter(bond_id=some_bond) instead? -
Django Model - CharField as concatenation of other fields
I'm learning Django and looking for a best practice: Imagine I have a model for a mobile phone device: class Device(models.Model): vendor = models.CharField(max_length=100) line = models.CharField(max_length=100, blank=True) model = models.CharField(max_length=100) Let's say I create an object like this: Device.objects.create(vendor = "Apple", line = "iPhone", model = "SE" ) or without "line": Device.objects.create(vendor = "Xiaomi", model = "Mi 6" ) Then I'd like to track sales in my shop for every device, so I create a model for a "Deal" (I track only the deal date and the device sold, device as a ForeignKey): class Deal(models.Model): device = models.ForeignKey(Device, on_delete=models.CASCADE) deal_date = models.DateTimeField(default=None) Question: What is the best way to create a "Deal" object, if I want to query "Device" by its full, concatenated name, e.g. "Apple iPhone SE" or "Xiaomi Mi 6"? I've found something similar in Django database entry created by concatenation of two fields , however not sure if it's the right path in my case. My best guess is something like this (where "name" is a concatenated field): de = Device.objects.get(name = "Apple iPhone SE") Deal.objects.create(device = de, deal_date = datetime(2018, 4, 26, 15, 28) ) What is the correct way to do this task? Many … -
How does Django handles Model Meta ordering in Database
On ordering Django documentation says The default ordering for the object, for use when obtaining lists of objects What does it means by obtaining? Does Django stores objects normally and while fetching use something like ORDER BY (e.g. in SQL)? Or does data is stored in this way? Or indexing takes place on ordering column ? Objective is to understand how costly is insert/fetch operation on Django model with Meta ordering as compared to one which hasn't. -
What is the Django equivalent for the Flask example used by Google API Python Client?
I'm trying to follow the examples for getting OAuth up and running with a Python app as described by Google's API. They use a flask example only. In the case of this, for example: @app.route('/test') def test_api_request(): if 'credentials' not in flask.session: return flask.redirect('authorize') # Load credentials from the session. credentials = google.oauth2.credentials.Credentials( **flask.session['credentials']) ... How would I know what to replace the **flask.session['credentials'] with in my Django application? I am still attempting to do the same thing, but without Flask. What is the Django equivalent for flask.session? The code is taken from here: https://developers.google.com/api-client-library/python/auth/web-app#example -
Installing numpy on openshift origin
I am trying to install numpy on openshift so that my django website can access it. I tried to install it by calling pip install numpy in the pod terminal. This seemed to install but when I tried to import numpy in my code it gave ImportError: No module named numpy -
best away to return json of mongodb in django app
How can I return a json of all documents in my collection? I'm using pymongo, and I has one method that do this for me client = MongoClient('localhost', 27017) db = client.sourceReggaeMusic source = db.source def findAll(self): return source.find() but this method return something like this <pymongo.cursor.Cursor object at 0x0618FDD0> and I need to do a for to print elements. Exists some away to get this result in json format? or convert this? I need to convert to json, because when I make a request to some url, I'll response this json -
Connecting Nginx and Django
This is my first time working in Nginx. I know that in order to connect Django and Nginx easily I require uWSGI. Setup uWSGI: I think my uWSGI setup was completely fine, I've used it to run my Django website on HTTP port 80: uwsgi --http :80 --root /root/Env/firstsite --chdir /root/mysite -w mysite.wsgi But since this is not a very practical method for the "best" security, I had to use Nginx. In this case I've used "The uWSGI Emperor" mode and then i've created a new file /etc/uwsgi/sites/mysite.ini: [uwsgi] project = mysite base = /root chdir = %(base)/%(project) home = %(base)/Env/%(project) module = %(project).wsgi:application master = true processes = 5 socket = %(base)/%(project)/%(project).sock chmod-socket = 666 vacuum = true In this case, Instead of HTTP ports I've used unix socket which uses uwsgi protocol. Finally, I've created /etc/systemd/system/uwsgi.service file (which from my understanding initiates uwsgi on startup): [Unit] Description=uWSGI Emperor service After=syslog.target [Service] ExecStart=/usr/uwsgi --emperor /etc/uwsgi/sites Restart=always KillSignal=SIGQUIT Type=notify StandardError=syslog NotifyAccess=all [Install] WantedBy=multi-user.target Nginx: My Nginx setup was pretty simple, I've just modified the existing server block to fit uWSGI configuration: server { listen 80; server_name mysite.com www.mysite.com; location = favicon.ico { access_log off; log_not_found off; } location /static/ { … -
Django: models function for download
views.py def image_downloaded (request, image_id): x = get_object_or_404(Image, pk=image_id) x.no_of_download += 1 x.download_photo x.save() return render (request, 'imagebank/download_successful.html',{'image': x}) models.py class Image(models.Model): title = models.CharField(max_length=100) photo = models.FileField() no_of_download = models.IntegerField(default=0) def __str__(self): return self.title def download_photo(?????): ??????????????????? what code should I add in the ?????????, so that once calling the function image_downloaded in views.py, the photo file will be downloaded to the user's computer. Is this possible? Just tell me it wont be possible if it is....>< -
Django - override SESSION_SAVE_EVERY_REQUEST for a particular view
Is there a better way to override SESSION_SAVE_EVERY_REQUEST on just one view. The rest of the application the session can be renewed. -
Improve Django/Python report creating process
I'm currently generating a report with a database table with 30K records, for this report I'm generally doing something like the following: for obj in Model.objects.all(): do_work() obj.save() I have all the phases of the report creation separated in functions like: report_phase_1() report_phase_2() report_phase_3() In each one something happens like Model.objects.all() or Model.objects.filter(some_filtering_by_columns) Then problem is that I'm doing the same Model.objects.all() multiple times during the report creation so I understand each time is retrieving the records from the database and then storing them back on each .save() My question is, is there a way I can tell Django to retrieve the whole data set and keep filtering that dataset applying the modifications but keeping everything in memory and just send it back to the database once everything is updated? -
Diffrence between get_user_model() and importing User from auth
When I need to use the current user in a model. lets say I have a model with a current_user field, something like: class mymodel(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,default=None) my understanding is User can be fetched either: 1)by importing the current user: from django.contrib.auth.models import User or 2) setting User to: User = get_user_model() I understand both will work if I am not wrong!! So What is the main difference between those two methods if there is any? Thanks -
How to properly pass a context variable to DRF serializer
I am trying to pass some parameters into a DRF serializer. In my views, I am passing these parameters (through context) into the serializer. def post(self, request, name, age, format=None): serializer = CreatePersonSerializer(data=request.data, context={'name': name, 'age': age}) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) In my serializer, I am trying to append these values 'name' and 'age' to self.initial_data class CreatePersonSerializer(GenericSerializer): name = serializers.CharField(source='parent.name', required=False) age = serializers.CharField(source='parent.age', required=False) class Meta: model = Person fields = ('name', 'age', 'location', 'parent') def is_valid(self, raise_exception=False): if hasattr(self, 'initial_data'): self.initial_data['name'] = self.context['name'] self.initial_data['age'] = self.context['age'] logging.debug(self.initial_data) super(CreatePersonSerializer, self).clean_ids() return super().is_valid(raise_exception) I know that what I am trying to accomplish is working because logging.debug(self.initial_data) returns: {'name': 'test', 'age': 'test', 'parent': 'test', 'location': 'test'} which is exactly what I want. However, that last line super().is_valid() is throwing this error: dictionary[keys[-1]] = value TypeError: 'parent' object does not support item assignment What am I doing wrong here? I really can't figure it out. self.initial_data contains all the values I need models.py class Person(models.Model): location = models.CharField(max_length=150) parent = models.CharField(max_length=200) -
Django:how to install Spatialite for django on windows 10
I am using the spatial database spatialite for a django project for the first time, I followed the Django documentation, when I reach the step that says " run the configure script" I don't konow how to run that script, and witch script exactly, is it the configure file or configure.ac. can you please help me, or is there a very simple way to intall Spatialite for a django project. Thanks. -
Parse value in html from dictionary in django
I have a dictionary like this in django my_dict = {0: 'Dog - Wikipedia', 1: 'https://en.wikipedia.org/wiki/Dog', 2: 'Funny babies annoying dogs - Cute dog & baby compilation ...', 3: 'https://www.youtube.com/watch?v=M1djO19aSFQ'} What I want is to have title as title but the link to be appeared as a link in html template...Can u guys please help me sort this out?i am new in this case.. :( ps: how do i iterate over the dictionary to create one as a title and the next one as a link? -
How to reduce long template rendering time?
I am trying to optimize my view-template rendering. At this moment I have such picture: As you see: SQL timing lasts ~0.5sec, TemplateTiming ~2sec, but Total Time is almost 9 seconds! Also I have a timer in my view - it shows ~0.6 seconds of view work. When the view prints "Finished" - after that goes a lot of time when I see this page render finished in my browser. Can somebody explain me from where the hell additional 9-0.5-2-0.6 = 5.9 seconds come from? I have quite a long list to render, with pagination, ~12k items. If there is smaller item amount - the render time is also smaller. Sometimes I also render this page with list of ~20k items, but with another combination of queries/filters - and the total time is much smaller ~4~5 seconds. What is going wrong and when? -
CSRF token in Angular 4 CLI from Django
I created a full-stack app with Angular, Node, Express and Postgres: https://github.com/shivkiyer/database-app Now I am trying to learn Django by repeating the project with Django on the backend instead of Node JS. The entire code is here: https://github.com/shivkiyer/djangoangular I am not able to extract the CSRF token sent by Django in Angular so that I can send it back when I submit a POST form. In Django, I have these two views: from django.shortcuts import render from django.http import HttpResponse, JsonResponse from . import models, forms # Create your views here. def basic_list(request): print(request) customer_list = [] for customer_item in models.Customer.objects.all(): customer_list.append({ "first_name": customer_item.first_name, "last_name": customer_item.last_name, "city": customer_item.city }) print(customer_list) return JsonResponse(customer_list, safe=False) def empty_form(request): print(request) return HttpResponse("Form received") In my settings.py file I have 'django.middleware.csrf.CsrfViewMiddleware' enabled. I checked out the Django documentation: https://docs.djangoproject.com/en/2.0/ref/csrf/ I tried adding several options in settings.py file: CSRF_USE_SESSIONS = True CSRF_HEADER_NAME = 'HTTP_X_CSRFTOKEN' CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_HEADERS = ( 'content-type', 'HTTP_X_CSRFTOKEN' ) CORS_EXPOSE_HEADERS = [ 'content-type', 'HTTP_X_CSRFTOKEN'] My Angular component has: import { Component, OnInit } from '@angular/core'; import { Http, Response, Headers } from '@angular/http'; import { FormGroup, FormControl, Validators } from '@angular/forms'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) … -
Django - Delete view seems to be splitting IDs in success url
My delete view seems to be splitting url arguments on the success url. trace back included below. when deleting an object I get an error which looks like it has split the site_id The view is as follows:- class DeleteDevice(DeleteView): model = Device template_name = "home/delete_confirmation.html" @method_decorator(user_passes_test(lambda u: u.has_perm('config.delete_device'))) def dispatch(self, *args, **kwargs): self.site_id = self.kwargs['site_id'] self.site = get_object_or_404(Site, pk=self.site_id) return super(DeleteDevice, self).dispatch(*args, **kwargs) def get_success_url(self, **kwargs): return reverse_lazy("config:site_device_overview", args=(self.site_id)) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) deletable_objects, model_count, protected = get_deleted_objects([self.object]) context['deleted_objects']=deletable_objects context['model_count']=dict(model_count).items() context['protected']=protected context['active_devices']='class="active"' context['cancel_url'] = reverse('config:device_details', args=[self.object.id, self.site_id]) return context Below error which looks like it has split the site id into 3 digits File "/usr/local/lib/python3.6/site-packages/django/urls/resolvers.py" in _reverse_with_prefix 497. raise NoReverseMatch(msg) Exception Type: NoReverseMatch at /config/delete_device/192/101 Exception Value: Reverse for 'site_device_overview' with arguments '('1', '0', '1')' not found. 1 pattern(s) tried: ['config/devices/(?P<site_id>[0-9]+)$'] -
"An unknown FastCGI error ocurred" using FastCGI with Django on Windows Server
I am trying to run a Django application on a Windows Server VM hosted on Microsoft Azure. I'm using Python 3.6. I already made all the configurations in this Microsoft tutorial (https://docs.microsoft.com/en-us/azure/virtual-machines/windows/classic/python-django-web-app), but I still get an error message: "HTTP Error 500.0 - Internal Server Error" "An unknown FastCGI error occurred" here's my web.config: <configuration> <appSettings> <add key="WSGI_HANDLER" value="django.core.handlers.wsgi.WSGIHandler()" /> <add key="PYTHONPATH" value="C:\inetpub\wwwroot\tb_product" /> <add key="DJANGO_SETTINGS_MODULE" value="tb_project.tb_project.settings" /> </appSettings> <system.webServer> <handlers> <add name="Python FastCGI" path="*" verb="*" modules="FastCgiModule" scriptProcessor="c:\users\giorgecaique\appdata\local\programs\python\python36-32\python.exe|c:\users\giorgecaique\appdata\local\programs\python\python36-32\lib\site-packages\wfastcgi.py" resourceType="Unspecified" requireAccess="Script" /> </handlers> </system.webServer> </configuration> Can anyone help me? Cheers! -
Django - Filter based on number of times a field comes up
I have a model that tracks the number of impressions for ads. class Impression(models.Model): ad = models.ForeignKey(Ad, on_delete=models.CASCADE) user_ip = models.CharField(max_length=50, null=True, blank=True) clicked = models.BooleanField(default=False) time_created = models.DateTimeField(auto_now_add=True) I want to find all the user_ip that has more than 1000 impressions. How can I do that? I wrote a function for this but it is very inefficient and slow because it loops over every impression. def check_ip(): for i in Impression.objects.all(): if Impression.objects.filter(user_ip=i.user_ip).count() > 1000: print(i.user_ip) -
relation "blog_blog" does not exist - error in Django app
I am to write simple Django blog application. Django Version: 2.0.4 http://dpaste.com/0H62TQY - this is error output. ( I hope it's safe to show this file all over the Internet =) ) models.py look like from django.db import models from django.shortcuts import reverse from django.template.defaultfilters import slugify from django.utils import timezone class Blog(models.Model): author = models.ForeignKey('auth.User', on_delete=models.PROTECT) title = models.CharField(max_length=500) body = models.TextField() created_at = models.DateTimeField(default=timezone.now) slug = models.SlugField(default='', editable=False, unique=True, blank=False, null=False) class Meta: verbose_name_plural = "blog" def __str__(self): return self.title def get_absolute_url(self): kwargs = {'slug': self.slug} return reverse('blog_detail', kwargs=kwargs) def save(self, *args, **kwargs): self.slug = slugify(self.title) super().save(*args, **kwargs) views.pylook like from django.views.generic import DetailView, ListView from .models import Blog class HomeView(ListView): template_name = 'blog/blog.html' queryset = Blog.objects.order_by('-created_at') class BlogDetail(DetailView): model = Blog template_name = 'blog/blog-detail.html' urls.py look like from django.urls import path, re_path from . import views urlpatterns = [ path(r'', views.HomeView.as_view(), name='home'), re_path(r'^(?P<slug>[-\w]*)/$', views.BlogDetail.as_view(), name='blog_detail'), ] This is my blog.html {% for blog in blog_list %} <div class="item-blog-txt p-t-33"> <h4 class="p-b-11"> <a class="m-text24" href="{{ blog.get_absolute_url }}"> {{ blog.title }} </a> </h4> <div class="s-text8 flex-w flex-m p-b-21"> <span> {{ blog.author }} <span class="m-l-3 m-r-6">|</span> </span> </div> <p class="p-b-12"> {{ blog.body|linebreaksbr }} </p> <a class="s-text20" href="{{ blog.get_absolute_url }}"> Continue …