Saturday, September 30, 2017

Setting up Django for the first time, urls.py and settings.py

I'm playing with Django for the first time.  I am using a guide called, "Python from Scratch - Creating a Dynamic Website"  by [b]Tuts+ Code[/b] from YouTube.  It's kinda old.  It was first posted in November 2011 and Django has evolved considerably.  I've had to try different commands, like 'syncdb' is no longer used.  Now it's 'migrate'. Yes, Tuts+ Code is over 6 years old, but it's the best tutorial in terms of explanations and teaching style. Anyways.


I'm getting an error saying there is something wrong with my settings.py:

$ python ../manage.py runserver
Performing system checks...
Unhandled exception in thread started by <function wrapper at 0x7fe4876e76e0>
Traceback (most recent call last):
 File "/home/gnull/.local/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper
   fn(*args, **kwargs)
 File "/home/gnull/.local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run
   self.check(display_num_errors=True)
 File "/home/gnull/.local/lib/python2.7/site-packages/django/core/management/base.py", line 359, in check
   include_deployment_checks=include_deployment_checks,
 File "/home/gnull/.local/lib/python2.7/site-packages/django/core/management/base.py", line 346, in _run_checks
   return checks.run_checks(**kwargs)
 File "/home/gnull/.local/lib/python2.7/site-packages/django/core/checks/registry.py", line 81, in run_checks
   new_errors = check(app_configs=app_configs)
 File "/home/gnull/.local/lib/python2.7/site-packages/django/core/checks/urls.py", line 16, in check_url_config
   return check_resolver(resolver)
 File "/home/gnull/.local/lib/python2.7/site-packages/django/core/checks/urls.py", line 26, in check_resolver
   return check_method()
 File "/home/gnull/.local/lib/python2.7/site-packages/django/urls/resolvers.py", line 254, in check
   for pattern in self.url_patterns:
 File "/home/gnull/.local/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__
   res = instance.__dict__[self.name] = self.func(instance)
 File "/home/gnull/.local/lib/python2.7/site-packages/django/urls/resolvers.py", line 405, in url_patterns
   patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
 File "/home/gnull/.local/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__
   res = instance.__dict__[self.name] = self.func(instance)
 File "/home/gnull/.local/lib/python2.7/site-packages/django/urls/resolvers.py", line 398, in urlconf_module
   return import_module(self.urlconf_name)
 File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
   __import__(name)
 File "/home/gnull/Dropbox/TECH/python/2017/beginning-Django/G_Thomas/G_Thomas/urls.py", line 21, in <module>
   url(r'^$', 'blog.views.home', name='home')
 File "/home/gnull/.local/lib/python2.7/site-packages/django/conf/urls/__init__.py", line 85, in url
   raise TypeError('view must be a callable or a list/tuple in the case of include().')
TypeError: view must be a callable or a list/tuple in the case of include().


Those last couple of lines in this error message are instructive. I'm not sure about the case of include() in urls.py but my url declaration indeed is a tuple.  Why is my shell telling me there is something wrong with my tuple when it should be a tuple?  I also swapped out the parentheses with square brackets to see if it would take a list as it says it can.  Either way, same error.


Here are the contents of my urls.py:


from django.conf.urls import *
from django.contrib import admin
admin.autodiscover()
urlpatterns = ['',
    # url(r'^admin/', admin.site.urls),
url(r'^$', 'blog.views.home', name='home')
]


Take note of the square brackets and lack of the patterns function (as compared to the presence of the function in the code from the teacher below). Also commented out above is the default urlpattern that came with Django 1.11.  


So the urlpattern in Tuts+ Code's actually looks like this:


from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
urlpatterns = patterns ('',
url(r'^$', 'FirstBlog.views.home', name='home'),
)


