view in one app is not recognized by different view - Django - django

I have a Django project that I am building. Within the django project I have two apps. one is users and one is accounts. I want to call a view from the acounts app called user_synapse in the users app. I have imported the accounts views python file to import all the methods. I am then calling the method but I am getting an error that says the view method that I am trying to call is not defined. It was working earlier but now it is not working at all. I added the django app name to the settings file and the main urls file. Here is the code I have:
Users app:
views.py file:
#import all references from other apps
from accounts.views import *
from groups.models import *
from groups.views import *
...
# create synapse user
user_synapse(request)
accounts app:
views.py file:
#import all references from other apps
from groups.models import *
from groups.views import *
from users.views import *
from users.models import *
# synapse import statements that are needed
from synapse_pay_rest import Client, Node, Transaction
from synapse_pay_rest import User as SynapseUser
from synapse_pay_rest.models.nodes import AchUsNode
...
# ensure someone is logged in
#login_required
# create a synapse user
def user_synapse(request):
# grab the logged in user
user = request.user
# grab users profile
profile = Profile.objects.get(user = user)
# set user items before creating items
legal_name = profile.first_name + " " + profile.last_name
note = legal_name + " has just created his synapse profile "
supp_id = generate_number()
cip_tag = user.id
# grab the account type
account = profile.business
if account == 'INDIVIDUAL':
account = False
if account == 'BUSINESS':
account = True
# the following is all of the information that is required in order to make a
# new user within the Synapse application
args = {
'email':str(user.email),
'phone_number':str(profile.phone),
'legal_name':str(legal_name),
'note': str(note),
'supp_id':str(supp_id),
'is_business':account,
'cip_tag':cip_tag,
}
# the following is the request to the synapse api as well as the returned
# json that contains information that needs to ba saved in local database
create_user = SynapseUser.create(client, **args)
response = create_user.json
# the following updates the current profile to add the users synapse id within
# the local database.
if response:
synapse_id = response['_id']
updateProfile = profile
updateProfile.synapse_id = synapse_id
updateProfile.save()
the view does exist. why in the world is it saying that the method is not defined:
NameError at /personal/
name 'user_synapse' is not defined
settings.py file:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'general',
'users',
'localflavor',
'groups',
'accounts',
]
It was working earlier but now it is not working and I have no idea why.

The problem is that you have a circular import: in users.views.py
from accounts.views import *
in accounts.views.py
from users.views import *
This is not permitted in Python. See import dependency in Python for more info.

Related

python django whatsapp bot to let others to signup to DBs without using html

