ImproperlyConfigured error when using pyrebase with Django - django

I tried to import pyrebase in my views.py, but I've got an error raisen:
Exception in thread django-main-thread:
Traceback (most recent call last):
File "C:\Users\USER\Documents\python projects\yerekshe\lib\site-packages\django\urls\resolvers.py", line 581, in url_patterns
iter(patterns)
TypeError: 'module' object is not iterable
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
raise ImproperlyConfigured(msg.format(name=self.urlconf_name))
django.core.exceptions.ImproperlyConfigured: The included URLconf 'yerekshe.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.
here is my views.py:
from django.shortcuts import render, redirect
from .forms import UserForm, UserProfileInfoForm, UpdateProfileForm
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect, HttpResponse
from django.urls import reverse
from . import forms
import pyrebase
config = {
'apiKey': "0",
'authDomain': "yerekshe.firebaseapp.com",
'databaseURL': "https://yerekshe.firebaseio.com",
'projectId': "yerekshe",
'storageBucket': "",
'messagingSenderId': "0",
}
firebase = pyrebase.initialize_app(config)
auth = firebase.auth()
def home(request):
return render(request, 'home.html')
def signIn(request):
return render(request, 'login.html')
def postsign(request):
email = request.POST.get('email')
passw = request.POST.get("pass")
try:
user = auth.sign_in_with_email_and_password(email, passw)
except:
message = "invalid cerediantials"
return render(request, "login.html", {"msg": message})
print(user)
return render(request, "home.html", {"e": email})
and here is yerekshe\urls.py:
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('account/', include('account.urls'))
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Related

I'm trying to add a new page in Django but getting 404 error yet I've added urls and views

I'm a newbie trying to add an a new page but get the following error:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/study
Using the URLconf defined in student_management_system.urls, Django tried these URL patterns, in this order:
I've added a function for the page in Views.py and also added the path in URLS.py.
StudentViews.py ---> in student management app folder:
from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib import messages
from django.core.files.storage import FileSystemStorage # To upload Profile Picture
from django.urls import reverse
import datetime # To Parse input DateTime into Python Date Time Object
from student_management_app.models import CustomUser, Staffs, Courses, Subjects, Students, Attendance, AttendanceReport, \
LeaveReportStudent, FeedBackStudent, StudentResult
def study(request):
return render(request, "student_template/study.html")
Views.py ---> in student management app folder:
# from channels.auth import login, logout
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render, redirect
from django.contrib import messages
from student_management_app.EmailBackEnd import EmailBackEnd
def home(request):
return render(request, 'index.html')
def loginPage(request):
return render(request, 'login.html')
def doLogin(request):
if request.method != "POST":
return HttpResponse("<h2>Method Not Allowed</h2>")
else:
user = EmailBackEnd.authenticate(request, username=request.POST.get('email'), password=request.POST.get('password'))
if user != None:
login(request, user)
user_type = user.user_type
#return HttpResponse("Email: "+request.POST.get('email')+ " Password: "+request.POST.get('password'))
if user_type == '1':
return redirect('admin_home')
elif user_type == '2':
# return HttpResponse("Staff Login")
return redirect('staff_home')
elif user_type == '3':
# return HttpResponse("Student Login")
return redirect('student_home')
else:
messages.error(request, "Invalid Login!")
return redirect('login')
else:
messages.error(request, "Invalid Login Credentials!")
#return HttpResponseRedirect("/")
return redirect('login')
def get_user_details(request):
if request.user != None:
return HttpResponse("User: "+request.user.email+" User Type: "+request.user.user_type)
else:
return HttpResponse("Please Login First")
def logout_user(request):
logout(request)
return HttpResponseRedirect('/')
URLS.py ---> in student management app folder:
from django.urls import path, include
from . import views
from .import HodViews, StaffViews, StudentViews
urlpatterns = [
path('', views.loginPage, name="login"),
path('student_view_result/', StudentViews.student_view_result, name="student_view_result"),
path('study/', StudentViews.study, name="study"),
]
Urls.py for the whole system:
from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from student_management_system import settings
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('student_management_app.urls')),
]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
How could I resolve this error? And why it reported this error?

django.core.exceptions.ImproperlyConfigured error

Here is the error message:
django.core.exceptions.ImproperlyConfigured:
The included URLconf '<module 'basicsiteApp' from '/Users/msa/trydjango/basicsite/basicsiteApp/__init__.py'>'
does not appear to have any patterns in it.
If you see valid patterns in the file then the issue is probably
caused by a circular import.
I don't have anything written in init.py because I don't know what I need to write in it so it can work.
Below is what I have in views.py:
from django.shortcuts import render
from .forms import SignUpForm
from django.contrib import messages
def signup(request):
if request.method == 'POST'
form = SignUpForm(request.POST)
if form.is_valid():
form.save()
messages.success(request, 'Account Created')
return render(request, 'signup.html')
else:
form = SignUpForm()
render(request, 'signup.html')
Basicsite/urls.py:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('', include('basicsiteApp')),
path('admin/', admin.site.urls)
]
basicsiteApp/urls.py:
from django.urls import path
from . import views
app_name = 'basicsiteApp'
urlpatterns = [
path('', views.signup, name='signup')
]
I know it comes late, but if someone (like me) faces the same problem:
In your "Basicsite/urls.py"
path('', include('basicsiteApp')),
it should be
path('', include('basicsiteApp.urls')),
implying django to use the basicsiteApp/urls.py file instead of basicsiteApp/init.py