Addressing a related issue with importing the name pattern in urls.py for Django, some folks over on stackoverflow describe their Djanog urls.py configuration file use a simple variable declaration for urlpatterns and don't bother with the function patterns() the way the YouTuber explains that it should look like.  Like, the YouTuber uses: 'urlpatterns = patterns( ... )' whereas the stackoverflow people set it as: 'urlpatterns = [ '', ...]'.  


I get the sense that I am slightly off in my understanding of the issue. Based on what you see in the traceback, what could be going on with  my scripts?


Is there any other information I could provide?


Thanks in advance.


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/335764e9-ff16-4460-9e14-ce535b90bbfe%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Help with staticfiles in deployment

Hello,

My site is deployed on an ubuntu/nginx/gunicorn droplet on digitalOcean. For some reason my static files are not updating after running collectstatic. I have access to older static files but cant make updates to static files and see them in production. It works as it should on my development computer. Its kind of like my staticfiles storage is some CDN that I wasnt aware of and now when I run collectstatic its not putting the files in the CDN anymore

Below is my base settings configuration

# settings/base.py

import environ

ROOT_DIR = environ.Path(__file__) - 3  # (business_management/config/settings/base.py - 3 = business_management/)
APPS_DIR = ROOT_DIR.path('business_management')

# Load operating system environment variables and then prepare to use them
env = environ.Env()

# .env file, should load only in development environment
READ_DOT_ENV_FILE = env.bool('DJANGO_READ_DOT_ENV_FILE', default=False)

if READ_DOT_ENV_FILE:
    # Operating System Environment variables have precedence over variables defined in the .env file,
    # that is to say variables from the .env files will only be used if not defined
    # as environment variables.
    env_file = str(ROOT_DIR.path('.env'))
    print('Loading : {}'.format(env_file))
    env.read_env(env_file)
    print('The .env file has been loaded. See base.py for more information')


# DEBUG
# ------------------------------------------------------------------------------
# See: https://docs.djangoproject.com/en/dev/ref/settings/#debug
DEBUG = env.bool('DJANGO_DEBUG', False)


# Application definition
# ------------------------------------------------------------------------------

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    
    'django.contrib.sites',
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'allauth_office365',
    
    'bootstrap4',
    
    'business_management.accounts',
    'business_management.engineering',
]

#SOCIALACCOUNT_ADAPTER = 'allauth_office365.adapter.SocialAccountAdapter'
SOCIALACCOUNT_EMAIL_VERIFICATION = False

SOCIALACCOUNT_PROVIDERS = {
    'office365': {
      'SCOPE': ['User.read',],
      'USERNAME_FIELD': 'mail'
    }
}

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',
]

ROOT_URLCONF = 'config.urls'


TEMPLATES = [
    {
        # See: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-TEMPLATES-BACKEND
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-dirs
        'DIRS': [
            str(APPS_DIR.path('templates')),
        ],
        'OPTIONS': {
            # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-debug
            'debug': DEBUG,
            # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-loaders
            # https://docs.djangoproject.com/en/dev/ref/templates/api/#loader-types
            'loaders': [
                'django.template.loaders.filesystem.Loader',
                'django.template.loaders.app_directories.Loader',
            ],
            # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-context-processors
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.template.context_processors.i18n',
                'django.template.context_processors.media',
                'django.template.context_processors.static',
                'django.template.context_processors.tz',
                'django.contrib.messages.context_processors.messages',
                # Your stuff: custom template context processors go here
            ],
        },
    },
]


WSGI_APPLICATION = 'config.wsgi.application'


# Password validation
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

AUTHENTICATION_BACKENDS = (
    # Needed to login by username in Django admin, regardless of `allauth`
    'django.contrib.auth.backends.ModelBackend',
    # `allauth` specific authentication methods, such as login by e-mail
    'allauth.account.auth_backends.AuthenticationBackend',
)


# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
# ------------------------------------------------------------------------------
LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'America/Denver'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders
STATICFILES_FINDERS = [
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]


# AllAuth Settings
# ------------------------------------------------------------------------------