Creating a Django project
django-admin startproject messages .
django-admin startapp whatsapp
python manage.py migrate
python manage.py runserver
Open the settings.py file from the messages directory
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'whatsapp.apps.WhatsappConfig', # ← new item
]
Open the views.py from the whatsapp subdirectory.
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
def message(self):
return HttpResponse('Hello!')
To make this endpoint accessible through the web application, a URL needs to be assigned to it. Open the urls.py file from the messages directory and add a new entry to the urlpatterns list as shown below:
from django.contrib import admin
from django.urls import path
from whatsapp import views # ← new import
urlpatterns = [
path('admin/', admin.site.urls),
path('message', views.message), # ← new item
]
Receiving WhatsApp messages
The next step is to update the logic inside the message() endpoint to extract the information about the incoming message. Replace the contents of the views.py file in the whatsapp subdirectory with the following:
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
def message(request):
user = request.POST.get('From')
message = request.POST.get('Body')
print(f'{user} says {message}')
return HttpResponse('Hello!')
Sending a response
Update the views.py file in the whatsapp subdirectory one last time with the following code:
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from twilio.twiml.messaging_response import MessagingResponse
#csrf_exempt
def message(request):
user = request.POST.get('From')
message = request.POST.get('Body')
print(f'{user} says {message}')
response = MessagingResponse()
response.message('Thank for your message! Do you want to signup'
return HttpResponse(str(response))
so far is my code on the project and i want it to accept a username and a password form main only using whatsapp

Safely importing models in django's middleware

I have been trying to import a model in a middleware process function but I am getting the error:
Value: Model class x doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
I am guessing the problem is that the application setup is not complete, however, all my attempts to solve this have hit a wall.
middleware.py function
from notifications.models import Notification
...
class CheckNotificationMiddleware(object):
"""
Checks clicked notification to mark it as read
"""
def process_request(self, request):
if request.user.is_authenticated():
notification_id = request.GET.get('notification_id')
if notification_id:
AppConfig.get_model('Notification')
try:
notification = Notification.objects.get(
pk=notification_id, status=0, recipient=request.user)
notification.status = 1
notification.save()
except ObjectDoesNotExist:
pass
settings.py
INSTALLED_APPS = (
...
'notifications',
...
)
I have tried a couple of things including...
from django.apps import AppConfig
AppConfig.get_model('Notification')
I am using Django version 1.11 and python 2.7
you have to include notifications under the
INSTALLED_APPS = [
'notifications',
]
in the settings file

Django: Unable to get user's groups from LDAP user

My Django ( Django 1.11) project is using django-auth-ldap 1.2 as authentication backed.
I have no problem to authenticate any user agents LDAP database using:
#login_required(login_url='/accounts/login/')
and in this case, any user from any group can login to the site.
I want to allow only user from 'group1' to be able to access the website.
I used the code listed below
from django.shortcuts import render
from django.template import loader
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from django.contrib.auth import views as auth_views
#user_passes_test(
lambda u: hasattr(u, 'ldap_user') and 'group1' in u.ldap_user.group_names,
login_url='/accounts/login/')
def index(request):
template = loader.get_template('main/index.html')
return HttpResponse(template.render())
This is code is not working and user will never pass the test.
According to the model documents django-auth-ldap Document I can use ldap_user.group_names to get group names of a user.
Here is my ldap settings from settings.py:
import os
import django
AUTHENTICATION_BACKENDS = ('django_auth_ldap.backend.LDAPBackend',)
import ldap
from django_auth_ldap.config import LDAPSearch, GroupOfNamesType
AUTH_LDAP_SERVER_URI = "ldap://mydomain.com"
AUTH_LDAP_BIND_DN = "cn=admin,dc=mydomain,dc=com"
AUTH_LDAP_BIND_PASSWORD = "mypass"
AUTH_LDAP_USER_SEARCH = LDAPSearch("ou=ou_org_unit,dc=mydomain,dc=com",
ldap.SCOPE_SUBTREE, "(uid=%(user)s)")
AUTH_LDAP_GROUP_SEARCH = LDAPSearch("ou=ou_org_unit,cn=group1,cn=group2,dc=mydomain,dc=com",
ldap.SCOPE_SUBTREE, "(objectClass=groupOfNames)"
)
AUTH_LDAP_GROUP_TYPE = GroupOfNamesType()
AUTH_LDAP_USER_ATTR_MAP = {
"first_name": "givenName",
"last_name": "sn",
"email": "mail"
}
AUTH_LDAP_FIND_GROUP_PERMS = True
AUTH_LDAP_CACHE_GROUPS = True
AUTH_LDAP_GROUP_CACHE_TIMEOUT = 3600
My question is:
Why I am not able to authenticate any user with this code?
You should be using the AUTH_LDAP_REQUIRE_GROUP setting if you want to restrict logins to a single group.
You will also likely want to use AUTH_LDAP_MIRROR_GROUPS in order to have all of your LDAP groups automatically loaded into your Django database.
As a bonus, you can include multiple groups in the AUTH_LDAP_REQUIRE_GROUP setting, by using the LDAPGroupQuery class. For example (taken from the documentation):
from django_auth_ldap.config import LDAPGroupQuery
AUTH_LDAP_REQUIRE_GROUP = (
(
LDAPGroupQuery("cn=enabled,ou=groups,dc=example,dc=com") |
LDAPGroupQuery("cn=also_enabled,ou=groups,dc=example,dc=com")
) &
~LDAPGroupQuery("cn=disabled,ou=groups,dc=example,dc=com")
)

Django setting - apps aren't loaded yet

I want to import an apps model in setting.py for PUSH_NOTIFICATIONS_SETTINGS in django-push-notifications. This is my code:
INSTALLED_APPS = (
....
'my_app',
'push_notifications'
....
)
from my_app.models import User
PUSH_NOTIFICATIONS_SETTINGS = {
'GCM_API_KEY': 'xxxxx',
'APNS_CERTIFICATE': 'xxxxx.pem',
'USER_MODEL': User, # i want to change the default from auth_user to my_app User
}
But it raise an error on this line:
from my_app.models import User
The error is:
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
How Can i load my_app model in setting.py?
You cannot load models from inside your settings file like that - models can only be loaded once all apps are loaded (which can only happen after the settings have been loaded).
Looking at the code in django-push-notifications, you should be able to provide the model as a string with dotted path:
'USER_MODEL': 'my_app.User'
You can't load User model in settings, but instead you can change it
PUSH_NOTIFICATIONS_SETTINGS = {
'GCM_API_KEY': 'xxxxx',
'APNS_CERTIFICATE': 'xxxxx.pem',
'USER_MODEL': 'my_app.User',
}
And use it later like:
from django.apps import apps
from django.conf import settings
User = apps.get_model(settings.PUSH_NOTIFICATIONS_SETTINGS['USER_MODEL'])
And you can do whatever you want with this User model

enable a model on Django Admin on Dreamhost

Hi I've created a new app (Paginas) but I cannot see inside the admin page. I've added 'paginas' to INSTALLED_APP. My admin.py is
# coding=utf-8
from django.contrib import admin
from .models import Pagina
class PaginaAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("titulo",)}
list_display = ('titulo' , 'contenido')
class Media:
js = ('/layout/grappelli/tinymce/jscripts/tiny_mce/tiny_mce.js','/layout/grappelli/tinymce_setup/tinymce_setup.js')
admin.site.register(Pagina,PaginaAdmin)
I am using passenger_wsgi.py file, I've touched tmp/restart.txt file, I've killed python process
I don't know what else can I do
The project you can see it on github https://github.com/totechess/paralisis_cerebral
What kind of error do you get when you go to your site yoursite.com/admin/
Did you add admin to INSTALLED_APPS? Note the S
....
'django.contrib.admin',
....
Perhaps your urls.py are not updated properly? What is the error?