Why am I getting error 404 in my django project when everything seems correct?

I have two apps in my Django project:basket and store. In root url files I configured the urls.py like this:
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('store.urls', namespace='store')),
path('basket/', include('basket.urls', namespace='basket')),
store/urls.py:
from django.urls import path
from . import views
app_name = 'store'
urlpatterns = [
path('', views.all_products, name='all_products'),
path('<slug:slug>/', views.product_detail, name='product_detail'),
path('category/<slug:category_slug>/',
views.category_list, name='category_list')
]
basket/urls.py:
from django.urls import path
from . import views
app_name = 'basket'
urlpatterns = [
path('', views.basket_summary, name='basket_summary'),
path('add/', views.basket_add, name='basket_add'),
]
I am getting an error:
Page not found(404)
Request Method:GET
Request URL:http://127.0.0.1:8000/basket/
Raised by:store.views.product_detail
this is my store/views.py:
from django.shortcuts import get_object_or_404, render
from .models import *
def product_detail(request, slug):
product = get_object_or_404(Product, slug=slug, in_stock=True)
context = {
'product': product,
}
return render(request, 'store/products/detail.html', context)
please help me solve this problem i've been stuck on this for a long time.
Try this way if you want to avoid 404 error:
from django.shortcuts import get_object_or_404, render
from .models import *
def product_detail(request, slug):
try:
product = Product.objects.get(slug=slug, in_stock=True)
context = {
'product': product,
}
except Product.DoesNotExist:
raise ValidationError('Product Does not exist ')
return render(request, 'store/products/detail.html', context
)

Why do I get circular import error when importing view?

Could someone please help me. I get the following error when loading my project:
raise ImproperlyConfigured(msg.format(name=self.urlconf_name))
django.core.exceptions.ImproperlyConfigured: The included URLconf
'siteV1.urls' does not appear to have any patterns in it. If you see
valid patterns in the file then the issue is probably caused by a
circular import.
This is my urls.py
from django.contrib import admin
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from drink.views import HomepageView, CreateDrinkView, CreateNormalDrinkView, CreateMixedDrinkView
from machine.views import SettingsView
from account.views import LoginView
urlpatterns = [
path('', HomepageView.as_view()),
path('create-drink', CreateDrinkView.as_view()),
path('create-drink/save-normal', CreateNormalDrinkView.as_view()),
path('create-drink/save-mixed', CreateMixedDrinkView.as_view()),
path('settings/', SettingsView.as_view()),
path('accounts/login/', LoginView.as_view()),
path('admin/', admin.site.urls),
]
if settings.DEBUG == True:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
else:
pass
#enter code here for media and static handeling during production
The problem seems to be related to the import of the LoginView. If I delete this import and path the program runs without any errors. My accounts.views contains the following code:
from django.contrib.auth import authenticate, login
from django.shortcuts import render, redirect
from django.views.generic import TemplateView
# Create your views here.
class LoginView(TemplateView):
template_name = 'login.html'
def get(self, request):
return render(request, self.template_name, {})
def post(self, request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
# Redirect to a success page.
return redirect('')
else:
# Return an 'invalid login' error message.
return render(request, self.template_name {'error': 'Gebruikersnaam of wachtwoord onjuist!'})
The account.models is empty at the moment. I tried running pycycle to check for circular imports. Pycycle returned that there were no circular imports found. Your help is much appreciated!
Solved this by deleting the app and recreating it. Still don't know what the problem is but it works for now.

can't use reverse url function in django

tests.py
from django.test import TestCase
from django.urls import reverse
from rest_framework import status
from .models import User
class UserCreateAPIViewTestCase(APITestCase):
def setUp(self):
super().setUp()
self.url = reverse("admins")
def test_user_creating(self):
user_data = {}
response = self.client.post(self.url, user_data, format="json")
self.assertEqual(response.status_code,
status.HTTP_403_FORBIDDEN)
2.urls.py
from django.urls import path
from django.conf.urls import include
from rest_framework_nested.routers import SimpleRouter
from apps.users.views import (
CreateProviderViewSet,
LoginViewSet,
UserViewSet,
ProviderViewSet,
ClientViewSet,
LoginAsViewSet
)
app_name = 'users'
router = SimpleRouter(trailing_slash=False)
router.register("admins", UserViewSet, base_name='admins')
router.register("providers", ProviderViewSet, base_name='providers')
router.register("clients", ClientViewSet, base_name='clients')
router.register("login", LoginViewSet, base_name='auth')
router.register("login-as", LoginAsViewSet)
urlpatterns = [
path('', include(router.urls)),
]
when I run python .\manage.py test apps.users.tests
This error occurs
ERROR: test_user_creating (apps.users.tests.UserCreateAPIViewTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Users\vu.tran\Desktop\kona-server\apps\users\tests.py", line 19, in setUp
self.url = reverse("admins")
File "C:\Users\vu.tran\Desktop\kona-server\env\lib\site-packages\django\urls\base.py", line 90, in reverse
return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
File "C:\Users\vu.tran\Desktop\kona-server\env\lib\site-packages\django\urls\resolvers.py", line 668, in _reverse_with_prefix
raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'admins' not found. 'admins' is not a valid view function or pattern name.
my structure folders like this my folders
I wonder why cannot get reverse("admins")
Do you have any idea?
According to the documentation, if you want to access the list view, the name for the url should be admins-list. The name of the argument for your register function may also be basename instead of base_name.