AUTH_USER_MODEL = 'accounts.User'

SITE_ID = 1

LOGIN_REDIRECT_URL = 'dashboard'
ACCOUNT_EMAIL_REQUIRED = True # email required to signup
ACCOUNT_EMAIL_VERIFICATION = False # email verification manditory for account verification
ACCOUNT_AUTHENTICATION_METHOD = "username_email" # username or email
#ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = True
#VERIFIED_EMAIL = True
#ACCOUNT_FORMS = {'login': 'accounts.forms.MyLoginForm', 'sign_up': 'accounts.forms.MySignupForm'}
ACCOUNT_LOGIN_ATTEMPTS_LIMIT = 5
ACCOUNT_LOGIN_ATTEMPTS_TIMEOUT = 300
#ACCOUNT_SIGNUP_FORM_CLASS = 'business_management.accounts.forms.UserCreateForm'
ACCOUNT_USERNAME_MIN_LENGTH = 4
ACCOUNT_LOGOUT_REDIRECT_URL = 'account_login'
#ACCOUNT_SESSION_REMEMBER = None # Controls the life time of the session. Set to None to ask the user 'Remember me?', False to not remember, and True to always remember.


and below is my production settings (sensitive data omitted)...

from .base import *

import json


DEBUG = False

WHITENOISE_MIDDLEWARE = ['whitenoise.middleware.WhiteNoiseMiddleware', ]
MIDDLEWARE = WHITENOISE_MIDDLEWARE + MIDDLEWARE

INSTALLED_APPS += ['gunicorn', ]

# Static File Configuration
# ------------------------------------------------------------------------------
# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-root
STATIC_ROOT = str(ROOT_DIR('staticfiles'))

# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-url
STATIC_URL = "/staticfiles/"

# See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS
STATICFILES_DIRS = [
    str(APPS_DIR.path('static')),
]

When i run collectstatic new static files are going to the staticfolder where I expect them to go also. Thanks for your help!

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/3e9f167b-6c09-4dec-85b2-a1617a37646e%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Adding support for postgres 10

Postgres10 RC1 has been released recently with some exciting feature such as native partitioning. I have created this DEP to discuss about adding pg10 support to the django.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/156935af-ef59-4fd1-ac2e-44714c73a767%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Re: get_ip_address() not working when used Custom Decorators

Hello Constantine C,

Thanks for your reply!

