Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create a live video interacting session using python?
I'm currently developing an e-learning website using python and django. In that, after the completion of each course we have to implement a live video interacting functionality between tutor and student. Is it possible to implement the same using any python package or do I need to integrate any third party plugin? Any advice is much appreciated. -
Why my celery task is not running?
I'm following this guide: http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html My proj.celery file: from __future__ import absolute_import, unicode_literals import os from celery import Celery from celery.schedules import crontab os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hc.settings') app = Celery('hc') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task def debug_task(a): print a app.conf.beat_schedule = { # Executes every Monday morning at 7:30 a.m. 'debug-every-minute': { 'task': 'tasks.debug_task', 'schedule': crontab(), 'args': ("BLa BLA BlA", ), }, } also, I've added periodic task into /admin/django_celery_beat/ I understand that it's makes not sense to use both app.conf.beat_schedule and periodic_task in admin but I don't see expecting entries after Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. (I expect that Bla bla will be written under that) Where I'm wrong? -
Save a foreign key in postgreSQL using python-django
I'm trying to a save a foreign key inside an object into my db using a form, but i get the error : 'Syntax isn't valid for integer', I discovered that postgreSQL save the foreign key as an id, how can i save it then? Here it is my code. Models.py : class treballador(models.Model): nom = models.CharField(max_length=150, null=False, unique=True) cognom = models.CharField(max_length=150, null=False) tipusDocID = models.CharField(max_length=3, choices=TIPUSDOC, null=False) docId = models.CharField(max_length=9, null=False) tlf_regex = RegexValidator(regex=r'^\d{9,9}$',message="Phone number must be entered in the format: '+999999999'. Up to 9 digits allowed.") tlf = models.CharField(validators=[tlf_regex], blank=True, max_length=9) # validators should be a list correu = models.EmailField(max_length=254) ciutat = models.CharField(max_length=150) dataDAlta = models.DateTimeField(auto_now_add=True) def __unicode__(self): return unicode(self.nom) or unicode(self.id) class despesa(models.Model): nomTreballador = models.ForeignKey(treballador, to_field='nom') tipusDeGast = models.CharField(max_length=3, choices=GASTOS) quantia = models.DecimalField(max_digits=5, decimal_places=2) data = models.DateTimeField() forms.py: class desModelForm(forms.ModelForm): data = forms.DateField(widget=DateInput(format='%d/%m/%Y'), label="Data de la despesa", input_formats=['%d/%m/%Y']) class Meta: model= despesa fields= ["nomTreballador","tipusDeGast","quantia","data"] def clean_despesa(self): despeses = self.cleaned_data.get("tipusDeGast") return despeses def clean_date(self): date = self.cleaned_data.get("data") return date def clean_quantia(self): quantia = self.cleaned_data.get("quantia") return quantia def clean_nom(self): nomTreballador = self.cleaned_data.get("nomTreballador") return nomTreballador def __init__(self, *args, **kwargs): super(desModelForm, self).__init__(*args, **kwargs) self.fields["nomTreballador"].queryset=treballador.objects.all().distinct() views.py: def home(request): form = desModelForm(request.POST or None) context = { "gast_form": form } if form.is_valid(): … -
Adding Extra Field to the Picture model of django-jquery-file-upload Plugin
I have been trying to add some extraa Field to the django-jquery-file-upload with its default field. Plugin repo I searched but all the answers are for previous django-version. For example i tried also this : Solution But the answer is 5 years old. I Need to Store more data in each Picture object, my Model look like this : class Picture(models.Model): """This is a small demo using just two fields. The slug field is really not necessary, but makes the code simpler. ImageField depends on PIL or pillow (where Pillow is easily installable in a virtualenv. If you have problems installing pillow, use a more generic FileField instead. """ user=models.ForeignKey(User) //added extra page=models.ForeignKey(Page,related_name='pages') //added extra story=models.ForeignKey(Story,related_name='stories') //added extra file = models.ImageField(upload_to="picture") //default in plugin model slug = models.SlugField(max_length=50, blank=True) //default in plugin model def __str__(self): return self.user.username+"->"+self.page.name @models.permalink def get_absolute_url(self): return ('upload-new', ) def save(self, *args, **kwargs): self.slug = self.file.name super(Picture, self).save(*args, **kwargs) def delete(self, *args, **kwargs): """delete -- Remove to leave file.""" self.file.delete(False) super(Picture, self).delete(*args, **kwargs) Please suggest what should i change. Or perhaps A Example would do better. -
Connect Django Project to a distant Mysql Database
I'm working on a Django Project on my localhost and I would like to use a distant MySQL Database. My localhost IP is : 172.30.10.54 My MySQL distant server is : 172.30.10.81 In my Django settings.py file, I wrote : DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'DatasystemsEC', 'USER': 'root', 'PASSWORD': '*****', 'HOST': '172.30.10.81', 'PORT': '3306', 'OPTIONS': { 'init_command': 'SET innodb_strict_mode=1', }, } } My Database name is : DatasystemsEC But, when I run : python manage.py migrate, I get this error : Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python2.7/site-packages/django/core/management/base.py", line 342, in execute self.check() File "/usr/local/lib/python2.7/site-packages/django/core/management/base.py", line 374, in check include_deployment_checks=include_deployment_checks, File "/usr/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 61, in _run_checks issues = run_checks(tags=[Tags.database]) File "/usr/local/lib/python2.7/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/usr/local/lib/python2.7/site-packages/django/core/checks/database.py", line 10, in check_database_backends issues.extend(conn.validation.check(**kwargs)) File "/usr/local/lib/python2.7/site-packages/django/db/backends/mysql/validation.py", line 9, in check issues.extend(self._check_sql_mode(**kwargs)) File "/usr/local/lib/python2.7/site-packages/django/db/backends/mysql/validation.py", line 13, in _check_sql_mode with self.connection.cursor() as cursor: File "/usr/local/lib/python2.7/site-packages/django/db/backends/base/base.py", line 231, in cursor cursor = self.make_debug_cursor(self._cursor()) File "/usr/local/lib/python2.7/site-packages/django/db/backends/base/base.py", line 204, in _cursor self.ensure_connection() File "/usr/local/lib/python2.7/site-packages/django/db/backends/base/base.py", line 199, in ensure_connection self.connect() File "/usr/local/lib/python2.7/site-packages/django/db/utils.py", line … -
curl request on django working without csrf token
I have a django project running on Heroku, using Django REST framework I use the following middlewares: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] Here is one of my class-based views : class CommunityMemberView(APIView): permissions_classes = [IsAuthenticated, ] serializer_class = CommunitySerializer def post(self, request, community_id=None): """ add the member identified by 'id' to the community 'community_id', if it exists. """ data = request.data id = data.get('id') account = Account.objects.get(id=id) community = Community.objects.get(id=community_id) community.add_member(account) serializer = self.serializer_class(community, context={'request': request}) return Response(serializer.data, status=status.HTTP_201_CREATED) When I try to do a POST request using curl, and without any csrf token, it works fine, and I don't know why. I don't use any decorator, but if I understand the django doc correctly, I don't need to. curl -v -H "content:application/json" -X POST -H "Content-Type:application/json" -d '{"id":"3"}' https://www.example.com/api/v1/community/2/member/ | python -m json.tool I'm guessing there is an obvious reason, but I can't find it in the django doc nor on Stack Overflow, all the previous questions on a related topic were about why it's not working, not the contrary. Thanks -
In django, do we need to define application name in settings.py file under INSTALLED_APPS list
I am using django 1.10.5, and mongodb in project backend. My project structure is as follow- project_name |-- applications | |-- app1 | | |-- admin.py | | |-- upload.py | | |-- __init__.py | | |-- migrations | | | `-- __init__.py | | |-- models.py | | |-- services.py | | |-- urls.py | | |-- views.py | |-- __init__.py |-- __init__.py |-- manage.py |-- project_name_config |-- __init__.py |-- settings | |-- dev_settings.py | |-- __init__.py | |-- prod_settings.py | |-- settings.py |-- urls.py |`-- wsgi.py I am using virtual environment. I have created app using manage.py under directory applications. As per django tutorials when I have added app_name under INSTALLED_APPS list in settings.py, as- INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'app1', ] it is giving error as- (virtEnv):~$python manage.py runserver Unhandled exception in thread started by <function wrapper at 0x7fe94e554848> Traceback (most recent call last):File "/home/dir_project/virtEnv/local/lib/python2.7/site- packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/home/dir_project/virtEnv/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "/home/dir_project/virtEnv/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "/home/dir_project/virtEnv/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/home/dir_project/virtEnv/local/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/dir_project/virtEnv/local/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/home/dir_project/virtEnv/local/lib/python2.7/site-packages/django/apps/config.py", … -
Database mutable field
I have to store data, a part of them is predefined but the user can chose to custom it. What is the best way to store these data in the database? 2 fields, 1 will be an integer field for predefined option and the second will be a string for the custom user input 1 string field, which will contains a json like {predefined: 2, custom: ''} 1 string field which will contains custom string or predefined option id (converted during the request process) 1 string field which will contains the fulltext option even if there is predefined (some of these predefined options can be long text) I tried the 1) but double the number of fields for each "custom ready" data doesn't seem to be perfect... Any idea ? -
Exclude url from search results in django-haystack
I have django app (1.8) and I use there django haystack to search. I want to exclude some url addresses from search results. I get this urls in search results based on searching words. How can I dealing with this? I can't find any tutorials or examples. -
Django material with django smart select error
I'm using django smart select and django material in a project and getting 'NoneType' object is not subscriptable from admin\templates\material\fields\django_relatedfieldwidgetwrapper.html page and the code is {% admin_related_field_urls bound_field as bound_field_urls %} Need help to fix the issue. -
ValueError invalid literal for int() with base 10: ''
I am making a images' uploas system. But I got an error, ValueError at /accounts/upload_save/ invalid literal for int() with base 10: '' . I think this error is that int type value is not in argument. My traceback showed photo_obj = Post.objects.get(id=photo_id) was wrong. But get() is ok to be in int type value,so I cannot fix my error. How can I fix it? I wrote in views.py, @require_POST def regist_save(request): form = RegisterForm(request.POST) if form.is_valid(): user = form.save() login(request, user) context = { 'user': request.user, } return redirect('profile') context = { 'form': form, } return render(request, 'registration/accounts/regist.html', context) def photo(request): d = { 'photos': Post.objects.all(), } return render(request, 'registration/accounts/profile.html', d) def upload(request, p_id): d = { 'p_id': p_id, } return render(request, 'registration/accounts/profile.html', d) def upload_save(request): photo_id = request.POST.get("p_id", "") photo_obj = Post.objects.get(id=photo_id) files = request.FILES.getlist("files[]") photo_obj.image1 = files[0] photo_obj.image2 = files[1] photo_obj.image3 = files[2] photo_obj.save() return redirect("registration/accounts/profile.html") in urls.py from django.conf.urls import url from . import views from django.contrib.auth.views import login, logout urlpatterns = [ url(r'^regist/$', views.regist,name='regist' ), url(r'^regist_save/$', views.regist_save, name='regist_save'), url(r'^profile/$', views.profile, name='profile'), url(r'^upload/(?P<p_id>\d+)/$', views.upload, name='upload'), url(r'^upload_save/$', views.upload_save, name='upload_save'), ] in profile.html {% extends "registration/accounts/base.html" %} {% block content %} <!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> … -
Django: Serialize a model with a many-to-many relationship with a through argument
The model defines an Article and an Author classes. They are linked together with a many-to-many relationship. This relationship is defined through an custom intermediary table: # models.py class Article(models.Model): title = models.CharField(max_length=500) authors = models.ManyToManyField(Author, through='AuthorOrder') class Author(models.Model): name = models.CharField(max_length=255) class AuthorOrder(models.Model): author = models.ForeignKey(Author) article = models.ForeignKey(Article) writing_order = models.IntegerField() The serialization of an Article Queryset doesn't serialize the authors field: # views.py articles = Article.objects.all() articles_json = serialize('json', articles, fields=('title', 'authors') #articles_json {"fields": { "title": "A title" } } I've identified two solutions. This one suggests to serialize the AuthorOrder field separately. The second one is to use the Django Rest Framework. I tried the twos but without success. Do you know another way to do it? -
Django models : pick up existing players for a team in admin
I need help defining models in Django. What I need is : players, and teams. In terms of relationships : 1 player can only be a member in one team (or no team) at a time, and (obviously) teams can only include existing players. So I suppose that there should be a One-to-many relationship from teams to players. What I would like to have in the admin side of Django is : 1) when creating/editing a player : a drop-down list to pick up a team, 2) and when creating/editing a team, the ability to create a list of players from an existing list ("Add" from a drop-down, for instance). While 1) is automatic when adding a ForeignKey to teams in the model for players, I don't know how to achieve 2). Say my models are : class Team(models.Model): team_name = models.CharField(max_length=100) def __str__(self): return self.team_name class Player(models.Model): player_name = models.CharField(max_length=100) def __str__(self): return self.player_name -
max value in annotate with condition in django
I am new to django and SQL queries. I am trying some annotation with django. but unable to get results +-----------------------+-----------+---------------------+ | email | event | event_date | |-----------------------+-----------+---------------------| | hector@example.com | open | 2017-01-03 13:26:13 | | hector@example.com | delivered | 2017-01-03 13:26:28 | | hector@example.com | open | 2017-01-03 13:26:33 | | hector@example.com | open | 2017-01-03 13:26:33 | | tornedo@example.com | open | 2017-01-03 13:34:53 | | tornedo@example.com | 1 | 2017-01-03 13:35:22 | | tornedo@example.com | open | 2016-09-05 00:00:00 | | tornedo@example.com | open | 2016-09-17 00:00:00 | | sparrow@example.com | open | 2017-01-03 16:05:36 | | tornedo@example.com | open | 2017-01-03 20:12:15 | | hector@example.com | open | 2017-01-03 22:06:47 | | sparrow@example.com | open | 2017-01-09 19:46:26 | | sparrow@example.com | open | 2017-01-09 19:47:59 | | sparrow@example.com | open | 2017-01-09 19:48:28 | | sparrow@example.com | delivered | 2017-01-09 19:52:24 | +-----------------------+-----------+---------------------+ I have a table like this which contains email activity. I want to find who opened recently and also i want to count of each event happened. I want results exactly like email | open | click | delivered | max_open_date hector@example.com 4 <null> 1 2017-01-03 22:06:47 sparrow@example.com 3 <null> … -
CSRF token missing or incorrect in django
views.py from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.http import HttpResponse import MySQLdb from django.shortcuts import render_to_response from django.shortcuts import HttpResponseRedirect from django.template.loader import get_template from django.template import Context, Template,RequestContext import datetime import hashlib from random import randint import random from django.views.decorators.csrf import csrf_protect, csrf_exempt from django.template.context_processors import csrf import requests from django.template import RequestContext from log.forms import * @csrf_protect def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): user = User.objects.create_user( username=form.cleaned_data['username'], password=form.cleaned_data['password1'], email=form.cleaned_data['email'] ) return HttpResponseRedirect('/register/success/') else: form = RegistrationForm() variables = RequestContext(request, { 'form': form }) return render_to_response( 'register.html', variables, ) # return render(request,"recharge.html") def register_success(request): return render_to_response( 'registration/success.html', ) base.html <form method="post" action="."> {% csrf_token %} <table border="0"> { form.as_table }} </table> <button type="submit" value="Register">Register</button> <button type="button" onclick="window.location.href='/' ">Login</button> </form> How can i solve this problem? -
Customizing Django user model to take into account DB non-null marks
I am using Django's standard django.contrib.auth.models to implement authorization on my website. I have added a NON-NULL email field to my DB auth_user table. The problem is that in Django's ORM email seems to be nullable. In other words, Django does not respect non-null attribute of DB field in MySQL. Is there any way to tell Django that this field is required as specified in DB, and to make this information reflected when doing if field.required == True: check inside a form's __init__ method? My models and respective forms look like this: class UserForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(UserForm, self).__init__(*args, **kwargs) for field_name, field in self.fields.items(): if field.required == True: field.widget.attrs['required'] = '' class Meta: model = User fields = ('email', 'password',) -
Object must be an instance or subtype of type in django
I'm learning django from thedjangobook and there is an example at class based views that it's in the django documentations aswell, here, my problem is that i'm getting an error when i'm trying to run this. It is supposed to keep track of the last time anybody looked at an author: models.py class Author(models.Model): salutation = models.CharField(max_length=10, null=True) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=40) email = models.EmailField(blank=True, verbose_name='e-mail') headshot = models.ImageField(upload_to='author_headshots', null=True, blank=True) last_accessed = models.DateTimeField(null=True) urls.py urlpatterns = [ url(r'^authors/(?P<pk>[0-9]+)/$', views.AuthorDetailView.as_view(), name='AuthorDetailView'), ] views.py class AuthorDetailView(DetailView): def get_object(self, queryset=Author.objects.all()): # Call the superclass object_1 = super(Author, self).get_object() # Record the last accesed date object_1.last_accessed = timezone.now() object_1.save() # Return the object return object_1 Error: Traceback (most recent call last): File "/home/alex/Documents/Proiecte/Django/Django_tutorial/venv/lib/python3.5/site-packages/django/core/handlers/exception.py", line 39, in inner response = get_response(request) File "/home/alex/Documents/Proiecte/Django/Django_tutorial/venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/alex/Documents/Proiecte/Django/Django_tutorial/venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/alex/Documents/Proiecte/Django/Django_tutorial/venv/lib/python3.5/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/home/alex/Documents/Proiecte/Django/Django_tutorial/venv/lib/python3.5/site-packages/django/views/generic/base.py", line 88, in dispatch return handler(request, *args, **kwargs) File "/home/alex/Documents/Proiecte/Django/Django_tutorial/venv/lib/python3.5/site-packages/django/views/generic/detail.py", line 115, in get self.object = self.get_object() File "/home/alex/Documents/Proiecte/Django/Django_tutorial/mysite/books/views.py", line 179, in get_object object_1 = super(Author, self).get_object() TypeError: super(type, obj): obj must be an instance or subtype of … -
import error while trying to run django on apache
I am trying to run my django project on an apache server. I am not running the django project on a virtualenv. I have the following piece of code in views.py where I get an import error saying No module named startInsight every time. The same if I run with python manage.py runserver 0.0.0.0:80 it works prefectly fine. Error point in views.py: sys.path.insert(0,"/Insight/scripts") import startInsight The following are the configurations I made: /etc/apache2/sites-available/000-default.conf <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /web/mysite ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined <Directory /> Options FollowSymLinks AllowOverride None </Directory> <Directory /web/mysite> Options Indexes FollowSymLinks MultiViews AllowOverride None Require all granted </Directory> Alias /static /web/mysite/mysite/static <Directory /web/mysite/mysite/static> Require all granted </Directory> <Directory /web/mysite/mysite> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess mysite python-path=/usr/bin/python:/web/mysite WSGIProcessGroup mysite WSGIScriptAlias / /web/mysite/mysite/wsgi.py </VirtualHost> /web/mysite/mysite/wsgi.py: import os ''' I tried adding these two lines below. Did not make a difference. import sys sys.path.insert(0,"/IOInsight/scripts") ''' from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") application = get_wsgi_application() I am not sure what I am doing wrong and would need some guidance. -
How to make Curl request for USPS django python
I am working on USPS API for tracking packages i want to make curl request for tracking package. This is what i found on USPS API documentation for tracking package. > http://production.shippingapis.com/ShippingApi.dll?API=TrackV2&XML=<TrackFieldRequest > USERID="xxxxxxxxxx"> <TrackID ID="XXXXXXXXXXXXX"> </TrackID> > > </TrackFieldRequest> Now i am trying to make curl request in django this is what i am doing but it does not working.Is this a right way to parse xml/url in django. def get_tracking_status(self): try: headers = {'Content-Type': 'application/xml'} xml = "<TrackFieldRequest USERID='xxxxxxxxxx'><TrackID ID='XXXXXXXXXXXXX'></TrackID></TrackFieldRequest>" requests.post("http://production.shippingapis.com/ShippingApi.dll?API=TrackV2", headers=headers, data=xml) except Exception as e: print e -
Django allauth stackexchange error items[0]
I've setup stackexchange in the settings file as SOCIALACCOUNT_PROVIDERS = { 'stackexchange': { 'SITE': 'stackoverflow' }, 'linkedin':{'SCOPE': ['r_basicprofile', 'r_emailaddress']} } it directly correctly to stackexchange and asks to approve permission the redirect now back to djangoallauth then throws an error Environment: Request Method: GET Request URL: http://kazichimp.com/accounts/stackexchange/login/callback/?code=P3mvQoa4qM2q*g8f6WoIxg))&state=tjK2T4QHRkXz Django Version: 1.8.7 Python Version: 2.7.12 Installed Applications: ... Traceback: File "/usr/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response 132. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python2.7/dist-packages/allauth/socialaccount/providers/oauth2/views.py" in view 69. return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/allauth/socialaccount/providers/oauth2/views.py" in dispatch 130. response=access_token) File "/usr/local/lib/python2.7/dist-packages/allauth/socialaccount/providers/stackexchange/views.py" in complete_login 23. extra_data = resp.json()['items'][0] Exception Type: KeyError at /accounts/stackexchange/login/callback/ Exception Value: 'items' -
I cannot show a file-upload button
I cannot show a file-upload button. I wrote in profile.html like {% extends "registration/accounts/base.html" %} {% block content %} user.username: {{ user.username }}<hr> user.is_staff: {{ user.is_staff }}<hr> user.is_active: {{ user.is_active }}<hr> user.last_login: {{ user.last_login }}<hr> user.date_joined: {{ user.date_joined }} {% endblock %} <!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <title>UPLOAD</title> <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> {% block body %} <div class="container"> <form action="{% url 'accounts:upload_save' %}" method="POST" enctype="multipart/form-data"> <input type="file" name="files[]" multiple> <input type="hidden" value="{{ p_id }}" name="p_id"> {% csrf_token %} <input type="submit"> </form> </div> {% endblock %} <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> </body> </html> So,I wrote multipart/form-data tag like <form action="{% url 'accounts:upload_save' %}" method="POST" enctype="multipart/form-data">. But, profile.html did not show the part of below , it showed only upper . How can i fix it? -
django restframework in login module authenticate() not working
email = request.data.get('email', None) password = request.data.get('password', None) account = authenticate(email=email, password=password) I am using an authenticate() function but it always returns None. Can you suggest some modifications to rectify the function. -
Is it normal that the Django site I recently deployed on Apache is always on?
I recently deployed a Django site on a DigitalOcean droplet through Apache. I did python manage.py runserver through ssh and now the Django site is running. However, it stayed on even after the ssh session expired (understandable because it's still running on the remote server) but how do I shut it down if I need to? Also, due to this, I don't get error messages on the terminal if something goes wrong like I do when I develop locally. What would be a fix for this? -
Custom Forum in Django - issues parsing BB & HTML output
I know that there is a sufficient supply of mature forum application but I decided not to use any of them, because I would need to cut out like 3/4 of their functionality (auth, profiles, messanger, notification, reputations - all of which i already have or don't want) and once chopped down to the bone I still need to customize the rest. Instead I found a basic forum application which I am trying to build up to the forum that fits my needs and my application. For writing posts I have installed CKeditor but as I am no expert in this field I am looking for guidance into this BB forum which I once used (chopped down but didn't found the will to customize). However, that creates issues of it's own: When I am trying to post in to a thread I achieve either to correctly parse the bb tags or the html tags, but never both. This is an example of a reply view with sucessful bb quotes, that fails to parse html tags: <p> test20 ffffff </p> <p><img alt=“:-)” height=“15” src="url/static/ckeditor/ckeditor/plugins/smiley/images/big_smile.png“ title=”:-)“ width=”15" /></p> And here a reply that parses the html tags correctly (no p tags visible) … -
File descriptor stays doesn't update for logging in Django
We use Python(2.7)/Django(1.8.1) and Gunicorn(19.4.5) for our web application and supervisor(3.0) to monitor it. I have recently encountered 2 issues in logging: Django was logging into previous day logs(We have log rotation enabled) Django was not logging anything at all. The first scenario is understandable where the log rotation changed the file but Django was not updated. The second scenario fixed when I restarted the supervisor process. Which led me to believe again the file descriptor was not updated in the django process. I came by this SO thread which states: Each child is an independent process, and file handles in the parent may be closed in the child after a fork (assuming POSIX). In any case, logging to the same file from multiple processes is not supported. So I have few questions: My gunicorn has 4 child processes and if one of them fails while writing to a log file will the other child process won't be able to use it? and how to debug these kind of scenarios? Personally I found debugging errors in python logging module to be difficult. Can some one point how to debug errors such as this or is there any way I can …