I am working on a django project, but it returns the included urlconf "myapp.urls"does not appear to have any patterns in it.
I tried checking my views to ensure I imported everything correctly
from django.contrib import admin
from django.urls import path
from .views import home
from accounts.views import login_view
urlpatterns = [
path('admin/', admin.site.urls),
path('',home),
path('accounts/login/', login_view),
]
I expect the site to run and redirect me to the login page
This is my views in the same directory with the urls.py
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
#login_required
def home(request):
return render(request,"home.html")
This is the views.py for the accounts.
from django.shortcuts import render,redirect
from django.contrib.auth import(
authenticate,
get_user_model,
login,
logout
)
from .forms import UserLoginForm, UserRegisterForm
def login_view(request):
next = request.GET.get('next')
form = UserLoginForm()
if form.is_valid():
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
user = authenticate(username=username,password=password)
login(request,user)
if next:
return redirect(next)
return redirect("/")
context = {
'form': form,
}
return render(request, "login.html",context)
When I run your project on Django 2.2, I don't see a circular import. Instead I see the error:
django.core.exceptions.ImproperlyConfigured: Creating a ModelForm without either the 'fields' attribute or the 'exclude' attribute is prohibited; form UserRegisterForm needs updating.
Looking at your form, you haven't set fields, you have model = Userfields = [...] instead.
class UserRegisterForm(forms.ModelForm):
...
class Meta:
model = Userfields = [
'username',
'email',
'password',
"c_password"
]
Change it so that you set fields. You can remove 'password' and 'c_password' since you define these on your form separately.
class UserRegisterForm(forms.ModelForm):
...
class Meta:
fields = [
'username',
'email',
]
Related
I have a User table that has some attributes where the Password is being stored as a String. I am trying to store it as an encrypted string using bcrypt, but for some reason it is not changing and the password continues to be the one before encryption.
I have this in my settings.py:
enter image description here
And the method to add my User to the table is in views.py as this:
enter image description here
What am I doing wrong and how can I fix it?
I think you shouldn't do custom encryption. Django already has an encryption system. You can easily integrate bcrpyt as in the documentation. Then all you have to do is;
passwd = user_data['passwd']
user = user_serializer.save()
user.set_password(passwd)
user.save()
EDIT:
Changing password Django doc
Your django configurations are wrong, they should be these:
PASSWORD_HASHERS = [
'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
'django.contrib.auth.hashers.PBKDF2PasswordHasher',
'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
'django.contrib.auth.hashers.Argon2PasswordHasher',
]
this is not the why you should create users with API
first install django rest framework (DRF)
then do this
serializers.py
from django.conf import settings
from django.contrib.auth.models import User
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
"""Serializes a user object"""
class Meta:
model = User
fields = ('__all__')
extra_kwargs = {
'password': {
'write_only': True,
'style': {'input_type': 'password'}
}
}
def create(self, validated_data):
"""Create and return new user"""
user = User.objects.create_user(**validated_data)
return user
permissions.py
from rest_framework import permissions
class UpdateOwnUser(permissions.BasePermission):
"""Allow user to just change their own profile"""
def has_object_permission(self, request, view, obj):
"""Check if user is trying to change their own profile"""
if request.method in permissions.SAFE_METHODS:
return True
return obj.id == request.user.id
views.py
from rest_framework.authentication import TokenAuthentication
from rest_framework import viewsets
from . import permissions, serializers
class UserViewSet(viewsets.ModelViewSet):
"""Handle creating and updating profiles"""
serializer_class = serializers.UserSerializer
queryset = User.objects.all()
authentication_classes = (TokenAuthentication,)
permission_classes = (permissions.UpdateOwnUser,)
urls.py
from django.urls import include, path
from rest_framework.routers import DefaultRouter
from . import views
router = DefaultRouter()
router.register('profile', views.UserProfileViewSet)
urlpatterns = [
path('', include(router.urls)),
]
in the root url.py:
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('profiles_api.urls')),
]
I'm fairly new to Django, but I'm trying to build a customized authentication system by subclassing the generic Django authentication components. The main issue is that my custom LoginView does not seem to do anything besides refresh the page.
forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm, ReadOnlyPasswordHashField, AuthenticationForm, UsernameField
from django.utils.translation import gettext, gettext_lazy as _
from .models import CustomUser
BUREAU_CHOICES = [ ('HR', 'Human Resources'),
('CRT', 'Creative'),
('ACC', 'Accounting'),]
class CustomAuthForm(AuthenticationForm):
bureau = forms.ChoiceField(widget=forms.Select, choices=BUREAU_CHOICES)
email = forms.CharField(widget=forms.TextInput(attrs={'autofocus': True, 'placeholder': 'Email'}))
password = forms.CharField(
label=_("Password"),
strip=False,
widget=forms.PasswordInput(attrs={'autocomplete': 'current-password', 'placeholder': 'Password'}),
)
class Meta:
model = CustomUser
fields = ('email', 'password',)
views.py
from django.shortcuts import render
from django.urls import reverse_lazy
from django.contrib.auth.views import LoginView
from django.contrib.auth import authenticate, login
from django.contrib.auth.forms import AuthenticationForm
from .forms import CustomAuthForm
class CustomLoginView(LoginView):
form_class = CustomAuthForm
authentication_form = CustomAuthForm
template_name = 'users/login.html'
urls.py
from django.urls import path
from . import views
app_name='users'
urlpatterns = [
path('login/', views.CustomLoginView.as_view(), name='login'),
]
So I've read answers here, here and here which all seem to involve overriding methods from the superclass LoginView. When I rewrite my CustomLoginView to override a method, they are not being called. For example:
views.py
class CustomLoginView(LoginView):
form_class = CustomAuthForm
authentication_form = CustomAuthForm
template_name = 'users/login.html'
def form_valid(self, request):
print(self.request)
return super().form_valid(form)
This does nothing. I can't seem to find any reference to which methods I need to override and within which to place login logic.
I am getting some issues with my urls. I don't have any 'account/' route but i when I want to visit 'login/' and after logging in it should redirect me to my profile... but it is taking me to this route: "http://127.0.0.1:8000/accounts/login/?next=/profile/"
I am sorry if I've posted any unnecessary kinds of stuff:
mainapp.urls
from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.urls import path, include
from forms.views import RegisterView,LoginView
from django.conf import settings
from django.conf.urls.static import static
from user_profile import views as profile_views
from blog import views
urlpatterns = [
path('admin/', admin.site.urls),
path('register/',RegisterView.as_view(), name='register'),
path('login/', LoginView.as_view(), name = 'login'),
path('profile/',profile_views.profile,name='profile'),
path('updateprofile/',profile_views.updateprofile,name='update_profile'),
path('',include('blog.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
forms.views(Login/Logout)View
from django.shortcuts import render, redirect,reverse
from django.http import HttpResponse
from django.contrib.auth import authenticate, get_user_model, logout
from django.utils.http import is_safe_url
from django.contrib.auth.decorators import login_required
from django.views.generic import CreateView, FormView
from .models import User
from .forms import RegisterForm,LoginForm
class LoginView(FormView):
form_class = LoginForm #instance
template_name = 'forms/login.html'
success_url = '/profile/'
def User_logout(request):
if request.method == "POST":
logout(request)
return redirect(reverse('login'))
LoginForm:
class LoginForm(forms.Form):
email = forms.EmailField(label='email')
password = forms.CharField(widget=forms.PasswordInput)
def form_valid(self,form):
request=self.request
next_=request.GET.get('next')
next_post=request.POST.get('next')
redirect_path=next_ or next_post or None
email=form.cleaned_data.get('email')
password=form.cleaned_data.get('password')
user=authenticate(username=email, password=password)
if user is not None:
login(request, user)
try:
del request.session['UserProfile.html']
except:
pass
if is_safe_url(redirect_path, request.get_host()):
return redirect(redirect_path)
else:
return redirect("login")
return super(LoginView, self).form_invalid(form)
set a variable in your urls.py of you mainapp as following
appname='mainapp'
now in your login view add following
def get_success_url(self):
return reverse('mainapp:profile')
Currently, in Django 3.2, the reverse method is written this way:
def get_success_url(self):
return reverse('profile')
No need to add appname var in your urls.py
I'm studying Django and doing a course to guide me in this process. Now I'm building some forms and I got this problem: when I access http://127.0.0.1:8000/ the main page is loaded correctly, but when I click in the SignUp link, the page doesn't change, just the URL changes (now http://127.0.0.1:8000/signup) with the same content of the homepage. I expected that the form was loaded and the template correspondent for this view as well.
I've checked if my code could be different from the original course code, but I found nothing wrong.
Here is my views.py file:
from django.shortcuts import render
from django.contrib.auth.models import User
from django.http import HttpResponseRedirect
from .forms import SubscriberForm
def subscriber_new(request, template='subscribers/subscriber_new.html'):
if request.method == 'POST':
form = SubscriberForm(request.POST)
if form.is_valid():
# Unpack form values
username = form.cleaned_data['username']
password = form.cleaned_data['password1']
email = form.cleaned_data['email']
# Create the User record
user = User(username=username, email=email)
user.set_password(password)
user.save()
# Create Subscriber Record
# Process payment (via Stripe)
# Auto login the user
return HttpResponseRedirect('/success/')
else:
form = SubscriberForm()
return render(request, template, {'form':form})
This is my urls.py file:
from django.conf.urls import patterns, include, url
from marketing.views import HomePage
from django.contrib import admin
urlpatterns = patterns('',
#url(r'^admin/', include(admin.site.urls)),
# Marketing pages
url(r'$', HomePage.as_view(), name="home"),
# Subscriber related URLs
url(r'^signup/$',
'crmapp.subscribers.views.subscriber_new', name='sub_new'),
)
This is my forms.py file:
from django import forms
from django.contrib.auth.forms import UserCreationForm
class SubscriberForm(UserCreationForm):
email = forms.EmailField(
required=True, widget=forms.TextInput(attrs={'class':'form-control'})
)
username = forms.CharField(
widget=forms.TextInput(attrs={'class':'form-control'})
)
password1 = forms.CharField(
widget=forms.TextInput(attrs={'class':'form-control', 'type':'password'})
)
password2 = forms.CharField(
widget=forms.TextInput(attrs={'class':'form-control', 'type':'password'})
)
In my templates, the forms are called with this syntax:
<li>Sign Up</li>
I'm using Django version 1.8.4 and Python 2.7.10.
Can someone help me to understand what is happen, please?
You are missing ^ in "home" url:
url(r'^$', HomePage.as_view(), name="home"),
I have a question, I wrote peace of Djnago code, to upload profile picture for user, from admin area model works fine, but from website itself image cannot be uploaded, it seems that code is not even being called. Here is my code, could you check and tell me what might be wrong?
models.py:
from django.conf import settings
from django.db import models
from django.core.files import File
def upload_location(instance, filename):
location = str(instance.user.id)
return "%s/%s" %(location, filename)
class ProfilePicture(models.Model):
user = models.ForeignKey(User)
profile_picture = models.ImageField(upload_to=upload_location, null=True, blank=True)
def __unicode__(self):
return unicode(self.user.id)
forms.py:
from django import forms
from .models import ProfilePicture
class ProfileEditPicture(forms.ModelForm):
class Meta:
model = ProfilePicture
fields = [
"profile_picture"
]
views.py:
from django.contrib.auth.decorators import login_required
from django.contrib.auth import get_user_model
from django.shortcuts import render, get_object_or_404, render_to_response
rom .forms import ProfileEditPicture
from .models import ProfilePicture
#login_required()
def profile_picture(request, id):
user = get_object_or_404(User, id=id)
title = "Profile Edit"
profile, created = Profile.objects.get_or_create(user=user)
form = ProfileEditPicture(request.POST, request.FILES)
if form.is_valid():
instance = form.save(commit=False)
instance.user = request.user
instance.save()
context = {
"form":form,
"title":title,
"profile":profile
}
return render(request, "profile/form.html", context)
urls.py:
urlpatterns = [
...
url(r'^profile_picture/(?P<id>[\w.#+-]+)/', 'profiles.views.profile_picture', name='profile_picture'),
...
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
HTML code in template is default django form.
Thanks in advance :)
A useful piece of documentation is "Binding uploaded files to a form". Possibly if you follow this you will overcome your issue.
Among other things, it is important that include this attribute in your forms element:
<form method="post" action="..." enctype="multipart/form-data">