Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django's not working when implement a custom middleware to check whether user is active and check if user is login then it can be enter in the site
django's not working when implement a custom middleware to check whether user is active and check if user is login then it can be enter in the site otherwise it will back to the login page my middleware is i just try to implement that for check if user is not login then it can not enter in to site from django.shortcuts import render, redirect from django.contrib.auth.forms import AuthenticationForm class FilterMiddleware(object): # Check if client is allowed def process_request(self, request): if not request.user.is_authenticated() : form_class = AuthenticationForm template_name = 'music/login_form.html' form = form_class(None) return render(request, template_name, {'form': form}) return super(FilterMiddleware, self).dispatch(request) and settings.py is MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'music.middleware.filter_middleware.FilterMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware' ] -
ApiError: Incorrect username or password YouTube Account Authentication error
I am new for stack overflow and also Python Django with YouTube API, I am trying to upload video from my own website using django-youtube 0.2 python-package. I am using django 7.11, My project is configured as https://github.com/laplacesdemon/django-youtube per this link. Note: The Account Authentication only work with Demo Gmail account but when i try to create account for Live site it's don't work and all the credentials and settings are correct. Any one know the YouTube API Help email or Contact Information to Solve this issue then let me know thanks. settings.py INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'django_youtube' ) YOUTUBE_AUTH_EMAIL = "xxxxx@gmail.com" YOUTUBE_AUTH_PASSWORD = "xxxxxxx" YOUTUBE_DEVELOPER_KEY = 'AIzaSyANLDSlzAx8qIWIRzLP_rG0V1FAZGhmrBE' YOUTUBE_CLIENT_ID = '1027445482699-1ujfqumakstu1hsd315baq61nms3u6jo.apps.googleusercontent.com' api.py import os import gdata.youtube.service from django.conf import settings from django.utils.translation import ugettext as _ YOUTUBE_READ_WRITE_SCOPE = "https://www.googleapis.com/auth/youtube" YOUTUBE_API_SERVICE_NAME = "youtube" YOUTUBE_API_VERSION = "v3" class OperationError(BaseException): """ Raise when an error happens on Api class """ pass class ApiError(BaseException): """ Raise when a Youtube API related error occurs i.e. redirect Youtube errors with this error """ pass class AccessControl: """ Enum-like structure to determine the permission of a video """ Public, Unlisted, Private = range(3) class Api: """ Wrapper for Youtube API See: https://developers.google.com/youtube/1.0/developers_guide_python … -
asynchronous SOAP api call using Python
My purpose is to make a request from async SOAP api that take a data from pre-configured database and store it to another pre-configured database. I am using suds SOAP client for it. >>> from suds.client import Client >>> url="http://abcdjkfdsfjlkl?WSDL" >>> client=Client(url) >>> result=client.service.execute('City', 'Utility','147') >>> print result None my api call going well and I am getting data in my database too, but I am not getting response from it whether my task it completed,error or in-progress, it might be possible that the way I am using that is wrong, Please suggest me the proper way of doing this. Note:- I developing project in python 2.7 using django 1.8, In above code I just checked api call by python terminal. -
Django Restful Framework Authentication HTTP Post Error
I was following the Django restful framework tutorial and I came across a error at the "Authenticating with the API" step. I've retraced myself however can't seem to see where I went wrong. Basically when I go to post to my API i get an error see below. Ideally I would also like to setup permissions which state "access denied" unless object owner - any advice on this would be greatly appreciated. http -a jimmynos:password POST http://127.0.0.1:8000/snippets/ code="print 789" Some of the error: IntegrityError at /snippets/ NOT NULL constraint failed: snippets_snippet.owner_id Request Method: POST Request URL: http://127.0.0.1:8000/snippets/ Django Version: 1.9.9 Python Executable: /Users/james/Documents/django/tutorialSerialization/env/bin/python Python Version: 2.7.10 Python Path: ['/Users/james/Documents/django/tutorialSerialization/tutorial', '/Users/james/Documents/django/tutorialSerialization/env/lib/python27.zip', '/User views.py from snippets.models import Snippet from snippets.serializers import SnippetSerializer from django.http import Http404 from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from django.contrib.auth.models import User from snippets.serializers import UserSerializer from rest_framework import generics from rest_framework import permissions from snippets.permissions import IsOwnerOrReadOnly class UserList(generics.ListAPIView): queryset = User.objects.all() serializer_class = UserSerializer class UserDetail(generics.RetrieveAPIView): queryset = User.objects.all() serializer_class = UserSerializer class SnippetList(APIView): """ List all snippets, or create a new snippet. """ permission_classes = (permissions.IsAuthenticatedOrReadOnly,IsOwnerOrReadOnly,) def get(self, request, format=None): #snippets = Snippet.objects.all() snippets = Snippet.objects.filter(owner=self.request.user) serializer = SnippetSerializer(snippets, … -
djnago celery flower socket error: address already in use
In order to debug hanging workers of celery I installed flower on both my development and production server. On development it is installed correctly and I can access flower dashboard using port 5555. On production after installation when I try to start flower server by doing celery flower error came which says socket.error: [Errno 98] Address already in use. To debug I tried to see what is running on port 5555 in both development and production. On development without celery flower server running, nothing returns. On development with celery flower server running following comes: which seems fine. On production server without celery flower server running following comes: This is quite confusing as even though I haven't run celery flower, its process is already running and I am not able to access the dashboard. -
Django Channels TokenAuthentication instead of http_session
I am using Django-Channels for a SPA Project, and the entire website is built on top of TokenAuthentication in DjangoRestFramework. I would like to authenticate the websocket channels somehow with the Token but I am not sure what the best practice for that would be. -
How to Implement linked zooming, panning in bokeh plots when embedded as Components
I have a django web application where we render multiple bokeh plots (timeseries) for usability it is required that the x-axis of all plots is linked between all plots (time). I had the following solution (pseudocode) that worked with bokeh-1.10.0 plot_1 = figure() plot_1.line([0,1,2],[1,2,3]) plot_2 = figure() plot_2.line([0,1,2],[1,3,9]) plot2.x_range = plot_1.x_range # This line causes the linking script1, div1 = components(plot_1) script2, div2 = components(plot_2) Then the div1, div2 and the scripts were embedded into a django template. Bokeh-js did the magic so when plot_1 is zoomed plot_2 is zoomed simultaneously. Since the x_range objects have the same id. But with bokeh-0.12.1 it seems that bokeh js the second plot is not effected by the zooming events on the first plot and vice versa. How can i achieve linked panning and zooming in a similar embedding setup? -
Change Django Rest Framework serializers output structure?
I have a Django model like this: class Sections(models.Model): section_id = models.CharField(max_length=127, null=True, blank=True) title = models.CharField(max_length=255) description = models.TextField(null=True, blank=True) class Risk(models.Model): title = models.CharField(max_length=256, null=False, blank=False) section = models.ForeignKey(Sections, related_name='risks') class Actions(models.Model): title = models.CharField(max_length=256, null=False, blank=False) section = models.ForeignKey(Sections, related_name='actions') And serializers like that : class RiskSerializer(serializers.ModelSerializer): class Meta: model = Risk fields = ('id', 'title',) class ActionsSerializer(serializers.ModelSerializer): class Meta: model = Actions fields = ('id', 'title',) class RiskActionPerSectionsSerializer(serializers.ModelSerializer): risks = RiskSerializer(many=True, read_only=True) actions = ActionsSerializer(many=True, read_only=True) class Meta: model = Sections fields = ('section_id', 'risks', 'actions') depth = 1 def to_representation(self, instance): response_dict = dict() response_dict[instance.section_id] = { 'actions': HealthCoachingActionsSerializer(instance.actions.all(), many=True).data, 'risks': HealthCoachingRiskSerializer(instance.risks.all(), many=True).data } return response_dict When accessing the RiskActionPerSectionSerializer over a view, I get the following output: [ { "section 1": { "risks": [], "actions": [] } }, { "section 2": { "risks": [], "actions": [] } }, ..... ] It s fine but I would prefer to have that : [ "section 1": { "risks": [], "actions": [] }, "section 2": { "risks": [], "actions": [] } ..... ] Also why is it returning an array by default [] and not an object for example like: { "count": 0, "next": null, "previous": null, … -
The view showname.views.delete didn't return an HttpResponse object. It returned None instead
I have the next code in delete generic class: class delete(DeleteView): def get(self, request, *args, **kwargs): def get_absolute_url(self): return reverse('index') There is the url patttern: url(r'^$', views.indext.as_view(), name='index'), As i understand from the decumentation, if i want to redirect thr user to the index when he tryies to approach the page through the url by himself, i Call "get" which defind what to do when "get" messege sent, and then "get_absolute_url" with "reverse" to do the same method that "url" in html pages does. But it doesnt work. why it returning None as the page sayes? -
python error AttributeError: 'str' object has no attribute 'setdefault'
I'm trying to run the django project using this command. python manage.py runserver 8080 But everytime I'm trying to run I faced the such a error. Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/Users/admin/.virtualenvs/seethisproperty/lib/python2.7/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/Users/admin/.virtualenvs/seethisproperty/lib/python2.7/site-packages/django/core/management/__init__.py", line 327, in execute django.setup() File "/Users/admin/.virtualenvs/seethisproperty/lib/python2.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/admin/.virtualenvs/seethisproperty/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/Users/admin/.virtualenvs/seethisproperty/lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/admin/.virtualenvs/seethisproperty/lib/python2.7/site-packages/django/contrib/auth/models.py", line 4, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/Users/admin/.virtualenvs/seethisproperty/lib/python2.7/site-packages/django/contrib/auth/base_user.py", line 49, in <module> class AbstractBaseUser(models.Model): File "/Users/admin/.virtualenvs/seethisproperty/lib/python2.7/site-packages/django/db/models/base.py", line 108, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "/Users/admin/.virtualenvs/seethisproperty/lib/python2.7/site-packages/django/db/models/base.py", line 307, in add_to_class value.contribute_to_class(cls, name) File "/Users/admin/.virtualenvs/seethisproperty/lib/python2.7/site-packages/django/db/models/options.py", line 263, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "/Users/admin/.virtualenvs/seethisproperty/lib/python2.7/site-packages/django/db/__init__.py", line 36, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File "/Users/admin/.virtualenvs/seethisproperty/lib/python2.7/site-packages/django/db/utils.py", line 209, in __getitem__ self.ensure_defaults(alias) File "/Users/admin/.virtualenvs/seethisproperty/lib/python2.7/site-packages/django/db/utils.py", line 181, in ensure_defaults conn.setdefault('ATOMIC_REQUESTS', False) AttributeError: 'str' object has no attribute 'setdefault' I tried python2(python2.7.11) and python3(python3.5.1) with virtualenvwrapper. I think it's not the bug of the project source. but something missed in environment configuration. But I can't figure out what the problem is. Please help me fix it. Thanks in advance. -
I got confused between the all "url" functiond in django
I searched in the internet for a proper explanation to the next methods: "Redirect(), get_absolute_url(), Reverse, Reverse_lazy" They are all the same? so why django make them all? -
Vagrant unable to reflect changes in code
I am using vagrant for one of my django project. I have used rsync in vagrant file to sync folders between host and guest machine. I am able to run project in my host machine browser as well. Issue is, when I do changes in code and sync the code using vagrant rsync it works perfect and I can see the changes in guest machine using ssh BUT I am not able to see those changes in browser after refresh. vagrant file . . . Vagrant.configure("2") do |config| config.vm.synced_folder ".", "/home/vagrant/project", type: "rsync", create: "true", rsync__exclude: ".git/" end Its strange that I need to do vagrant reload each time to see those changes in browser. what is an issue with sync Need help. -
Handling Push notifications in android using GCM and Django
i'm new to android programming, there are two types of push notifications in my app (for eg- one for Notices and other for News), how can i differentiate these notifications and how can i open different activities by clicking them separately? -
RecursionError at /person/ maximum recursion depth exceeded in __instancecheck__
My inclusion tag gives "RecursionError at /person/ maximum recursion depth exceeded in instancecheck" error. Full traceback: Template error: In template /home/ohid/test_venv/alumni/member/templates/member/person_list.html, error at line 15 my person_list.html: {% extends 'alumni/base.html' %} {% block content %} <h2>Members</h2> <table> <tr> <th>sl.</th> <th>Name and Position</th> <th>Photo</th> <th>Organisation & Address</th> <th>Contact</th> </tr> {% for person in persons %} <tr> <td>{{forloop.counter}}.</td> <td>{{person.name}}<br> {{person.present_position}} </td> <td><a href="{% url 'member:person-list' %}"> <img src="{{ person.photo_url|default_if_none:'#'}}" class="img-responsive"> </a></td> <td> {{person.organization}}<br> {{person.address}} </td> <td> {{person.tele_land}}<br> {{person.tele_cell}}<br> {{person.email}} </td> </tr> {% endfor %} </table> {% endblock %} my inclusion tag: from django import template from ..models import Person register = template.Library() @register.inclusion_tag('member/person_list.html') def get_person_list(): return {'persons': Person.objects.all()} my person model: class Person(models.Model): name = models.CharField(max_length=128) present_position=models.CharField(max_length=100) organization= models.CharField(max_length=150,blank=True) address = models.CharField(max_length=150, blank=True) tele_land = models.CharField(max_length=15,blank=True) tele_cell = models.CharField(max_length=15, blank=True) email = models.EmailField(max_length=70, blank=True, null=True, unique=True) photo= ResizedImageField(size=[60, 60],crop=['middle', 'center'],upload_to='persons/%Y/%m/%d/',null=True, blank=True, editable=True, help_text="Person Picture") category = models.ForeignKey('Membership', on_delete=models.CASCADE) member_since = models.DateField(blank=True) image_height = models.PositiveIntegerField(null=True, blank=True, editable=False, default="100") image_width = models.PositiveIntegerField(null=True, blank=True, editable=False, default="100") def get_absolute_url(self): return reverse('member:detail', kwargs={'pk': self.pk}) my urls: app_name = 'member' urlpatterns = [ # Member url(r'^$', views.IndexView.as_view(), name='index'), url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'), url(r'member/add/$', views.AlbumCreate.as_view(), name='member-add'), url(r'^person/$', views.PersonListView.as_view(), name='person-list'), ] How to avoid maximum recursion depth? Could anyone suggests the … -
How to use Signal after a Save is called
from django.db.models.signals import post_save from django.dispatch import receiver class Connector(models.Model): connector_id = models.AutoField(primary_key = True) name = models.CharField(max_length=255, null=False,unique=True) description = models.TextField(null=True) class ConnectorAud(models.Model): id = models.AutoField(primary_key = True) ref_connector_id = models.CharField(max_length=255, null=False) name = models.CharField(max_length=255, null=False,unique=True) description = models.TextField(null=True) @receiver(post_save, sender=Connector) def create_connector_audit_trail(sender, **kwargs): connector = ConnectorAud( ref_connector_id = kwargs.get('connector_id'), name = kwargs.get('name'), description = kwargs.get('description',''), ) connector.save() This causes Connector() to run twice when connector.save() is run How to solve this problem? -
How to display modal from bootstrap by checking cookie in javascript
I am trying to set a cookie only when a button in the modal(bootstrap) is clicked. I have written the below code to set and get cookies but i am going somewhere wrong because the cookies are set automatically when the page is loaded and the modal is not displayed at all. I need to set it only when the button is clicked. I have no idea how the cookies are set when the modal does not even show up to click the #setcookie_btn. Any ideas where this code goes wrong ? $('#setcookie_btn').click(setCookie('{{user.get_username}}', true, 0.042)); function setCookie(cname, cvalue, exdays) { var d = new Date(); d.setTime(d.getTime() + (exdays*24*60*60*1000)); var expires = "expires="+ d.toUTCString(); document.cookie = cname + "=" + cvalue + "; " + expires; } function getCookie(cname) { var name = cname + "="; var ca = document.cookie.split(';'); for(var i = 0; i <ca.length; i++) { var c = ca[i]; while (c.charAt(0)==' ') { c = c.substring(1); } if (c.indexOf(name) == 0) { return c.substring(name.length,c.length); } } return ""; } var cookie_val = getCookie('{{user.get_username}}'); $(window).load(function() { if(cookie_val == false || "" ) { $('#myModal').modal({backdrop: 'static', keyboard: false}); } }); </script> -
SSO with Django 1.9 + djangosaml2 + ADFS 2.0
I'm install and configure ADFS 2.0 as Idp and Django project as SP using djangosaml2. Django project deploing on IIS 7.5. django saml2 config: SAML_CONFIG = { # full path to the xmlsec1 binary programm 'xmlsec_binary': 'C:\\Program Files\\xmlsec1\\xmlsec1-1.2.20-win32-x86\\bin\\xmlsec1.exe', # your entity id, usually your subdomain plus the url to the metadata view 'entityid': 'https://sp.corp.com/saml2/metadata/', # this block states what services we provide 'service': { # we are just a lonely SP 'sp' : { 'authn_requests_signed': "true", 'name': 'SP', 'name_id_format': NAMEID_FORMAT_EMAILADDRESS, 'endpoints': { # url and binding to the assetion consumer service view # do not change the binding or service name 'assertion_consumer_service': [ ('https://sp.corp.com/saml2/acs/', saml2.BINDING_HTTP_POST), ], # url and binding to the single logout service view # do not change the binding or service name 'single_logout_service': [ ('https://sp.corp.com/saml2/ls/', saml2.BINDING_HTTP_REDIRECT), ('https://sp.corp.com/saml2/ls/post', saml2.BINDING_HTTP_POST), ], }, # attributes that this project need to identify a user 'required_attributes': ['email'], # attributes that may be useful to have but not required 'optional_attributes': ['surname'], }, }, # where the remote metadata is stored 'metadata': { 'local': [os.path.join(BASE_DIR, 'FederationMetadata.xml')], }, # set to 1 to output debugging information 'debug': 1, # certificate 'key_file': os.path.join(BASE_DIR, 'iispk.pem'), # private part 'cert_file': os.path.join(BASE_DIR, 'iiscert.pem'), # public part } On adfs … -
How to integrate django-machina (a django based forum solution) into django website?
I'm trying to integrate django-machina forum solution (https://github.com/ellmetha/django-machina) into my django website. However, I cant find a decent guide for doing the integration after downloading the repository, pip installing django-machina and installing the dependencies. I've checked the django-machina documentation, github and google. Can anyone guide me on this integration issue? Also, what are the other forum building solutions out there that can easily be integrated into a python django website? Even basic features are ok, as long as it lets me easily integrate and I dont have to separately login into the forum and website. Thanks -
Check in DeleteView if its post or get? django
Im trying to check either a user tried to enter a url by himself or he follows the ruls and put the values nedded in the form i build for him.. In some Ungeneric class, I can check that thing - if request.method == 'GET': But in DelteView i cant do that thing so i dont know how to prevent from the user from doing bad things by input url by himself. How can i use a function that does the same in generic View and checks if the user enter a url by himself or fill in the form? -
Django Celery Periodic Task ignoring contrab
After an update it appears celery has stopped to work like it should. I have periodic tasks per day and from 6-22. All of the tasks running from 6-22 run every 5 minutes for no reason. I changed the task from running every hour to running from 6-22. The every hour function wasn't working either. I tried: minute=0 hour=6-22, minute=0, hour='*/3,8-17' and completely written like below. The last one i copied from the docs because i thought maybe this would work. @periodic_task( run_every=(crontab(minute=0, hour='6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22')), queue='feed', name="feed_update", ignore_result=True ) def feed_update(): """ checks for feed updates """ feed_update_for_all_users() logger.info("Feed Update complete") According to the Docs these are all valid contrab vars. Why isn't it working properly? -
Send Email Issue - Google Compute Engine VM
I am trying to send an Email from python code. The Code works fine when tested on my local Server. But when I deploy these changes on my Google Compute Engine VM, the Email sending stops and Connection Error starts coming. Error Trace: File "/usr/local/lib/python2.7/dist-packages/django/core/mail/message.py", line 342, in send return self.get_connection(fail_silently).send_messages([self]) File "/usr/local/lib/python2.7/dist-packages/django/core/mail/backends/smtp.py", line 100, in send_messages new_conn_created = self.open() File "/usr/local/lib/python2.7/dist-packages/django/core/mail/backends/smtp.py", line 58, in open self.connection = connection_class(self.host, self.port, **connection_params) File "/usr/lib/python2.7/smtplib.py", line 256, in __init__ (code, msg) = self.connect(host, port) File "/usr/lib/python2.7/smtplib.py", line 316, in connect self.sock = self._get_socket(host, port, self.timeout) File "/usr/lib/python2.7/smtplib.py", line 291, in _get_socket return socket.create_connection((host, port), timeout) File "/usr/lib/python2.7/socket.py", line 571, in create_connection raise err error: [Errno 110] Connection timed out These are the Email settings in settings.py File: EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.zoho.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'abc@abc.in' EMAIL_HOST_PASSWORD = 'abcxxxabc' DEFAULT_FROM_EMAIL = 'abc@abc.in' DEFAULT_TO_EMAIL = 'def@abc.in' Can someone please suggest what could be the cause for this behavior ? And how can this issue be resolved ? Thanks, -
Save data to database
I want to make a dropdownlist and want to store data to DB after clicking on submit button. There is a field named ChoiceField, Is it used to make dropdownlist in django? Is it possible through choicefield, if it is possible please give me an example, how I can do this. -
Django1.11 - URLconf does not appear to have any patterns
I'm a new user of django and i have some difficulties. I follow a Django 1.8 tutorial and i have Django1.11. the problem is about urls.py files & patterns Here my code, blog/urls.py: from django.conf.urls import url from . import views urlpattern = [ url(r'^accueil/$', views.home, name='home'), ] first/urls.py: from django.conf.urls import url include urlpattern = [ url(r'^blog/', include('blog/urls')), ] And when i use runserver command, it display : URLconf '<module 'blog.urls'>'does not appear to have any patterns in it I read somewhere that patterns are removed since 1.10 and it's an old syntax now but i don't found the solution. Any idea ? -
How to create requirements.txt if project does not contain requirements.txt
I am started with django project for practices but realise that, If I'm share django project without requirements.txt should my friend able to install requirements. I'm just curious to know is it possible to install required package without having requirements.txt? -
Can't read json in TemplateView
abc.json: { "employee": { "name": "Rose" } } views.py class employee_ViewDetails_TemplateView(TemplateView): template_name = 'employee.djhtml' def get_data(self, **kwargs): json_data=json.loads(open(BASE_DIR+'/app/jsonRead/abc.json').read()) context = {'ref':json_data}, return render_to_response(request,self.template_name,context) I am able to see the template is fully loaded but json is not able to load. May be render_to_response is not the suitable method to render inside class based view.