2
votes

I am facing error while running a project :

Environment:

Request Method: POST Request URL: http://127.0.0.1:8000/

Django Version: 1.8.4 Python Version: 2.7.6 Installed Applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'mongo_login') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware')

Traceback: File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response 132. response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/home/shubham/Documents/python/django project/login/mongo_login/views.py" in register
      24.         if form.is_valid():



 File "/usr/local/lib/python2.7/dist-packages/django/forms/forms.py" in

is_valid 184. return self.is_bound and not self.errors File "/usr/local/lib/python2.7/dist-packages/django/forms/forms.py" in errors 176. self.full_clean() File "/usr/local/lib/python2.7/dist-packages/django/forms/forms.py" in full_clean 392. self._clean_fields() File "/usr/local/lib/python2.7/dist-packages/django/forms/forms.py" in _clean_fields 410. value = getattr(self, 'clean_%s' % name)()

 File "/home/shubham/Documents/python/django project/login/mongo_login/forms.py" in clean_username
      56.         existing = MongoUser.objects(username=self.cleaned_data['username'])

File "/usr/local/lib/python2.7/dist-packages/mongoengine/queryset/manager.py" in get 37. queryset = queryset_class(owner, owner._get_collection()) File "/usr/local/lib/python2.7/dist-packages/mongoengine/document.py" in _get_collection 176. db = cls._get_db() File "/usr/local/lib/python2.7/dist-packages/mongoengine/document.py" in _get_db 169. return get_db(cls._meta.get("db_alias", DEFAULT_CONNECTION_NAME)) File "/usr/local/lib/python2.7/dist-packages/mongoengine/connection.py" in get_db 145. conn = get_connection(alias) File "/usr/local/lib/python2.7/dist-packages/mongoengine/connection.py" in get_connection 101. raise ConnectionError(msg)

    Exception Type: ConnectionError at /
    Exception Value: You have not defined a default connection

and the code is :

View.py

from django.template.context import RequestContext
from django.shortcuts import redirect, render_to_response
from django.conf import settings

from forms import RegistrationForm
from auth import User as MongoUser

def save_user_in_mongo(**kwargs):
    new_user = MongoUser.create_user(kwargs['username'], kwargs['password1'], kwargs['email'])
    new_user.first_name = kwargs.get('first_name')
    new_user.last_name = kwargs.get('last_name')
    new_user.save()
    return new_user


def register(request, success_url=None, form_class=None,
             template_name='registration/registration_form.html',
             extra_context=None):

    if form_class is None:
        form_class = RegistrationForm
    if request.method == 'POST':
        form = form_class(data=request.POST, files=request.FILES)
        if form.is_valid():            # line 24 =======
            save_user_in_mongo(**form.cleaned_data)
            if success_url is None:
                success_url = settings.LOGIN_URL
            return redirect(success_url)
    else:
        form = form_class()

    if extra_context is None:
        extra_context = {}
    context = RequestContext(request)
    for key, value in extra_context.items():
        context[key] = callable(value) and value() or value

    return render_to_response(template_name,
            {'form': form},
        context_instance=context)

forms.py

from auth import User as MongoUser
from django import forms
from django.utils.translation import ugettext_lazy as _


attrs_dict = {'class': 'required'}


class RegistrationForm(forms.Form):

    username = forms.RegexField(regex=r'^[\w.@+-]+$',
        max_length=30,
        widget=forms.TextInput(attrs=attrs_dict),
        label=_("Username"),
        error_messages={'invalid': _("This value may contain only letters, numbers and @/./+/-/_ characters.")})
    email = forms.EmailField(widget=forms.TextInput(attrs=dict(attrs_dict,
        maxlength=75)),
        label=_("E-mail"))
    password1 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False),
        label=_("Password"))
    password2 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False),
        label=_("Password (again)"))
    first_name = forms.CharField(widget=forms.TextInput(attrs=dict(attrs_dict, maxlength=50)),
        label=_("First Name"))
    last_name = forms.CharField(widget=forms.TextInput(attrs=dict(attrs_dict, maxlength=50)),
        label=_("Last Name"), required=False)


    def clean_username(self):

        existing = MongoUser.objects(username=self.cleaned_data['username'])#line 56 ======
        if existing:
            raise forms.ValidationError(_("A user with that username already exists."))
        else:
            return self.cleaned_data['username']

    def clean(self):

        if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
            if self.cleaned_data['password1'] != self.cleaned_data['password2']:
                raise forms.ValidationError(_("The two password fields didn't match."))
        return self.cleaned_data

setting.py

DATABASES = {
    'default': {
        'ENGINE': 'django_mongodb_engine',
        'NAME': 'my_database',
        'OPTIONS' : {
            'socketTimeoutMS' : 500,

        }
    }
}

How i can resolve this problem ?

2

2 Answers

1
votes

Try this with sqlite3 database that is already added in django project .

change in your setting.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': 'logintest.db',                     
        'USER': '',                      
        'PASSWORD': '',                  
        'HOST': '',                     
        'PORT': '',                     
    }
}
0
votes

It appears Django doesn't know how to connect to the database.

Define a default connection to the DB in settings.py

DATABASES = {
    'default' : {
        'ENGINE' : 'django_mongodb_engine',
        'NAME' : 'my_database',
        ...
        'OPTIONS' : {
            'socketTimeoutMS' : 500,
            ...
        }
    }
}