What do you mean to say just one place ?
I just printed the request using `print(request)` and getting this `<function all at 0x7f6ffc65a050>` ( don't know what this actually is )

Am i using the following approach.
On Saturday, September 30, 2017 at 8:08:22 AM UTC+5:30, Constantine Covtushenko wrote:
Hi Mannu,

It seems like all are ok.
Sorry, but do you use it in just one place?
And do you see response in console from your print?

Regards,
Constantine C.

On Thu, Sep 28, 2017 at 4:36 PM, Mannu Gupta <abhiman...@gmail.com> wrote:
I am just using it in a view function. For example:-

@owner_required
def all(request, **kwargs):
   
pass


On Friday, September 29, 2017 at 12:33:09 AM UTC+5:30, Mannu Gupta wrote:
While making a customer decorator in django, the code is here :-

def owner_required(function):
   
def wrap(request, *args, **kwargs):
       
print(request)
        ip_address
= get_client_ip(request)
        ip_exist
= Node.objects.get(ip_address=ip_address)
       
if ip_exist:
           
return function(request, *args, **kwargs)
       
else:
           
raise PermissionDenied
   
return wrap

my code for get_ip_address() is :-

def get_client_ip(request):
   
""" Extract ip address from a Django request object
    """

    x_forwarded_for
= request.META.get('HTTP_X_FORWARDED_FOR')
   
if x_forwarded_for:
        ip
= x_forwarded_for.split(',')[0]
   
else:
        ip
= request.META.get('REMOTE_ADDR')
   
return ip

The error i am getting is :-

x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
AttributeError: 'function' object has no attribute 'META'


That get_client_ip() is working fine when used in normal function, but don't know why it is not working when i am using it a decorator.

What might be the problem ?

Thanks in advance for replies.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/0e34ae73-5697-4a93-9402-c0ca1f4abd70%40googlegroups.com.

For more options, visit https://groups.google.com/d/optout.



--
Sincerely yours,
Constantine C

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/69879830-d7ad-4914-a8d4-7ac1ba1d8241%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Re: Auth Password Change template not working

I'd temporarily remove the built-in template that's being loaded so that TemplateDoesNotExist is raised. The debug page will show the locations that Django searched for the template.

On Wednesday, September 27, 2017 at 7:10:54 AM UTC-4, naitik gala wrote:
Hi all,

I am trying to add my own designed html to Auth urls.

One way obviously is to create my own view and implement Auth urls for them. Here, I will explicitly mention the html template that i have created. It would be like any other view that we would create.

But, there seems to be an alternate method. We can reuse the views already created in Auth module.

By reference of documentations, I made following steps:

1. created an html template 'myproject/myapp/templates/registration/login.html'
2. updated 'myproject/myproject/urls.py' with following

urlpatterns = [
    url
(r'^admin/', admin.site.urls),
    url
('', include('django.contrib.auth.urls')),
    url
(r'^', include('myapp.urls')),
]

This successfully worked for /login/ i.e. it showed my custom template.

It however now fails if I created for /password_change/ as i created 2 files for that 'myporject/myapp/templates/registration/password_change_form.html' and 'myporject/myapp/templates/registration/password_change_done.html'

Is this a bug or I am missing something? Please help.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/65cbb070-229e-462b-b302-e73debd93675%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Re: How safe is it to use sys.exit() in custom commands

I don't know of any reason why that would be unsafe. You'll find several uses of sys.exit() in Django's built in commands located in django/core/management/commands.

On Friday, September 29, 2017 at 5:13:50 PM UTC-4, phep wrote:
Hi,

Executive summary : everything's in the subject line.

Boring details :

I have a Django application where I use a lot of custom commands, most being
designed to be launched mostly by cron-jobs or other bash scripts of some
sorts. In this respect, the exit code value may be of utmost importance.

Up until now, as I focused on the business logic part, when things went
wrong I just raised exceptions so that the return code was set to 1. So good
so far. The problem is the output is rather uselessly verbose then. I'm in
the process of fixing things up in order to have some more concise output on
failures.

It seems to me I once read in the doc that one should not use sys.exit() in
custom commands, but can't find exactly where it was - but I found some
allusions about this in StackOverflow comments. Yet I just sgoogumbled on
this ticket https://code.djangoproject.com/ticket/25419 where it seems safe
to use it.

AFAIAC, I would be using sys.exit() almost exclusively at the top level
inside the handle() method, while testing sub-routines return values of
catching exceptions. Tests I've run seems show this is working as I'd
expected, but I'd like to be sure there is no hidden traps before to deploy
this code on the production server.

So what is your take on this question ?

Thanks in advance,

phep

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/073d81cb-9fcf-4cce-9d57-3e34f184df67%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Re: Bug to set session in Django Test?

There's a test in Django's test suite for this: https://github.com/django/django/blob/fd866c25d1665b73aff0d8312c414ae6f69812a3/tests/test_client_regress/tests.py#L1009-L1015

I guess you'll need to figure out how your project differs from that.

On Saturday, September 30, 2017 at 6:30:25 AM UTC-4, ThePhi wrote:
 Hi!

I have troubles setting cookie in Django test.

class Test_views(TestCase):        def test_set_cookie(self):          session = self.client.session          session['mycookie'] = 'testcookie'          session.save()          response = self.c.get(reverse('homepage'))           ...

I print the cookies in the Views to be sure:

views.py

...   def homepage(request):          print(request.session.keys())          ...

And indeed, the cookie mycookie doesn't exist.


Is it a bug?

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/14c2d75d-9438-4ca0-819e-b5f009ca6ce3%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Re: Django admin: is there an event, or another way to call a Javascript function, when a Django Admin Popup (the green plus icon) completes ?

Opened a new thread on django-developers: https://groups.google.com/d/msg/django-developers/BsudgRRCKb4/airBUyhaAwAJ



On Saturday, September 30, 2017 at 6:32:51 PM UTC+2, Federico Capoano wrote:
Hi James,

I was banging my head on the wall for this issue, you saved me some precious time, thank you!

I wonder why such a mechanism is not included by default into Django, I will bring up this issue on the development mailing list.

Federico



On Thursday, November 26, 2015 at 11:58:22 AM UTC+1, James Murty wrote:
Hi,

Below is a Javascript file with the hackery we use to trigger a change event when the add/change popup window is dismissed, which works for Django 1.7 at least.

Hopefully it will help, or at least point you in the right direction.

Regards,
James

/*
 * Trigger change events when Django admin's popup window is dismissed
 */
(function($) {
    $(document).ready(function() {

        // HACK to override `dismissRelatedLookupPopup()` and
        // `dismissAddAnotherPopup()` in Django's RelatedObjectLookups.js to
        // trigger change event when an ID is selected or added via popup.
        function triggerChangeOnField(win, chosenId) {
            var name = windowname_to_id(win.name);
            var elem = document.getElementById(name);
            $(elem).change();
        }
        window.ORIGINAL_dismissRelatedLookupPopup = window.dismissRelatedLookupPopup
        window.dismissRelatedLookupPopup = function(win, chosenId) {
            ORIGINAL_dismissRelatedLookupPopup(win, chosenId);
            triggerChangeOnField(win, chosenId);
        }
        window.ORIGINAL_dismissAddAnotherPopup = window.dismissAddAnotherPopup
        window.dismissAddAnotherPopup = function(win, chosenId) {
            ORIGINAL_dismissAddAnotherPopup(win, chosenId);
            triggerChangeOnField(win, chosenId);
        }

    });
})(jQuery);



On Wednesday, 25 November 2015 21:39:06 UTC+11, boito...@gmail.com wrote:
Hi,

  I see this question is not receiving a lot of love. Perhaps we can try to approach it differently then:
 What is the mechanism that populates back the parentform select once the pop-up form is completed and saved ? (As I have very limited experience with front-end web technologies, I would not know where to look for the code implementing that functionnality).

From here, perhaps we can try to hook some custom Javascript.

Thank you for reading,
  Ad

Le vendredi 20 novembre 2015 09:55:10 UTC+1, boito...@gmail.com a écrit :
Hi,

  We are developing an application that relies on dynamic admin pages (based on some custom ajax). The high level idea is that, when the user changes the value in a select html element that is mapped to a ForeignKey on another model, we call a JS function (which triggers an asynchronous request that changes the current admin form on completion).


To achieve that, we listen to the change event of said select (to call the JS function when it is fired), which works fine when the user clicks a value directly in the drop-down menu proposed by the select.

Sadly, when this select is populated through the Admin Popup functionality (the process that starts by clicking the green plus icon to open a popup window, and that completes when the user click the save button on the popup window), it seems that the change event is not fired for the select, as our callback is not executed, even though the selected value is actually changed.

Is there another event we can listen to to get the same behaviour than when the user clicks a value directly from the list ? Or any other method to call our JS function when the select value is set through the popup completion ?

Thank you for reading,
  Ad

(Full disclosure: I first tried my luck with a question on SO, without great success)

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/6172c177-174d-46f5-9018-e016ff58d092%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Re: Django admin: is there an event, or another way to call a Javascript function, when a Django Admin Popup (the green plus icon) completes ?

Hi James,

I was banging my head on the wall for this issue, you saved me some precious time, thank you!

I wonder why such a mechanism is not included by default into Django, I will bring up this issue on the development mailing list.

Federico



On Thursday, November 26, 2015 at 11:58:22 AM UTC+1, James Murty wrote:
Hi,

Below is a Javascript file with the hackery we use to trigger a change event when the add/change popup window is dismissed, which works for Django 1.7 at least.

Hopefully it will help, or at least point you in the right direction.

Regards,
James

/*
 * Trigger change events when Django admin's popup window is dismissed
 */
(function($) {
    $(document).ready(function() {

        // HACK to override `dismissRelatedLookupPopup()` and
        // `dismissAddAnotherPopup()` in Django's RelatedObjectLookups.js to
        // trigger change event when an ID is selected or added via popup.
        function triggerChangeOnField(win, chosenId) {
            var name = windowname_to_id(win.name);
            var elem = document.getElementById(name);
            $(elem).change();
        }
        window.ORIGINAL_dismissRelatedLookupPopup = window.dismissRelatedLookupPopup
        window.dismissRelatedLookupPopup = function(win, chosenId) {
            ORIGINAL_dismissRelatedLookupPopup(win, chosenId);
            triggerChangeOnField(win, chosenId);
        }
        window.ORIGINAL_dismissAddAnotherPopup = window.dismissAddAnotherPopup
        window.dismissAddAnotherPopup = function(win, chosenId) {
            ORIGINAL_dismissAddAnotherPopup(win, chosenId);
            triggerChangeOnField(win, chosenId);
        }

    });
})(jQuery);



On Wednesday, 25 November 2015 21:39:06 UTC+11, boito...@gmail.com wrote:
Hi,

  I see this question is not receiving a lot of love. Perhaps we can try to approach it differently then:
 What is the mechanism that populates back the parentform select once the pop-up form is completed and saved ? (As I have very limited experience with front-end web technologies, I would not know where to look for the code implementing that functionnality).

From here, perhaps we can try to hook some custom Javascript.

Thank you for reading,
  Ad

Le vendredi 20 novembre 2015 09:55:10 UTC+1, boito...@gmail.com a écrit :
Hi,

  We are developing an application that relies on dynamic admin pages (based on some custom ajax). The high level idea is that, when the user changes the value in a select html element that is mapped to a ForeignKey on another model, we call a JS function (which triggers an asynchronous request that changes the current admin form on completion).


To achieve that, we listen to the change event of said select (to call the JS function when it is fired), which works fine when the user clicks a value directly in the drop-down menu proposed by the select.

Sadly, when this select is populated through the Admin Popup functionality (the process that starts by clicking the green plus icon to open a popup window, and that completes when the user click the save button on the popup window), it seems that the change event is not fired for the select, as our callback is not executed, even though the selected value is actually changed.

Is there another event we can listen to to get the same behaviour than when the user clicks a value directly from the list ? Or any other method to call our JS function when the select value is set through the popup completion ?

Thank you for reading,
  Ad

(Full disclosure: I first tried my luck with a question on SO, without great success)

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/ff3a3421-11ca-4a17-99f3-c427240b6941%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Re: online training application


On Thursday, September 28, 2017 at 11:02:58 AM UTC+5:30, Mike Dewhirst wrote:
I need to write an online training application - except I don't know a
lot about online training.

Please, have a look at OpenEdx[1]. It is also a LMS like Moodle written using Django. 

[1]: https://open.edx.org/

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/26bd58fe-0034-45fc-bccb-e85b8f3379f3%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Re: Updating an instance.

Thanks for the help.....Cheers.

On Saturday, September 30, 2017 at 6:28:20 PM UTC+5:30, Constantine Covtushenko wrote:
Sounds good!

Have a great day

On Sat, Sep 30, 2017 at 1:45 AM, Mitul Tyagi <mitult...@gmail.com> wrote:
It is done.....
On Saturday, September 30, 2017 at 8:55:45 AM UTC+5:30, Mitul Tyagi wrote:

My form field is :

class CityForm(forms.ModelForm):
    class Meta:
        model = City
        fields = ['city1', 'city2', 'city3', 'city4', 'city5', 'userName']
        widgets = {
            'city1': autocomplete.Select2(url='city-autocomplete'),
            'city2': autocomplete.Select2(url='city-autocomplete'),
            'city3': autocomplete.Select2(url='city-autocomplete'),
            'city4': autocomplete.Select2(url='city-autocomplete'),
            'city5': autocomplete.Select2(url='city-autocomplete'),
        }

On Saturday, September 30, 2017 at 7:41:40 AM UTC+5:30, Constantine Covtushenko wrote:
Dear Mitui,

I saw 2 questions in your inquiry:
1. Regarding to Form behaviour
2. Regarding to log message

Let me clarify second:
Provided message said that server responded with 302 - redirect response.
It is correct as you said in your view method:
return HttpResponseRedirect('/login/response/'+str(a.userName.username))

Now is about first.
You printed 'using instance argument'. I asume that you are looking of a way add user info to POST data using form. It does not work in this way. That is why user info is cleared.

Initial value is used to pre populate form when it is no POST data yet, like when you generate form on GET response.

To get what you need I would suggest add user info differently.
You have some options here.

1 - change your form - remove user field from it. You did not provide code of your form. But I believe that you are using user field in the form.
2 - add user info to POST query. It is not recommended way as this POST QuerySet is immutable. So to do that you need to create new QuerySet from previous one and put user info there.

I hope that make some sense.

Regards,
Constantine C.

On Fri, Sep 29, 2017 at 3:11 PM, Mitul Tyagi <mitult...@gmail.com> wrote:
<form role="text" action="" method="post">
{% csrf_token %}
<ul>
<li class="bar">1st City: {{form.city1}}</li>
<li class="bar">2nd City: {{form.city2}}</li>
<li class="bar">3rd City: {{form.city3}}</li>
<li class="bar">4th City: {{form.city4}}</li>
<li class="bar">5th City: {{form.city5}}</li>

</form>
Is the template part.....

On Saturday, September 30, 2017 at 12:16:07 AM UTC+5:30, Mitul Tyagi wrote:
Problem 1 :
I have a model with  six fields. One is userName and other five are five favourite cities.....I want to update these five cities....but when I update them using instance argument the userName becomes NONE....I am using the id field to update....the cities are updated for the id but the userName is lost. Any help for that..The code I am using is 
"
def Update(request, city_id):
    if request.method == "POST":
        a= City.objects.get(pk= int(city_id))      
        print "User Updated is : ",a.userName.username                        
        f = CityForm(request.POST, instance=a, initial={'userName.': str(a.userName.username)})
        f.save()
        return HttpResponseRedirect('/login/response/'+str(a.userName.username))
    else:
        all_city = City.objects.all()
        for city in all_city:
            if int(city.pk) == int(city_id):
                a = city
        print "User: ",a.userName.username        
        form_class = CityForm(initial={'userName': a.userName})
        return render(request, 'formsub.html', {'form': form_class,'x':a.userName.username,'id':a.id})     
There is an error in the method also...
Console prints this whenever post request is made.
" [29/Sep/2017 18:43:43] "POST /login/update/18/ HTTP/1.1" 302 0
"

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/0e0dc653-92fe-4c3a-9cf5-e9d2de3cb274%40googlegroups.com.

For more options, visit https://groups.google.com/d/optout.



--
Sincerely yours,
Constantine C

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/e2edcae9-7b65-452c-b485-bab2289772bb%40googlegroups.com.

For more options, visit https://groups.google.com/d/optout.



--
Sincerely yours,
Constantine C

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/65cf527d-3f94-4db7-9f19-75f6c0e2718f%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Re: Add value to database without using forms in django

Yup did it.....save() method. I wanted to know if we need to create form for saving or other way's are present also...I got the answer. Thanks for the reply

On Saturday, September 30, 2017 at 9:19:41 PM UTC+5:30, Derek wrote:
Yes, its a strange question.

You can of course always add a new method to the City class:

class City(models.Model):

   ...

    def get_cities(self):
        return ''.join([self.city1, self.city2, self.city3, self.city4, self.city5]))

