Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to refresh Google OAuth2 token programatically
I'm using Django with python-social-auth to authenticate my users with Google OAuth2 and use the Youtube API. What I would like to achieve is ask them to login and authorize only once and be able to use their credentials as long as I want. This is not possible because after about an hour they expire and I need the user to re-authorize my application to get new credentials. I assume the solution is to refresh the credentials periodically but I could not find any reliable guide in how to do this. My current configuration is: SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = 'the_key' SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = 'the_secret' SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = ["https://www.googleapis.com/auth/youtube.readonly", "https://www.googleapis.com/auth/yt-analytics.readonly"] SOCIAL_AUTH_GOOGLE_OAUTH2_AUTH_EXTRA_ARGUMENTS = { 'access_type': 'offline', 'approval_prompt': 'force' } I've tried refreshing it with the code below but since It still expires I think it is not the correct way: social_user = UserSocialAuth.objects.get(...) # Fetch the instance social_user.refresh_token(load_strategy()) # Returns "None" -
Python/ Django form- how to 'save' value entered in a form 'DateInput' field?
I have a form displayed on one of my Django project webpages- the first field in the form accepts an integer in a text input field, the second displays another integer in a text input field, and the third displays a date value. Currently, when the user first loads this page, the integers displayed in fields one and two are already populated (the first has been retrieved from the database, and the value of the second is calculated based on the value of the first). The date field is blank. However, if I change the value of the first integer field, and refresh the page, the new values for fields one and two are automatically loaded (i.e. the view used to display this webpage registers the changes to the value, and updates the database, so that when it retrieves the values when the page is reloaded, the new values are what it finds. But, for some reason, when I select a date in the third field, and refresh the page, the date field is always blank when the page is reloaded... It seems that either the date is not being saved when a value is entered, or it is not … -
Django Signals, how to know when an update happen?
The url of my post object must be: city-the-title-of-the-post-POST.ID, to achieve this when the obj is created I am using a post_save signal @receiver(post_save, sender=Post, dispatch_uid="update_stock_count") def criar_slug(sender, instance, created,**kwargs): if created: string = (instance.city+" "+instance.title+" "+str(instance.id)) instance.slug = slugify(string) instance.save() It is working fine! Now the problem. If I go to the django admin when I change the post.title then save the post, the slug of course will not change. So I am wondering how I could catch this update signal, how I could automatic change the slug attribute when updating the obj. Thanks -
django.views.generic.edit.CreateView set template_name
I can't set template_name for intance of from django.views.generic.edit import CreateView How i can do this? -
Unable to debug in pycharm with pytest
I can't debug in PyCharm using py.test. All the test suite is running ok in "Run mode" but it doesn't stop on breakpoints. I also have py.test as the default test runner. Maybe this is not important, bug debugging works correctly in run server mode (Django server). Any ideas? -
AWS/Django: 500 internal server error on AWS ec2
I have created an Amazon ec2 instance with "Django powered by Bitnami" AMI. I think the problem is with djando.wsgi. I'm getting the "The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator, you@example.com..." I would appreciate helping me solve this. My django.wsgi is as follows: import os import sys sys.path.append('/opt/bitnami/apps/django/django_projects/Project') os.environ.setdefault("PYTHON_EGG_CACHE", "/opt/bitnami/apps/django/django_projects/Project/egg_cache") from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testproject.settings") application = get_wsgi_application() httpd.conf: <IfDefine !IS_DJANGOSTACK_LOADED> Define IS_DJANGOSTACK_LOADED WSGIDaemonProcess wsgi-djangostack processes=2 threads=15 display-name=%{GROUP} </IfDefine> <Directory "/opt/bitnami/apps/django/django_projects/Project/testproject"> Options +MultiViews AllowOverride All <IfVersion < 2.3 > Order allow,deny Allow from all </IfVersion> <IfVersion >= 2.3> Require all granted </IfVersion> WSGIProcessGroup wsgi-djangostack WSGIApplicationGroup %{GLOBAL} <IfVersion < 2.3 > Order allow,deny Allow from all </IfVersion> <IfVersion >= 2.3> Require all granted </IfVersion> </Directory> Alias /static "/opt/bitnami/apps/django/lib/python2.7/site-packages/Django-1.10.2-py2.7.egg/django/contrib/admin/static" WSGIScriptAlias / '/opt/bitnami/apps/django/django_projects/Project/testproject/wsgi.py' -
Django tests - User matching query does not exist
I have the following TestCase in my Django project : class UserCreateTestCase(TestCase): def SetUp(self): # Control object User.objects.create(name='Harry', surname='POTTER', email='harry.potter@email.com', passwd='scar') def test_print(self): harry = User.objects.get(name='Harry') print(harry) However, I get the following error when running the tests : ERROR: test_print (tests.test_user.UserCreateTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/PATH/tests/test_user.py", line 23, in test_print harry = User.objects.get(name='Harry') File "/usr/lib/python3/dist-packages/django/db/models/manager.py", line 127, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/lib/python3/dist-packages/django/db/models/query.py", line 334, in get self.model._meta.object_name structure.models.DoesNotExist: User matching query does not exist. I'm doing more or less the same thing as what's described in the documentation, but in my case the user object is not created, and I can't recover it using User.objects.get(). I have also tried printing User.objects.all(), which returns an empty result. If relevant, here is my model definition : class User(models.Model): # User informations name = models.CharField(max_length=30) surname = models.CharField(max_length=30) # Login informations email = models.EmailField() passwd = models.CharField(max_length=24) I am using django 1.8. Why is the user object not created, and how can I solve this problem ? -
Django request method
I have seen lot of django code where after posting the data in template it is checked if request.method=='POST' in view. Why is this followed and what are the advantages? Will it create any problem if not followed? -
Authentication with mod wsgi and apache in Django
I finally set up embedded mode of wsgi like this link with help. I was ready to move on authenticating with mod wsgi and apache in Django. In this django manual, it explains simply and kindly how to do that. I followed instructions but it showed internal server error after pop up for checking ID and password. No matter I entered authenticated user info in pop up windows or not, it showed internal server error on screen, not Django page. My setting /etc/apache2/mods-available/wsgi.conf <IfModule mod_wsgi.c> WSGIPythonHome /usr/local/pythonenv WSGIPythonPath /home/cango/jaemyun </IfModule> /etc/apache2/mods-available/wsgi.load LoadModule wsgi_module /usr/lib/apache2/modules/mod_wsgi-py35.cpython-35m-x835m-x86_64-linux-gnu.so /etc/apache2/sites-available <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined WSGIScriptAlias / /home/cango/jaemyun/jaemyun/wsgi.py WSGIProcessGroup %{GLOBAL} WSGIApplicationGroup %{GLOBAL} <Location "/"> AuthType Basic AuthName "Top Secret" Require valid-user AuthBasicProvider wsgi WSGIAuthUserScript /home/cango/jaemyun/jaemyun/wsgi.py </Location> <Directory /home/cango/jaemyun/jaemyun> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> home/cango/jaemyun/jaemyun/wsgi.py import os os.environ['DJANGO_SETTINGS_MODULE'] = 'jaemyun.settings' from django.contrib.auth.handlers.modwsgi import check_password from django.core.handlers.wsgi import WSGIHandler application = WSGIHandler() 1.Embedded mod of wsgi worked before changing codes following the manual. 2.My Apache instance is running only one Django application. 3.mod_auth_basic and mod_authz_user are load. Loaded Modules: core_module (static) so_module (static) watchdog_module (static) http_module (static) log_config_module (static) logio_module (static) version_module (static) unixd_module (static) access_compat_module (shared) alias_module … -
Show different verbose names for django admin models based on a condition
Hello i have a django model and i am trying to do something like this in my django admin. from django.contrib.auth.models import User class Patient(models.Model): id = models.AutoField(primary_key=True) patient_ID = models.ForeignKey(PatientProfile) temp = models.CharField(max_length=10, blank=True, editable=True) pulse = models.CharField(max_length=10, blank=True, editable=True) class Meta: if user.is_superuser: verbose_name = "Doctor Consulting" verbose_name_plural = "Doctor Consulting" else: verbose_name = "Patients Details" verbose_name_plural = "Patients Details" But this is not working. I have already registered the model in my admin. I get an error like this; if user.is_superuser: NameError user is not defined Any help will be appreciated. Thanks -
Django "./manage.py runserver" log to file instead of console
Running python manage.py runserver will initiate Django's development server and all logs are printed to the console. I need to write the logs in a django.log file instead of console. Django logging documentation is good, but I cant seem to configure the logging to log the same as python manage.py runserver. Question: How can I log everything from ./manage.py runserver to a file? -
Django Inline Formset Inside Model Formset
i have two models named product and productimage .I will have multiple images for product. So in this application, i want to create multiple products and each products i want to create multiple images in a single form using modelformset_factory and inlineformset_factory. i tried, but it was not success. how can i do that. here product is a modelformset and productimage is an inlineformset models.py : class Product(models.Model): title = models.CharField(max_length=128) description = models.TextField() image = models.ImageField(upload_to="images/") def __unicode__(self): return self.title class ProductImage(models.Model): product = models.ForeignKey(Product, related_name="%(app_label)s_%(class)s") title = models.CharField(max_length=128) image = models.ImageField(upload_to="images/") def __unicode__(self): return self.title forms.py Product_modelformset = modelformset_factory(Product, form=ProductForm, extra=0, min_num=1) Productimage_inlineformset = inlineformset_factory(Product, ProductImage, form=ProductImageForm, extra=0, min_num=1, max_num=5, can_delete=True) views.py def create_product(request): template = "frontend/create_product.html" context = {} product_formset = Product_modelformset(queryset=Product.objects.none(), prefix="product_formset") productimage_formset = Productimage_inlineformset(prefix="productimage_formset") if request.method == 'POST': pass ........ ......... context["product_formset"] = product_formset context["productimage_formset"] = productimage_formset return render(request, template, context) create_product.html {% for form in product_formset.forms %} <div class="form_items"> <p class="lead">Product ITems</p> {{ form.as_p }} </div> {% for form in productimage_formset.forms %} <div class="image_items"> <p class="lead">image items</p> {{ form.as_p }} </div> {% endfor %} {% endfor %} <script> $(document).ready(function() { $('div.form_items').formset({ prefix: "{{ product_formset.prefix }}" }); $('div.image_items').formset({ prefix: "{{ productimage_formset.prefix }}" }); }); </script> -
Boolean in django admin panel always True
Good Morning, I'm trying to get the django admin page to show icons when I list a boolean in de list_display, but I'm getting the green icon representing True even if the boolean is false. Here are the relevant parts of my django files: Models.py ... koodous = models.BooleanField(default=True) virustotal = models.BooleanField(default=True) Admin.py list_display = (... ,'koodous','virustotal',...) .... def koodous(self, obj): ver = obj.version.order_by('-crawled_date').first() return ver.koodous koodous.boolean = True def virustotal(self, obj): ver = obj.version.order_by('-crawled_date').first() return ver.virustotal virustotal.boolean = True I've entered into the shell mode, just to check that there is no problem with the type or the real value of the vars 'koodous' and 'virustotal' but both seem to be what they should be: (InteractiveConsole) >>> from apps.models import App, Version >>> obj = App.objects.get(pk="1") >>> ver = obj.version.order_by('-crawled_date').first() >>> ver.koodous False >>> ver.virustotal False >>> type(ver.koodous) <type 'bool'> >>> type(ver.virustotal) <type 'bool'> >>> But as you can see in the admin page they show as Ture Does anyone know what I'm missing here? Thanks for your time! -
What are the advantages of django-channels over python websockets?
Before people were using python websockets with django for websocket handling. Now the django-channels came as an official django project which supports django to handle websockets. can anyone list the advantage of django channels over python websockets? One point would be, Since channels built for django web development, it would be well integrated with django framework. Thanks for any reply. -
Django Rest Framework - Add object with foreign key data in path param
I have 2 models, representing an author his articles, the idea is an author can add articles freely (not that it matters for my problem, but in an append only matter). class Author(models.Model): name = ... class Article(models.Model): author = models.ForeignKey(Author, related_name='articles', on_delete=models.CASCADE) title = ... content = ... timestamp = models.DateTimeField(auto_now=True) My serializes are as follows: class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Author fields = '__all__' class ArticleSerializer(serializers.ModelSerializer): class Meta: model = Article fields = '__all__' And I have a simple view: @csrf_exempt def author_articles(request, author_id): try: author = Author.objects.get(id=author_id) except Author.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': articles = author.articles.all() serializer = serializers.ArticlesSerializer(articles, many=True) return JsonResponse(serializer.data, safe=False) elif request.method == 'POST': data = JSONParser().parse(request) serializer = serializers.ArticlesSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) Where the Url is defined: url(r'^authors/(?P<author_id>[0-9]+)/articles/$', views.author_articles) So a simple POST request to the URL: server:port/authors/1/articles/ with the body below works like a charm! { "author": 1, "title": "foo", "content": "bar" } What bugs me is that I provide the author id twice, once in the body and once in the path params. I can easily remove it from the path param and make it work, but what I really want is … -
Django-slack unable to send bot messages
I am trying to use django-slack api, I followed the path described here http://django-slack.readthedocs.io/ But I am not able to send sample bot message. Here is my code snippet: message.slack {% extends django_slack %} {% block text %} Hello World! {% endblock %} in views.py def index(request): slack_message('message.slack') return HttpResponse('Sent a message') Can someone please help me on this? -
ModelChoiceField with Django Forms
I'm stuck with Django and I would like to learn more and more on this framework. I read some tutorials (English and French tutorials) and as I'm beginning, I don't find what I want. I have a forms.py file in my app directory : #-*- coding: utf-8 -*- from django import forms class BirthCertificateForm (forms.Form) : # rowid = forms.IntegerField() # rowid primary key # numero_acte = forms.IntegerField() # Form number date_acte = forms.DateField('%d/%m/%Y') # Form date heure_acte = forms.TimeField('%H:%M:%S') # Form hour nom = forms.CharField(max_length=30, label=u"Nom") # Lastname prenom = forms.CharField(max_length=30, label=u"Prénom") # Firstname sexe = forms. # <== I would like to have the choice between 'M' or 'F' And this is my views.app file : from django.shortcuts import render_to_response from django.http import HttpResponse from django.template import loader from BirthCertificate.forms import BirthCertificateForm # Create your views here. def BirthCertificateAccueil(request) : # Fonction permettant de créer la page d'accueil de la rubrique Acte de Naissance #Cherche le fichier html accueil et le renvois template = loader.get_template('accueil.html') return HttpResponse(template.render(request)) def BirthCertificateCreationAccueil(request) : # Fonction permettant de créer la page de création du formulaire de la partie : Acte de Naissance template = loader.get_template('creation_accueil.html') return HttpResponse(template.render(request)) def BirthCertificateForm(request) : # Fonction … -
Facebook Bot sending reply multiple times
I have made a facebook bot using django as a webhook source, but for every message it is sending reply multiple times. Please help me. This is how my source code looks: class BotView(generic.View): def get(self, request, *args, **kwargs): if self.request.GET['hub.verify_token'] == '1234': return HttpResponse(self.request.GET['hub.challenge']) else: return HttpResponse('Error, invalid token') @method_decorator(csrf_exempt) def dispatch(self, request, *args, **kwargs): return generic.View.dispatch(self, request, *args, **kwargs) # Post function to handle Facebook messages # Post function to handle Facebook messages def post(self, request, *args, **kwargs): # Converts the text payload into a python dictionary incoming_message = json.loads(self.request.body.decode('utf-8')) # Facebook recommends going through every entry since they might send # multiple messages in a single call during high load for entry in incoming_message['entry']: for message in entry['messaging']: # Check to make sure the received call is a message call # This might be delivery, optin, postback for other events if 'message' in message: # Print the message to the terminal url = message['message']['text'] print(url) post_facebook_message(message['sender']['id'], url) return HttpResponse() def post_facebook_message(fbid, recevied_message): post_message_url = 'https://graph.facebook.com/v2.6/me/messages?access_token=EAAFsq1Lzxt4BADZBrGfZBd9LyEeX7gtb2aiKFpOluZAaMsDN2FTSEflg5B1frlmBuZC8xR5BOnngekPynQ2ZBC9mF1qMYOJdc5IN0NWJsESqZAXZBGRrniSFEfc3x2gonc23K6ZA8lMldhhlMfLA7QxvGn5Jb7PRrrZC5ZB1I48pZBjsxuRlUTEA326' 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) pprint(status.json()) -
angularjs doesnt POST to my django based apis - giving CORS error
This has been plaguing me for quite a while now. I've set up a basic set of apis in Django and am building an angularJS based front end. However for some weird reason the following code results in a CORS error. var req = { method: 'POST', url: url, headers: {'Content-Type': 'application/x-www-form-urlencoded'}, withCredentials: true, param: data, data: data } return $http(req).then( function(response){ callbackSuccess(response); }, function(response){ callbackError(response); } ); I found out two things that when I do a post an OPTIONS request is made and secondly none of what I post is even posted. I try to out put the request.POST contents and its empty. Internal Server Error: /api/users/auth/ Traceback (most recent call last): File "/home/ali/eb-virt/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 149, in get_response response = self.process_exception_by_middleware(e, request) File "/home/ali/eb-virt/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 147, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ali/eb-virt/local/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/home/ali/eb-virt/local/lib/python2.7/site-packages/django/utils/decorators.py", line 149, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/ali/Projects/api.project.local/project/api/views.py", line 50, in loginUser emailAddress = request.POST["emailAddress"] File "/home/ali/eb-virt/local/lib/python2.7/site-packages/django/utils/datastructures.py", line 85, in __getitem__ raise MultiValueDictKeyError(repr(key)) MultiValueDictKeyError: "'emailAddress'" [21/Nov/2016 07:56:59] "OPTIONS /api/users/auth/ HTTP/1.1" 500 81083 I've installed the django-cors-headers and followed all the instructions to the core but its still not working... -
Django model idea for storing visitor statistics
I am currently looking to build a Django module for providing a website with google-analytics like data, but without google-analytics. So I would want to process/record requests somehow before being able to display cumulative statistics regarding my visitors. total number of views total number of mobile views total number of desktop views visitors from north america visitors from south america ... Currently what I have in mind amounts to something of an incredibly large enumeration class Entry(models.Model): date = models.DateTimeField() # statistics are partitioned chronologically total = models.IntegerField() # number of total views mobile = models.IntegerField() # number of mobile views ... from_na = models.IntegerField() # from north america from_sa = models.IntegerField() # from south america ... However, as one might imagine, this would be extremely un-extensible as any future desire for an additional field of interest (e.g. visitors from antartica) would require modifying the schema of an entire database table. Primarily, I am interested in storage-usage vs extensibility. For example, if I wanted to be extremely extensible, I could just save a tuple for every request storing all relevant base information (user-agent, ip-address, etc) and later derive all desired statistics through clever use of aggregations. (Although I'm not quite … -
Django/Python Exception Value: dictionary update sequence element #0 has length 4; 2 is required
article.urls.py : from django.conf.urls import url from . import views urlpatterns = [ url(r'^tag/(?P<tag>\w+)/$',views.search_tag,name='search_tag'), ] article.views.py: from django.shortcuts import render from django.http import HttpResponse from article.models import Article def search_tag(request,tag): try: post_list = Article.objects.all() except Article.DoesNotExist: raise Http404 return render(request,'tag.html',{'post_list',post_list}) tag.html: {% extends "base.html" %} {% load custom_markdown %} {% block content %} <div class="posts"> {% for post in post_list %} <section class="post"> <header class="post-header"> <h2 class="post-title"><a href="{% url "detail" id=post.id %}">{{ post.title }}</a></h2> <p class="post-meta"> Time: <a class="post-author" href="#">{{ post.date_time |date:"Y M d"}}</a> <a class="post-category post-category-js" href="{% url "search_tag" tag=post.category %}">{{ post.category|title }}</a> </p> </header> <div class="post-description"> <p> {{ post.content|custom_markdown }} </p> </div> <a class="pure-button" href="{% url "detail" id=post.id %}">Read More >>> </a> </section> {% endfor %} </div><!-- /.blog-post --> {% endblock %} Why i got error like this? ValueError at /tag/Python/ dictionary update sequence element #0 has length 4; 2 is required Request Method: GET Request URL: http://localhost:9000/tag/Python/ Django Version: 1.10.3 Exception Type: ValueError Exception Value: dictionary update sequence element #0 has length 4; 2 is required Exception Location: /usr/local/lib/python3.5/dist-packages/django/template/context.py in __init__, line 18 Python Executable: /usr/bin/python3 Python Version: 3.5.2 Python Path: ['/home/weixiang/workspace/WebPy/my_blog', '/usr/lib/python35.zip', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-x86_64-linux-gnu', '/usr/lib/python3.5/lib-dynload', '/home/weixiang/.local/lib/python3.5/site-packages', '/usr/local/lib/python3.5/dist-packages', '/usr/lib/python3/dist-packages'] Server time: Mon, 21 Nov 2016 07:50:07 +0000 … -
Why is this Django form not raising ValidationError?
I'm trying to raise a ValidationError during registration if a use with the same email already exists. I have added the following method in my form to do that. def clean_email(self): email = self.cleaned_data.get('email') if email: try: user = User.objects.get(email=email) except: user = None if user is not None: raise forms.ValidationError('This email address is unavailable!') return email However, I have included a print statement after except and the console always prints that value. So it is for some reason executing that part of the code even if the user with the specified email address exists. What am I doing wrong? -
Django circular import AppRegistryNotReady error
i' ve Django 1.9.2 with python 3.4.2 in a virtualenvironment. I' ve many applications, and the 2 related are common and shop. common/models.py contains: from django.apps import apps class Document(CLDate): user = models.ForeignKey(User) assessmentorder = models.ForeignKey(apps.get_model('shop', 'AssessmentOrder'), blank=True, null=True) shop/models.py contains: from common.models import ServiceModel class AssessmentOrder(CLDate): """AssessmentOrder model""" order = models.ForeignKey(Order) comment = models.TextField() . This is a circular import, and i read many strategy to resolve it (including apps.get_model), but none of them seem to work for me. I also tried apps.get_model('shop.AssessmentOrder') , but the same. The complete error message is the following: File "/home/hidden/.virtualenvs/sccdb34/lib/python3.4/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/home/hidden/.virtualenvs/sccdb34/lib/python3.4/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/home/hidden/.virtualenvs/sccdb34/lib/python3.4/site-packages/django/utils/autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "/home/hidden/.virtualenvs/sccdb34/lib/python3.4/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/home/hidden/.virtualenvs/sccdb34/lib/python3.4/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/home/hidden/.virtualenvs/sccdb34/lib/python3.4/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/home/hidden/.virtualenvs/sccdb34/lib/python3.4/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/home/hidden/.virtualenvs/sccdb34/lib/python3.4/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/home/hidden/.virtualenvs/sccdb34/lib/python3.4/importlib/__init__.py", line 109, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 2254, in _gcd_import File "<frozen importlib._bootstrap>", line 2237, in _find_and_load File "<frozen importlib._bootstrap>", line 2226, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 1200, in _load_unlocked File "<frozen importlib._bootstrap>", line 1129, in … -
Unhandled exception error django
Everything was working fine and suddenly i start getting this error when running the command python manage.py runserver. Can anyone help me. Thank you! \Unhandled exception in thread started by Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/utils/autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/init.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/apps/config.py", line 199, in import_models self.models_module = import_module(models_module_name) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/init.py", line 37, in import_module import(name) File "/Users/shyam/Documents/firstdjangoapp/home/models.py", line 13, in from allauth.account.forms import SignupForm ImportError: No module named account.forms -
Getting data on HTML page without return render in Django?
I have below views.py file from django.shortcuts import render, redirect, render_to_response from bs4 import BeautifulSoup as bs import time output = [] def register(request): output = get_form_data(request) if output == None: output="" if request.POST.get('cancel'): return redirect('/login/') if output == 'Registration Successful': t_end = time.time() + 5 * 1 while time.time() < t_end: a = 0 return redirect('/login/') return render(request, 'template/register.html', {"output": output}) def get_form_data(request): if request.POST: if request.POST.get('register'): reg_uname = request.POST.get('reg_una') reg_pass = request.POST.get('password') reg_cnfpass = request.POST.get('cnfpass') reg_email = request.POST.get('emailid') return "Registration Successful" I want to show the output "Registration Successful" when i click on register button before return render to the register.html page and then want 5 seconds to redirect the page to login page. Currently if the registration is successful, after 5 seconds, I am redirected to the login page but I am unable see the "Registration Successful" message since I am not on the same page. Below is the register.html file for reference <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Register</title> <link href="/static/register.css" type="text/css" rel="stylesheet"> <script type="text/javascript"> function validate() { var name,pass,cnfpass,email; name = document.getElementById("reg_uname"); pass = document.getElementById('reg_pass'); cnfpass = document.getElementById('reg_cnfpass'); email = document.getElementById('reg_email'); if(name.value == '') { alert('Username Cannot be left blank!'); name.focus(); return false; } …