Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't get user in template using django.contrib.auth
What am i doing wrong? I just want the username of the user. I am logged so i don't know why it's not working. views.py from django.contrib.auth.models import User def check_user(request): data = dict() user = User.objects.all() data['user'] = user return render(request, 'check_user.html', data) urls.py url(r'^check_user/$', views.check_user, name='check_user'), check_user.html {{ request.user.is_authenticated }} {% if user.is_authenticated %} <p>Welcome, {{ user.username }}. Thanks for logging in.</p> {% else %} <p>Welcome, new user. Please log in.</p> {% endif %} And i'm getting this: CallableBool(True) Welcome, new user. Please log in. when i should get: Welcome, admin. Thanks for logging in. -
Sharing only the templates without giving access to source code
I'd like to share the templates of the website I've done with a graphist. My problem is that I dont want him to access the Python code at all. It's easy to share a folder and give access to it through sftp. I was wondering if it were possible given a right tag, to access my Python code. I know for example that with Php/Smarty or with Php/Twig, you can execute Php code, which means you can read whatever you want, including all the source files (I've done it to test). So sharing Php templates files and thinking "my source code is safe" is a mistake. I'm a beginner with Django, and I'm wondering if there's a way to access the source files through Django template system / or not? -
How to remove old static files while keep on serving until deployment succeeds?
I'm having an issue with static files piling up on S3 since i'm using the ManifestFilesMixin mixin to give static files a unique name (so clients are forced to load the new content). Since the name is different on each version (duhhh) it's written next to old version of the same file. Then also i don't like to use the --clear flag on collectstatic since this will (i expect) remove the current files even when deployment has not succeeded yet. I thought to manually run: python manage.py collectstatic --clear but this seems to not remove the old versions from the bucket? Anyone thoughts on this? Paul -
what admin style are you using for django projects? [on hold]
what admin style are you using ? -
Use S3 for staticfiles with Django + django-storages and Heroku
I have been struggling with this for days. First I create an S3 bucket 4f2xivbz443 and generated Access Keys (Access Key ID and Secret Access Key). I installed django-storages https://django-storages.readthedocs.io/en/latest/ and followed the instructions on how to add and setup Amazon S3. But I am missing something, because I get no errors when setting DEBUG=False in settings.py and deploying to Heroku. Nothing gets transferred to my S3 bucket, it is also empty. Here comes all the code. settings.py (Amazon S3 settings are added in at the end Django settings for helloworld project on Heroku. For more info, see: https://github.com/heroku/heroku-django-template For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os import dj_database_url # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = "=ax=ka-emu33ivw-y^u00p8#uvop#-ag#+4pm_s4-=da^chbuk" # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', # Disable Django's own staticfiles handling in favour of WhiteNoise, for … -
How to create two columns from a QuerySet in a Django template
def get_queryset(self): return AnnualMean.objects.values("Site", "url") With the above QuerySet from my views.py file, I can make a list of URL links appear on a page as one long column using this code: {% for value in object_list %} <ul><a href="/sites/{{value.url}}/">{{value.Site}}</a></ul> {% endfor %} It would be much better to have the list split into halves across two columns. I have spent a long time trying and looking at related forum posts. I think my difficulties might lie with with the html tags. Is there any way I can achieve what I am trying to do? -
Using Aggregation API Django
I have a simple task of aggregating some values from database, but the problem is that I need to do it in another django application. I need to aggregate Sum of cost, price and average for each month, and display it in a table. I'm using generic ListView so I can aggregate this, so simple example. in views.py i have: from django.views.generic import ListView from django.db.models import Sum, Avg from projects_app.models import Project class ProjectStatisticsList(ListView): model = Project template_name = 'statistics_app/statistics_list.html' def get_context_data(self, **kwargs): context = super(ProjectStatisticsList, self).get_context_data(**kwargs) context["price_aux"] = Project.objects.all().aggregate(Sum("price_aux")) return context and in template I have: <tr> <th class="align-left">{% trans 'Project income' %}</th> <th class="align-left">{{ total.price_aux }}</th> </tr> My problem is that I'm not getting anything on the template, so I'm wondering if I'm doing the right thing, is there a better way. -
render two views to a single html template
I have two views and I want to render those views to a single html page. I know how to render a single view to a html page but dont know know how to render two views to a single html page views.py file from django.shortcuts import render from django.http import HttpResponse from app.models import * # Create your views here. def collegeview(request): if request.method == 'POST': form = collegeform(requst.POST) if form.is_valid(): form.save() return HttpResponse('its done here') else: form = collegeform() return render(request, 'about.html', {'form':form}) def schoolview(request): if request.method == 'POST': f = schoolform(requst.POST) if f.is_valid(): f.save() return HttpResponse('its done here') else: f = schoolform() return render(request, 'about.html', {'f':f}) about.html <html> <body> <h1>its working </h1> first view <br> <form action = '' method = 'POST'> {% csrf_token %} {{form.as_p}} <input type='submit' name='submit'> </form> 2nd view<br> <form action='' method='POST'> {% csrf_token %} {{f.as_p}} <input type='submit' name='submit'> </form> </body </html> single view working corresponding to the url. -
Access angular controller from Django tamplate
Project contains three folders say App1, App2 and Folder1. App1 and App2 are django apps,Folder1 is not an app. App1 contains all the static files required for angular. Folder1 contains a template directory which contains a file text1.html (uses Django templating) I want to access a angular controller defined in App1 from text1.html -
Heroku "Error R14 (Memory quota exceeded)" with Django AJAX Request
So I know there were previous questions asked about this, but I think my situation may be a bit different since I am using Django filters on a large data set. I have a table with about 35,000 rows worth of products, and the issue is that when my site makes an AJAX call using an infinite scroll layout, the request usually returns a 503 error (sometimes it works after a long time). Any ideas how to optimize my code? Or do I need to upgrade my Heroku configurations? My configuration: Python 3.5.0 Django 1.10.5 Heroku PostgreSQL 9.6.1 ($9 Hobby plan) Heroku ($7 Hobby Basic plan) Waitress (server) 1.0.2 views.py class InfiniteResultsView(LoginRequiredMixin, View): def get(self, request): search_filters['status'] = Product.ACTIVE if search_terms: search_filters['title__icontains'] = search_terms if search_categories_slugs: for s in search_categories_slugs: q_objects |= Q(category__slug=s) products = Product.objects.filter(q_objects, **search_filters).select_related() products = paginate(queryset=products, page=page, amount=6, force_cutoff=True, force_shuffle=True) return render(request, '_includes/_products.html', {'products': products}) Heroku LOG 2017-02-09T06:44:43.277422+00:00 heroku[web.1]: Process running mem=648M(126.5%) 2017-02-09T06:44:43.277526+00:00 heroku[web.1]: Error R14 (Memory quota exceeded) -
What lenguage(S) should I learn for this project?
I want to do a project for myself. It is a webapp where it is an online store, and I wanted to be guided to know what language to learn and which framework to use to do so. My webapp I want you to have these characteristics Users who can have an account and log in: Having login account where you can view your purchases, make your purchases and make invoice. Automate the quote, (where they send in a form of what they want to quote from the list of products, and automatically receive them to their mail the quote and payment data) have an inventory in the store of the webapp linked to database, so you do not have to change the stock manually And the most important thing for me, to do scrapping of the products of the supplier's store. My supplier has hundreds of thousands of products and it is simply impossible to manually upload them and update stock and prices manually daily, so on the page of my provider I have an account that gives me access to the online store where the details of their products appear in lists , And I would like to … -
Django JSON file to Pandas Dataframe
I have a simple json in Django. I catch the file with this command 'data = request.body and i want to convert it to pandas datarame JSON: { "username":"John", "subject":"i'm good boy", "country":"UK", "age":25 } I already tried pandas read_json method and json.loads from json library but it didn't work. -
How call this backend coding?
Lets say I've following table: Table: Posts Fields: id, name, content And another table: Table: Images Fields: id, post_id, url Normally, I can create CRUD for each of them. User first create post and save it. Then by Images table CRUD user can add as many as images to posts. But what if requirement is no create CRUD for images. But inside Posts CRUD. I mean while creating (filling Posts fields) there is button which labeled "add images". Then when user add images via that button. Finally when press on "create post" backend code should create posts and images. How you call it? I couldn't find any tutorial and because of my English I couldn't describe it enough on Google search. -
what is the best way to use elasticsearch in Django Restframework
i am very confused that how to use elasticsearch in django restframework. please help me. -
django-bootstrap3: changed theme_url but Bootswatch theme not loading?
I'm trying to use the bootswatch flatly theme. I followed the instructions given on the documentation regarding updating the settings. I've added the following to my project's settings.py: BOOTSTRAP3 = { 'theme_url': 'https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/flatly/bootstrap.min.css', } I've also added the following to my project's base.html template, between the head tags: {% load bootstrap3 %} {% bootstrap_css %} {% bootstrap_javascript %} {% bootstrap_messages %} index.html template: {% extends "base.html" %} {% load i18n %} {% load bootstrap3 %} {% bootstrap_css %} {% block content %} Hello World {% endblock %} However, the theme is not reflected when I reload my index page. Is there something I'm doing wrong? -
Uncaught TypeError: $(...).mywidget is not a function(…)
Hi iam loading an external script in shopify. <script type=text/javascript src=https://www.domain.com/static/../survey.min.js></script> and i have a jquery in my body as <script type=text/javascript>$(document).ready(function () { $('#someID').mywidget({val: data}); }); but iam getting Uncaught TypeError: $(...).mywidget is not a function(…) mywidget is a function in the external js file . it work fine in normal html file any suggestions? -
How to show system notifications from Django app?
I have a running Django app in my office. My boss wants to receive notifications like the ones Facebook shows you, kind of like system notifications even when you are not logged in or the Facebook tab is not open. I feel like I have to handle a couple of things at least: Authorization and authentication check before showing the notification Showing the notification regardless of the browser or OS he is using Can anyone guide to me to the correct tutorial / docs to follow to achieve this result? Is there a third party Django app that could help me to achieve this? P.S. I am comfortable in using jQuery but that is my extent of JS. -
Facebook chatbot send back repeatedly Django
I am beginner in django and facebook bot. I have doing facebook chatbot with python and I have a small code to send message back to facebook. def post_facebook_message(fbid, recevied_message): post_message_url = 'https://graph.facebook.com/v2.6/me/messages?access_token=%s'%PAGE_ACCESS_TOKEN response_msg = json.dumps({"recipient":{"id":fbid}, "message":{"text":recevied_message}}) status = requests.post(post_message_url, headers={"Content-Type": "application/json"},data=response_msg) I call that method from other method (let say method A). If it got error in method A, it always call post_facebook_message again and again (it never stop). Part of method A is shown below. I don't use for-loop to send message also. objTwo = TwoCharacters.objects.filter(lucky_number=first_two_letters, times=inputTimes,lucky_alphabet=inputAlphabet).first() if objTwo is None: post_facebook_message(facebookSenderID, "Some text") -
How to pass objects to a TemplateView?
I am just learning CBVs and having a tough time with passing an object to a TemplateView. This has been pretty demoralizing as I know this should be very basic. Here is my views.py: from __future__ import absolute_import from django.views import generic from company_account.models import CompanyProfile class CompanyProfileView(generic.TemplateView): template_name = 'accounts/company.html' def get_context_data(self, **kwargs): context = super(CompanyProfileView, self).get_context_data(**kwargs) return CompanyProfile.objects.all() And here is my Models.py: from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User from django.core.urlresolvers import reverse class CompanyProfile(models.Model): company_name = models.CharField(max_length=255) def __str__(self): return self.company_name Here is urls.py urlpatterns = [ url(r'^accounts/companyprofile/$', CompanyProfileView.as_view()), ] And finally, here is the template: {% extends '_layouts/base.html' %} {% block title %}Company Profile{% endblock %} {% block headline %}<h1>Company Profile</h1>{% endblock %} {% block content %}{{ CompanyProfile.company_name }}{% endblock %} What am I missing? Thank you in advance for your help. -
Python unit test - Beginner
I am running Django 1.10 and Python 3.5. I have a basic form.py file that I am trying (and failing) to write the unit tests for. I must admit that I am finding the unit testing extremely difficult and need some help just to begin. I have made numerous attempts and I am now lost on the matter. I wouldn't normally ask such a basic question, but I am desperate and going around in circles. I am hoping that someone can start me off so I can have a starting point. Here is the code that requires the unit test (with the line numbers): 50: if 'achievement_type' in cd_adf and cd_adf['achievement_type'] == '': 51: self._errors['achievement_type'] = self.error_class([_("This field is required.")]) 52: elif 'achievement_type' in cd_adf and cd_adf['achievement_type'] == display_types.WRITE_MY_OWN_ACHIEVEMENT_TYPE_DESCRIPTION: 53: if 'achievement_type_description' in cd_adf and len(cd_adf['achievement_type_description'].strip()) == 0: 54: self._errors['achievement_type_description'] = self.error_class([_("This field is required.")]) 55: else: 56: if 'achievement_type_description' in cd_adf and len(cd_adf['achievement_type_description'].strip()) > 0: 57: # remove the entered value and/or assign a default value, when the achievement type only requires minimum data. 58: cd_adf['achievement_type_description'] = None 59: return cd_adf Here is the coverage reference: Name Stmts Miss Cover Missing achievement_details_forms.py 28 4 86% 51, 53-54, 58 -
Can't get django-star-ratings to display to template
New to Django, feel like I'm close to figuring out where I'm going wrong here. I have been trying to pass the context to my template to no avail. In models I have: class Rate(models.Model): name = models.CharField(max_length = 140) ratings = GenericRelation(Rating, related_query_name= 'object_list') def __str__(self): return self.id And in views, def RateList(request): queryset = Rate.objects.filter(ratings__isnull=False).order_by('ratings__average') context= { "object_list": queryset, "title": "List" } return render(request, 'UploadApp/upload.html', context) and lastly, in my template I've put {% ratings object_list %} into the html as per the documentation. Not sure if I'm just overlooking some small detail, but I'm getting a 'str' object has no attribute 'meta' error when I try and load the page. Any help is appreciated, I'm at the hair pulling stage -
I need sample code of django form
i need index.html and form.py and views.py or anything else that is needed. please help me i want learn form And I developed it i read django doc and search in google -
Django view decorator accessing 'self'
I'm trying to call self in my decorator but I get errors. Some background first: I have the following models: Car(models.Model): user = ForeignKey(User) color = models.CharField(max_length=25) Location(models.Model): user = ForeignKey(User) city = models.CharField(max_length=25) I want to have URLs to edit the city/color like: /edit/<model-name>/<model-id>, but I want to ensure that this is only accessible if request.user is the same as model_instance.user. So I have the following views: class EditView(View): ThisModel = Model def get(self, request, model_id): instance = self.ThisModel.objects.get(id=model_id) if instance.user != request.user: return HttpResponseForbidden("You can't do this!") else: # edit here return HttpResponse("successfully edited") def get(self, request, model_id): instance = self.ThisModel.objects.get(id=model_id) if instance.user != request.user: return HttpResponseForbidden("You can't do this!") else: # return form return render(request, 'my_template.html', context={'form':form}) def post(request, model_id): instance = self.ThisModel.objects.get(id=model_id) if instance.user != request.user: return HttpResponseForbidden("You can't do this!") else: # save form return HttpResponse('Edit successful.') class EditCarView(EditView): ThisModel = Car class EditLocationView(EditView): ThisModel = Location Instead of repeating the instance=... lines common to both the get and post methods, I want to use a decorator. I tried this: def current_user_only(func): def _check_curr_user(view_func): def _view(self, request, model_id, *args, **kwargs): self.instance = self.ThisModel.objects.get(id=model_id) if self.instance.user != request.user: return HttpResponseForbidden("Forbidden.") else: return view_func(request, username, *args, **kwargs) … -
ImportError: No module named 'tasks'
I'm trying to get Celery working with django to setup scheduled tasks. I've tried looking over the first steps w/ Celery and the first steps w/ Django tutorials and neither has been working for me. Here's my project layout with relevant files: Python 3.5.1 Django 1.10 Celery 4.0.2 RabbitMQ 3.6.6 OTP 19.2 mysite/ (project name) polls/ (myapp) tasks ... mysite/ __init__ celery settings ... manage ... mysite/__init__.py: from __future__ import absolute_import, unicode_literals # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app __all__ = ['celery_app'] polls/celery.py: from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') app = Celery('mysite', backend='amqp', broker='amqp://guest@localhost//',include=['polls.tasks']) # Using a string here means the worker don't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) polls/tasks.py: # Create your tasks here from __future__ import absolute_import, unicode_literals from celery import shared_task @shared_task def … -
pip install django graphos succesful but import error
this must be a very simple question, seams Im missing something obvious... I did: sudo pip install django-graphos and got: Successfully installed django-graphos all good up to this point, then I went to settings.py and added: 'graphos', to installed apps but Im getting this error: ImportError: No module named graphos what Im missing?