and then store those in Name; but from a design POV, probably 
best not to store them but just get them when you need them.


On Saturday, 30 September 2017 15:10:45 UTC+2, Constantine Covtushenko wrote:
Hi Mitul,

Can you clarify a little bit more your question?
What are you trying to resolve?
You asked: "How it will be done...?" It is not clear what exactly you are trying to be done.

I guess that it my be saving cities into model 'cityval' fields. Am I correct?

If so you can do something like that:

Name(cityval=''.join([city.city1, city.city2, ...])).save()

Regards,
Constantine C.

On Sat, Sep 30, 2017 at 5:39 AM, Mitul Tyagi <mitult...@gmail.com> wrote:
I have a model named "Name" which stores the list of all cities present in other model named  "City". How can it be done internally in the views.py without using forms. Here is the code of models.py

"
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models


class Detail(models.Model):
    username = models.CharField(max_length=100)
    password = models.CharField(max_length=100)

    def __str__(self):
        return str(self.username)


class City(models.Model):
    userName = models.ForeignKey(Detail, blank=True, null=True)
    city1 = models.CharField(max_length=100)
    city2 = models.CharField(max_length=100)
    city3 = models.CharField(max_length=100)
    city4 = models.CharField(max_length=100)
    city5 = models.CharField(max_length=100)
    def __str__(self):
        return "Id No:" + str(self.pk)+" and Name: "+str(self.userName)

