Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to make field only editable by system (not admin or users)
I need some fields in my model for internal usages (i.e. status, last modified, etc.) which should only editable (and fillable) by python code. How to hide it in Django Admin and disable direct editing from forms? -
Django Channels Worker not responding to websocket.connect
I'm having a problem with django channels. Daphne accepts WebSocket CONNECT requests properly, but then the workers doesn't respond to the request with the supplied method in consumers.py. The thing is this happens only most of the time. Sometimes it responds with the method in the consumers.py but most of the time the worker doesn't respond at all. I have a duplicate code working fine in vagrant (trusty64) environment, but the code behaves like that in an actual trusty64 machine. It should be noted that the trusty64 machine that hosts the app also has other application running (about 4 apps running at the same time). I have a routing.py set up like this from channels import route from app.consumers import connect_tracking, disconnect_tracking channel_routing = [ route("websocket.connect", connect_tracking, path=r'^/websocket/tms/tracking/stream/$'), route("websocket.disconnect", disconnect_tracking, path=r'^/websocket/tms/tracking/stream/$'), ] with the corresponding consumers.py that looks like this import json from channels import Group from channels.sessions import channel_session from channels.auth import http_session_user, channel_session_user, channel_session_user_from_http from django.conf import settings @channel_session_user_from_http def connect_tracking(message): group_name = settings.TRACKING_GROUP_NAME print "%s is joining %s" % (message.user, group_name) Group(group_name).add(message.reply_channel) @channel_session_user def disconnect_tracking(message): group_name = settings.TRACKING_GROUP_NAME print "%s is joining %s" % (message.user, group_name) Group(group_name).discard(message.reply_channel) and some channels related lines in settings.py like this redis_host … -
Filter user in django and add to a existing group
I am new to Django and I have failing on a task now for a while. I have searched in the Django docs and here for some questions but there nothing is working for me. Here is my view: def user_accept(request): if request.method == 'POST': username = AddUser.objects.filter(owner=request.user).get().user_request group_name = Projects.objects.filter(user=request.user).get().group_url group = Group.objects.get(name=group_name) group.user_set.add(username) delete_user = AddUser.objects.filter(user_request=username) delete_user.delete() Here is my model: class AddUser(models.Model): owner = models.ForeignKey(User) title = models.CharField(max_length=20, default='', blank=True) user_request = models.CharField(max_length=30, default='') answer = models.BooleanField(default=False) AddUser model is used for users to request access to a specific project. So when a user is requesting a project, data is saved to the AddUser model. The user field is set to the "owner" of the project so I can filter every project with a proper owner. If the owner decides to accept the request my user_accept view is executed. Here is the problem, when I try to add the username into the group, I get the following error: invalid literal for int() with base 10: 'myusername' I have tried to convert the username with int(username) and tried to get the username's user_id but nothing seems to work... I think it have something to do how I filter … -
Django Form is not validating Custom Choice Field
Adding attributes to Choice Field: class SelectWithTitles(forms.Select): def __init__(self, *args, **kwargs): super(SelectWithTitles, self).__init__(*args, **kwargs) # Ensure the titles dict exists self.titles = {} def render_option(self, selected_choices, option_value, option_label): title_html = (option_label in self.titles) and \ u' title="%s" ' % escape(self.titles[option_label]) or '' option_value = option_value selected_html = (option_value in selected_choices) and u' selected="selected"' or '' return u'<option value="%s"%s%s>%s</option>' % ( escape(option_value), title_html, selected_html, conditional_escape(option_label)) class ChoiceFieldWithTitles(forms.ChoiceField): widget = SelectWithTitles def __init__(self, choices=(), *args, **kwargs): choice_pairs = [(c[0], c[1]) for c in choices] super(ChoiceFieldWithTitles, self).__init__(choices=choice_pairs, *args, **kwargs) self.widget.titles = dict([(c[1], c[2]) for c in choices]) class InquiryForm(forms.ModelForm): phone_code = ChoiceFieldWithTitles( label=_("Country dialing code"), choices=[('','Dailing Code', 'Dailing Code')]+[(country.id, '{} (+{})'.format(country.name, country.phone_code), '+{}'.format(country.phone_code)) for country in Country.objects.all().filter(visible=True).order_by('name')], required=True, ) class Meta: model = Inquiry def __init__(self, *args, **kwargs): code = kwargs.pop('phone_code', None) super(InquiryForm, self).__init__(*args, **kwargs) if code is not None: self.initial['phone_code'] = code self.fields['is_subscribed'].label = _("Keep me updated with news, specials offers and more.") self.helper = FormHelper() self.helper.template_pack = "bootstrap3" self.helper.form_method = "post" self.helper.form_id = "form" self.initial['insurance'] = True self.helper.add_input( Submit('inquiry', _('Inquiry'), css_class='btn btn-default',) ) self.helper.form_method = 'post' self.helper.layout = Layout( Div( Field('code_phone'), ),) view.py class DetailView(TemplateView): model = Product template_name = "site/contact/detail.html" template_name_done = "site/contact/contact-us-done.html" template_name_done_email = "site/contact/emails/contact-us-done.html" def post(self, request, slug, … -
Creating a book app in django
I created a Book app using django. All of the text was formatted using TinyMCE via the admin interface meaning I had html stored in my database. This is the current structure of my app models class Chapter(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(unique=True) date_completed = models.DateTimeField(blank=True, null=True) completed = models.BooleanField(default=False) def __str__(self): return self.title def get_absolute_url(self): return reverse("course:subchapter_list", kwargs={"pk": self.pk}) class SubChapter(models.Model): chapter = models.ForeignKey(Chapter, on_delete=models.CASCADE) title = models.CharField(max_length=200, unique=True) slug = models.SlugField(unique=True) completed = models.BooleanField(default=False) def __str__(self): return self.title class SubSection(models.Model): sub_chapter = models.ForeignKey(SubChapter, on_delete=models.CASCADE) title = models.CharField(max_length=200, unique=True) slug = models.SlugField(unique=True) text = models.TextField(null=True, blank=False) completed = models.BooleanField(default=False) def __str__(self): return self.title def get_absolute_url(self): return reverse("course:detail", kwargs={"slug": self.sub_chapter.slug, "slug2": self.slug, "pk": self.sub_chapter.chapter.pk, } ) I want to redesign the app in way that only plain text is stored in the database but there's still a way to tell what is a subheading, a paragraph, a quote, a subscript etc so that when the a page is requested, the view can send a JSON response similar to this: response = { 0: {"type": "subheading", "content": "New subheading" }, 1: {"type": "paragraph", "content": "This is the first paragraph" }, 2: {"type": "quote", "content": "This is a quote" }, … -
Type of authentication when using HTTP and websockets
I have a website where I am using regular HTTP API requests and a websocket authenticated connection for realtime data. I am using token authentication for API requests, authenticating websocket connection upon connection via header token. I would however still like to somehow uniquely identify a "session", if a user was using the same token on two machines. Do I save a random string generated upon login along with the authentication token, to uniquely identify a session? Or did I go about this the wrong way and is token authentication really just not appropriate for my case? Because token authentication is just so much easier to implement on the frontend, as I am using React. -
Change page limit in test case
Question in short: how do I override the PAGE_SIZE setting of REST_FRAMEWORK in a test case in Django? Details about question: I have the following settings in my project's base.py: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'Masterdata.authentication.FashionExchangeAuthentication', ), 'DEFAULT_FILTER_BACKENDS': ( 'rest_framework.filters.DjangoFilterBackend', ), 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', 'PAGE_SIZE': 100 } Now I want to create a test case, in which I change the page size to 10. However, I cannot override this particular setting while keeping the rest of the dictionary intact. Does anyone know how to do so? This is what I tried: 1) Adding the modify_settings decorator above the test method: @modify_settings(REST_FRAMEWORK={ 'remove': 'PAGE_SIZE', 'append': {'PAGE_SIZE': 10} }) This does not change the setting. 2) Using override_settings as context manager: test_settings = settings.REST_FRAMEWORK test_settings['PAGE_SIZE'] = 10 with override_settings(REST_FRAMEWORK = test_settings): # do stuff However, the line with test_settings['PAGE_SIZE']=10 fails because apparently the variable settings.REST_FRAMEWORK is a list instead of a dictionary. print(settings.REST_FRAMEWORK) ['DEFAULT_PERMISSION_CLASSES', 'DEFAULT_AUTHENTICATION_CLASSES', 'DEFAULT_FILTER_BACKENDS', 'DEFAULT_PAGINATION_CLASS', 'DEFAULT_RENDERER_CLASSES'] How come this setting is a list here? I have verified that the variable is not overwritten anywhere else in the project. -
How to send xml data posted in post request by payment gateway to email using django
I have to integrate paystation payment gateway in my project, this gateway sends response using post url and sends data in post, so i have to send this response to my email so that i can see what variables we are getting in response. I an using this code but its not working. def payment_post(request): if request.method == 'POST': responseData = xmltodict.parse(request.POST.dict()) responseString = json.dumps(responseData) msg = EmailMultiAlternatives('Post Parameters', responseString, 'examplefrom@gmail.com', ['exampleto@gmail.com']) msg.send() This function works on the backend, so i can't check it, thats why i have to send it's response on my email id. I contacted to paystation server support, they said that its 500 error, and there is something problem in your code. Thats why i need help to solve this problem. Thanks -
django login users to their portal
I have couple of models and one of them is a foreign key to the user model that's extending django admin. I want to display what belongs to a user in their session upon login. I have defined this authentication that will check whether a particular user exist within the database and redirect them to their session with their instances. def auth_view(request): username = request.POST.get('username', '') password = request.POST.get('password', '') user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) return HttpResponseRedirect('/studentloggedin/') Basically, Registration is the first model and a foreign key to Student model, while Student is also a foreign key to UserLog. UserLog is extending the default django admin. I've defined the loggedin session here to filter out details of the individual users upon login. def studentloggedin(request): registration = Registration.objects.all() students = Student.objects.filter(registration=registration) alluser = UserLog.objects.filter(student=students) context = { 'registration': registration, 'students': students, 'alluser': alluser, } return render(request, "studentloggedin.html", context) Here is the template rendering the information upon login. <img {% for student in students %} src="{{ student.student_photo.url }}"> <p>{{ student.previous_school }}</p> {% endfor %} But I'm getting the below error: ProgrammingError at /studentloggedin/ more than one row returned by a subquery used as an expression -
Serializing subobject with foreign key with Django rest framework
serialization with django rest framework models.py from django.db import models class University( models.Model ): name = models.CharField( max_length = 50 ) createdTime = models.DateTimeField( auto_now_add=True ) updatedTime = models.DateTimeField( auto_now_add=True ) class Meta: verbose_name = "University" verbose_name_plural = "Universities" def __unicode__( self ): return self.name class Student( models.Model ): first_name = models.CharField( max_length = 50 ) ....... university = models.ForeignKey( University ) ....... @property def get_lookupName( self ): return self.first_name + self.last_name class Meta: verbose_name = "Student" verbose_name_plural = "Students" def __unicode__( self ): return '%s %s' % ( self.first_name , self.last_name ) serializers.py from rest_framework import serializers from .models import University, Student class UniversitySerializer( serializers.ModelSerializer ): class Meta: model = University fields = ( 'id' , 'name' ) class StudentSerializer( serializers.ModelSerializer ): class Meta: model = Student When i do a get on /students/1 i get this representation in json { "id": 1, "first_name": "Alok", "last_name": "Kumar", .......... "email_alt2": "something@invalid2.com", "university": 1 } but i want this representation : { "id": 1, "first_name": "YYYYYY", ........ "email_alt2": "something@invalid2.com", "university": { "id": 1, "name": XXXXX"", "links":[ { "rel": "self", "href": ".....api/universities/1" } ] } } Will i need to write a custom serializer for this ? -
getting Oauth 2 Invalid Client error while checking the application created in django project
I have created a project in django rest framework and installed django auth provider and created a application and generated the client id and client secret and when i am testing the application using curl request curl -X POST -d "grant_type=password&username=&password=" -u":" http://localhost:8000/o/token/ I tested by giving my username,password, client_id and client_request showing error like {"error": "invalid_client"} settings.py OAUTH2_PROVIDER = { # this is the list of available scopes 'SCOPES': {'read': 'Read scope', 'write': 'Write scope', 'groups': 'Access to your groups'} } REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'oauth2_provider.ext.rest_framework.OAuth2Authentication', ) } -
Installation of Neomodel raised error
I'm trying to install the library Neomodel to use Neo4j in my Django application but it raised many errors: Exception: Traceback (most recent call last): File "/Library/Python/2.7/site-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/Library/Python/2.7/site-packages/pip/commands/install.py", line 342, in run prefix=options.prefix_path, File "/Library/Python/2.7/site-packages/pip/req/req_set.py", line 778, in install requirement.uninstall(auto_confirm=True) File "/Library/Python/2.7/site-packages/pip/req/req_install.py", line 754, in uninstall paths_to_remove.remove(auto_confirm) File "/Library/Python/2.7/site-packages/pip/req/req_uninstall.py", line 115, in remove renames(path, new_path) File "/Library/Python/2.7/site-packages/pip/utils/__init__.py", line 267, in renames shutil.move(old, new) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 299, in move copytree(src, real_dst, symlinks=True) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 208, in copytree raise Error, errors Error: [('/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pytz/__init__.py', '/tmp/pip-rVZOK9-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pytz/__init__.py', "[Errno 1] Operation not permitted: '/tmp/pip-rVZOK9-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pytz/__init__.py'") There errors message is a lot of longer but I reduced it to be more concise. Also all the error are the same (Permission Denied). I try to install it using the command: sudo pip install neomodel I have never seen such an error and really don't know what to do to fix. Any help would be welcome. -
How to convert plain text to hashed password in django
I am new to django. Already migrated from sqlite to MySQL. User related information is store in auth_user table. I have 100 users related usernames and password is plain text. I need to insert into auth_user table. How can i do that? For example i inserting manually like below insert statement. INSERT INTO `auth_user` (username, `password`, is_superuser ) VALUES ('test', 'test_password', 0) If i inserting like that i shows plain text password. I want django hash password. Please help me with this -
deploy Django 1.10 project with Python 3.5 to Azure
just wanna know if I can deploy Django 1.10 project with Python 3.5 to Azure Cloud? I mean, I do not develop it using Visual Studio but only text editor (Atom or Sublime),,thank you -
How to convert Foreign Key Field into Many To Many Field without disturbing existing data in the database?
class Table1(models.Model): name = models.CharField(max_length=20) class Table2(models.Model): name = models.CharField(max_length=20) description = models.TextField() table1 = models.ForeignKey(Table1) Consider, Both the table has data into the database, But What is the possible way to convert the Foreign Key Field(in Table2) into Many To Many Field without losing existing data in database? Note: I am using Django 1.6.4 -
Getting error: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet while installing oauth2 provider in django rest framework
I am trying to install django-oauth2-provider in django. after installing and configuring settings.py,during migrations i am getting the error like. django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'hello_api', 'rest_framework.authtoken', 'provider', 'provider.oauth2', ] 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', #'corsheaders.middleware.CorsMiddleware', ] ROOT_URLCONF = 'hello_api2.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] error: File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/ravi/PycharmProjects/hello-api2/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/home/ravi/PycharmProjects/hello-api2/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 341, in execute django.setup() File "/home/ravi/PycharmProjects/hello-api2/venv/local/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/ravi/PycharmProjects/hello-api2/venv/local/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/home/ravi/PycharmProjects/hello-api2/venv/local/lib/python2.7/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/ravi/PycharmProjects/hello-api2/venv/local/lib/python2.7/site-packages/provider/oauth2/__init__.py", line 1, in <module> import backends File "/home/ravi/PycharmProjects/hello-api2/venv/local/lib/python2.7/site-packages/provider/oauth2/backends.py", line 2, in <module> from .forms import ClientAuthForm, PublicPasswordGrantForm File "/home/ravi/PycharmProjects/hello-api2/venv/local/lib/python2.7/site-packages/provider/oauth2/forms.py", line 10, in <module> from .models import Client, Grant, RefreshToken File "/home/ravi/PycharmProjects/hello-api2/venv/local/lib/python2.7/site-packages/provider/oauth2/models.py", line 23, in <module> class Client(models.Model): File "/home/ravi/PycharmProjects/hello-api2/venv/local/lib/python2.7/site-packages/django/db/models/base.py", line 105, in __new__ app_config = apps.get_containing_app_config(module) File "/home/ravi/PycharmProjects/hello-api2/venv/local/lib/python2.7/site-packages/django/apps/registry.py", line 237, in get_containing_app_config self.check_apps_ready() File "/home/ravi/PycharmProjects/hello-api2/venv/local/lib/python2.7/site-packages/django/apps/registry.py", line 124, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps … -
Why bootstrap doesn't work although I have loaded it, etc. (Django project)?
I'm working on this Django project. The functionality works perfectly fine. When I started working on the front-end using Bootstrap3, I ran into some issues (more like confusions). First, I installed django-bootstrap3 using command prompt like so: pip install django-bootstrap3 The installation was successful. Bootstrap3 was downloaded into this location in my computer c:\python34\lib\site-packages Then, I included it as a third-party app in settings.py in the list of INSTALLED_APPS in my main project directory like so: INSTALLED_APPS =( --apps-- 'bootstrap3', ) Also in settings.py, I included jQuery like so: BOOTSTRAP3 = {'include_jquery': True} I modified my base.html to include the bootstrap elements. I have two apps, users and mynotess (sorry for bad naming) base.html {% load bootstrap3 %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"><!-- encoding characters --> <meta http-equiv="X-UA-Compatible" content="IE=edge"><!-- some Microsoft Edge/IE stuff --> <meta name="viewport" content="width=device-width, initial-scale=1"><!-- viewport -> the user's visible area of a webpage, -> this sets it to normal zoom (scale 1) and width of device --> <title>My Notes</title {% bootstrap_css %} {% bootstrap_javascript %} </head> <body> <!-- Static top navbar --> <nav class="navbar navbar-default navbar-static-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data target="#navbar" aria-expanded="false" aria-controls="navbar"></button> <a class="navbar-brand" href="{% url 'mynotess:index' … -
Django can't find redirect url when authenticating user
I am trying to login protect some of my pages, including my dashboard. Here is the view for my dashboard at the root of my site: sitename.com/ @login_required def index(request): print(request.session['user_email']) context_dict = {} return render(request, 'dashboard/index.html', context_dict) My project url file: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^job/', include('job.urls')), url(r'^welcome/', include('welcome.urls')), //the app for logging in url(r'^$', include('dashboard.urls')), //main dashboard app # s ] My dashboard app url file: urlpatterns = [ url(r'$', views.index, name='index'), url(r'^signup/$', views.signup, name='signup'), url(r'^login/$', views.auth_login, name='login'), url(r'^logout/$', views.user_logout, name='logout'), ] When I try and logout and then go to / I get a message saying that http://127.0.0.1:8000/welcome?next=/ doesn't match any urls in my project urls file. So the login check is working, it just can't figure out the url when the GET variable next is set. -
python django scrapy return item to controller
I need to do some short real-time scraping and return the resulted data in my Django REST controller. trying to make use scrapy: import scrapy from scrapy.selector import Selector from . models import Product class MysiteSpider(scrapy.Spider): name = "quotes" start_urls = [ 'https://www.something.com/browse?q=dfd', ] allowed_domains = ['something.com'] def parse(self, response): items_list = Selector(response).xpath('//li[@itemprop="itemListElement"]') for value in items_list: item = Product() item['picture_url'] = value.xpath('img/@src').extract()[0] item['title'] = value.xpath('h2').text() item['price'] = value.xpath('p[contains(@class, "ad-price")]').text() yield item items model import scrapy class Product(scrapy.Item): name = scrapy.Field() price = scrapy.Field() picture_url = scrapy.Field() published_date = scrapy.Field(serializer=str) according to Scrapy architecture, items will be returned to the Item Pipeline (https://doc.scrapy.org/en/1.2/topics/item-pipeline.html) which is used to store the data to DB/save to files and so on. However i'm stuck with the question - how can i return the scraped items list through the Django REST APIview? -
How to convert APIView to ModelViewSet
I have a working Django-REST-framework APIView code. I want to rewrite that snippet to ModelViewSets. I found some basic here, but my input is little complicated here is my input code, class UsualLoginClass(APIView): def post(self,request): email=request.data.get('email') password=request.data.get('password') if (UserInformation.objects.filter(emailID=email).exists() and UserInformation.objects.filter(password=password).exists()): dbObject=UserInformation.objects.get(emailID=email) serializer = LoginSerializer(dbObject) userID=serializer.data.get('id') token=tokenGenerator(50) UserInformation.objects.filter(pk=userID).update(currentToken=token) return Response(data={"id":userID,"token":token}) else: return Response(data={"detail":"Email and Password are not machting"}) Ignore my logic . -
Way to pass JavaScript variable to Django
Is JSON the unic way to pass variable from JavaScript to Django and Django JavaScript? Thank you -
Can we call python script from jquery (While working with django)
can we call python script from jquery(while working with django framework). if yes then how we can do that.Please explain step by step (Since i am new to django and jquery) -
AngularJS error : Module Error. fixing typo doesn't apply and keeping causing error
I am new in Angular. I was following the tutorial of Thinkster : Building Web Applications with Django and AngularJS. Tutorial code is like below. Once I made a mistake and made typo 'otherwisde'. I should have written otherwise of course. So I collected the typo. But It keep causing error. It kept showing 'TypeError: $routeProvider.when(...).otherwisde is not a function' in console. angular js part (function() { 'use strict'; angular .module('thinkster.routes') .config(config); config.$inject = ['$routeProvider']; /** * @name config * @desc Define valid application routes */ function config($routeProvider) { $routeProvider.when('/register', { controller: 'RegisterController', controllerAs: 'vm', templateUrl: '/static/templates/authentication/register.html' }).otherwise('/'); } })(); script files {% load staticfiles %} <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular-route.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular-cookies.js"></script> <script type="text/javascript" src="{% static 'javascripts/thinkster.js' %}"></script> <script type="text/javascript" src="{% static 'javascripts/thinkster.config.js' %}"></script> <script type="text/javascript" src="{% static 'javascripts/thinkster.routes.js' %}"></script> <script type="text/javascript" src="{% static 'javascripts/authentication/authentication.module.js' %}"></script> <script type="text/javascript" src="{% static 'javascripts/authentication/services/authentication.service.js' %}"></script> <script type="text/javascript" src="{% static 'javascripts/authentication/controllers/register.controller.js' %}"></script> whole error Uncaught Error: [$injector:modulerr] Failed to instantiate module thinkster due to: Error: [$injector:modulerr] Failed to instantiate module thinkster.routes due to: TypeError: $routeProvider.when(...).otherwisde is not a function at config (http://127.0.0.1:8000/static/javascripts/thinkster.routes.js:19:6) at Object.invoke (https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.js:4708:19) at runInvokeQueue (https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.js:4601:35) at https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.js:4610:11 at forEach (https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.js:322:20) at loadModules (https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.js:4591:5) at https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.js:4608:40 at forEach (https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.js:322:20) at loadModules (https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.js:4591:5) … -
Django how to see generated SQL query?
I have a form which takes data and is supposed to insert it in a Database. When I am processing that form it gives me a value error. But when I go to database and try to insert it manually it works fine. In order to debug this situation I want to see what query django is generating which is failing. On the debug webpage I didn't see anything like sql query. How can I see the actual query generated by django?? Please advise. Thanks. -
Django: Global persistent object shared across users
I am new to Django and Python and am trying to implement a networking game that I already have running in Java/JSP. An administrator sets up the game and multiple users log in, select their friends (from within the users logged in) to form a network and send messages to each other based on the objectives given to them. Now in Java, I used a static list to store all active Game objects (in practice, only one game at a time). This way any request that had the game ID (stored in session) could access/modify the corresponding Game object, and in turn the network, messages etc. Once the game ended, I removed the Game from the list. So all of this happened in memory and would be stored in the database only after the game ended (to enable users to access results/scores later). Is there a way to do this in Python/Django? The more I read about this the more I get confused about sharing a single object across users/apps(/processes?). From what I have read it seems like I can declare an object (Game list) at the module level in one of the apps, but it is not a good …