class Name(models.Model):
    cityval=models.CharField(max_length=100)
"

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/5d83ea00-e613-4b86-830f-262b1db4ce99%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--
Sincerely yours,
Constantine C

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/4406d4b0-cf38-41c6-a61d-3cad42b8bd7b%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Re: Add value to database without using forms in django

Yes, its a strange question.

You can of course always add a new method to the City class:

class City(models.Model):

   ...

    def get_cities(self):
        return ''.join([self.city1, self.city2, self.city3, self.city4, self.city5]))

and then store those in Name; but from a design POV, probably 
best not to store them but just get them when you need them.


On Saturday, 30 September 2017 15:10:45 UTC+2, Constantine Covtushenko wrote:
Hi Mitul,

Can you clarify a little bit more your question?
What are you trying to resolve?
You asked: "How it will be done...?" It is not clear what exactly you are trying to be done.

I guess that it my be saving cities into model 'cityval' fields. Am I correct?

If so you can do something like that:

Name(cityval=''.join([city.city1, city.city2, ...])).save()

Regards,
Constantine C.

On Sat, Sep 30, 2017 at 5:39 AM, Mitul Tyagi <mitult...@gmail.com> wrote:
I have a model named "Name" which stores the list of all cities present in other model named  "City". How can it be done internally in the views.py without using forms. Here is the code of models.py

"
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models


class Detail(models.Model):
    username = models.CharField(max_length=100)
    password = models.CharField(max_length=100)

    def __str__(self):
        return str(self.username)


class City(models.Model):
    userName = models.ForeignKey(Detail, blank=True, null=True)
    city1 = models.CharField(max_length=100)
    city2 = models.CharField(max_length=100)
    city3 = models.CharField(max_length=100)
    city4 = models.CharField(max_length=100)
    city5 = models.CharField(max_length=100)
    def __str__(self):
        return "Id No:" + str(self.pk)+" and Name: "+str(self.userName)

class Name(models.Model):
    cityval=models.CharField(max_length=100)
"

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/5d83ea00-e613-4b86-830f-262b1db4ce99%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--
Sincerely yours,
Constantine C

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/a51afb41-e8b5-4431-a530-28ba500df3f6%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.