Why am I getting an error when trying to run my server to access the database to see if my code works? While in my projects folder in Terminal, I ran sudo python manage.py runserver to try to run the server but it doesn't work because of the aforementioned error. I've looked around SO but can't find one directly related to my problem.
I'm getting my if() statement is the problem.
The error I'm getting says:
RuntimeError: maximum recursion depth exceeded while calling a Python object
Here's my views.py file:
from .models import Album
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from django.core.urlresolvers import reverse_lazy
from django.views import generic
from django.views.generic import View
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from .forms import UserForm
class IndexView(generic.ListView):
template_name = 'music/index.html'
context_object_name = 'all_albums'
def get_queryset(self):
return Album.objects.all()
class DetailView(generic.DeleteView):
model = Album
template_name = 'music/detail.html'
class AlbumCreate(CreateView):
model = Album
fields = ['artist', 'album_title', 'genre', 'album_logo']
class AlbumUpdate(UpdateView):
model = Album
fields = ['artist', 'album_title', 'genre', 'album_logo']
class AlbumDelete(DeleteView):
model = Album
success_url = reverse_lazy('music:index')
class UserFormView(View):
form_class = UserForm
template_name = 'music/registration_form'
# display blank form
def get(self, request):
form = self.form_class(None)
return render(request, self.template_name, {'form': form})
def post(self):
form = self.form_class(request.POST)
if form.is_valid():
user = form.save(commit=False)
#cleaned normalized data
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user.set_password(password)
user.save()
Tail of error:
File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/urls/resolvers.py", line 255, in check
warnings.extend(check_resolver(pattern))
File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/core/checks/urls.py", line 26, in check_resolver
return check_method()
File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/urls/resolvers.py", line 172, in check
warnings = self._check_pattern_startswith_slash()
File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/urls/resolvers.py", line 140, in _check_pattern_startswith_slash
regex_pattern = self.regex.pattern
Here's my forms.py file:
from django.contrib.auth.models import User
from django import forms
class UserForm(forms.ModelForm): # UserForm inherits from forms.
passwords = forms.CharField(widget=forms.PasswordInput)
class Meta: # Information about your class.
model = User # whenevr a creates sign up to your site it's gonna go in same table
fields = ['username', 'email', 'password']
Here's my urls.py file:
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
app_name = 'music'
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^music/', include('music.urls'))
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root = settings.STATIC_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.MEDIA_ROOT)
You didn't pass request into your post method, It should be,
class UserFormView(View):
form_class = UserForm
template_name = 'music/registration_form.html'
def post(self, request, *args, **kwargs):
# blaah
Also, missed the extension of your template.
I think you should use FormView for this and don't need to override post or get method in your View, Because you will get form object in template if user assign form_class in View.You have to override form_valid() method for your custom operations
class UserFormView(FormView):
form_class = UserForm
template_name = 'music/registration_form'
def form_valid(self, form)
user = form.save(commit=False)
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user.set_password(password)
user.save()
Related
In the function "createProject" of views.py, I want that after submitting the form user should redirect to the "projects" page.
But I don't know what is my mistake here. After submitting the form it does not redirect the user to "projects" page but remains on the same page.
"views.py" file:
from django.shortcuts import render, redirect
from django.http import HttpResponse
from .forms import ProjectForm
from .models import Project
def projects(request):
projects = Project.objects.all()
context = {'projects':projects}
return render(request, 'projects/projects.html', context)
def project(request, pk):
return render(request, 'projects/single-project.html')
def createProject(request):
form = ProjectForm()
if request.method == 'POST':
form = ProjectForm(request.POST)
if form.is_valid():
form.save()
redirect('projects')
context = {'form':form}
return render(request, 'projects/project_form.html', context)
Here is "urls.py" file:
from django.urls import path
from . import views
urlpatterns = [
path('', views.projects, name = 'projects'),
path('project/<str:pk>/', views.project, name = 'project'),
path('create-project/', views.createProject, name = 'create-project'),
]
Here is "project-form.html" [I am using Django "ModelForm"]:
from django.db.models.base import Model
from django.forms import ModelForm
from .models import Project
class ProjectForm(ModelForm):
class Meta:
model = Project
fields = ['title', 'description', 'demo_link', 'source_link', 'tags']
Can anyone help me in finding the mistake here ?
Why after submitting the form, it is not redirecting it to the "projects" page and remain on same page?
This issue is because the redirect response was never returned, so:
if form.is_valid():
form.save()
return redirect('projects')
# ^^^ Add this
For whatever reason when I give a name="..." - argument to a URL pattern and I want to refer to it by using the name it does not seem to work.
That's my 'webapp/urls.py' file:
from django.urls import path
from .views import PostListView, PostDetailView, PostCreateView
from .import views
app_name = 'webapp'
urlpatterns = [
path("", PostListView.as_view(), name="webapphome"),
path("post/<int:pk>/", PostDetailView.as_view(), name="postdetail"),
path('post/new/', PostCreateView.as_view(), name="postcreate"),
path("about/", views.About, name="webappabout"),
]
And that's my 'webapp/views.py' file:
from django.shortcuts import render
from django.views import generic
from django.views.generic import ListView, DetailView, CreateView
from .models import Post
def Home(request):
context = {
'posts': Post.objects.all() }
return render(request, "webapp/home.html", context)
class PostListView(ListView):
model = Post
template_name = 'webapp/home.html'
context_object_name = 'posts'
ordering = ['-date']
class PostDetailView(DetailView):
model = Post
template_name = 'webapp/detail.html'
class PostCreateView(CreateView):
model = Post
fields = ['title', 'content']
template_name = 'webapp/postform.html'
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
def About(request):
return render(request, "webapp/about.html", {'title': 'About'})
And that's my 'webapp/models.py' file:
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
class Post(models.Model):
title = models.CharField(max_length=50)
content = models.TextField(max_length=300)
date = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("postdetail", kwargs={'pk': self.pk})
As you can see, I'm using the name 'postdetail' I've given to the URL path from PostDetailView but however I receive an Error like this when I create a new Post:
NoReverseMatch at /post/new/
Reverse for 'postdetail' not found. 'postdetail' is not a valid view function or pattern name.
Request Method: POST
Exception Type: NoReverseMatch
I'd suggest you read the Namespace section in Django Documentation, here
The issue is due to you having an app_name = 'webapp' but not using it with postdetail
The objective of app_name is to ensure you know where to redirect if you have two url in different apps with same names.
change
return reverse("postdetail", kwargs={'pk': self.pk})
to
return reverse("webapp:postdetail", kwargs={'pk': self.pk})
I use Django 1.11 and python 3.6.5 . I made a model and a form for user registration. every thing seems fine except i have this error that I could not solve.
__init__() takes 1 positional argument but 2 were given
Here is the model:
from django.db import models
class User_account(models.Model):
first_name = models.CharField(max_length=64)
last_name = models.CharField(max_length=64)
user_name = models.CharField(max_length=128)
email = models.EmailField(max_length=254, blank=False, unique=True)
password = models.CharField(max_length=64)
address = models.ForeignKey(Address, on_delete=models.CASCADE)
Here is the form:
from django import forms
from .models import User_account
class User_accountForm(forms.ModelForm):
class Meta:
model = User_account
fields = ['first_name', 'last_name', 'user_name', 'email', 'password', 'address']
Here is a portion of the view:
from django.shortcuts import render, redirect
from .models import *
from django.views import View
from .forms import *
from django.contrib.auth import authenticate, login
class User_accountFormView(View):
form_class = User_accountForm
template_name = 'towns/salehslist/registeration_form.html'
# display a blank form
def get(self, request, *args, **kwargs):
form = self.form_class(None)
return render(request, self.template_name, {'form':form})
The URLs:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^register/$', views.User_accountFormView, name='register'),
You need to call as_view() when you include your class based view in your url patterns.
url(r'^register/$', views.User_accountFormView.as_view(), name='register'),
I am trying to view a user profile for my website with the Detail CBV. Below is the code for views.py, urls.py, models.py and profile.html.
A user exists with the username "brian_weber", but for some reason when I navigate to this link: http://0.0.0.0:8000/accounts/profile/brian_weber the page is not found. My app is called "accounts".
If someone could point me in the right direction to get the view to show up with the url, that would be greatly appreciated! I have searched around Stack Overflow, but nothing has worked that I tried.
Thanks in advance,
Brian
views.py
from django.shortcuts import render
from django.shortcuts import get_object_or_404
from django.contrib.auth import login, logout, authenticate
from django.http import HttpResponseRedirect
from django.contrib.auth.forms import AuthenticationForm
from django.core.urlresolvers import reverse, reverse_lazy
from django.views import generic
from braces.views import LoginRequiredMixin
from django.contrib.messages.views import SuccessMessageMixin
from . import forms
from . import models
class LoginView(generic.FormView):
form_class = AuthenticationForm
success_url = reverse_lazy('home')
template_name = "accounts/login.html"
def get_form(self, form_class=None):
if form_class is None:
form_class = self.get_form_class()
return form_class(self.request, **self.get_form_kwargs())
def form_valid(self, form):
login(self.request, form.get_user())
return super().form_valid(form)
def logout_view(request):
logout(request)
return HttpResponseRedirect(reverse('home'))
class SignUp(SuccessMessageMixin, generic.CreateView):
form_class = forms.UserCreateForm
success_url = reverse_lazy("login")
template_name = "accounts/signup.html"
success_message = "Your profile has been successfully created. Please log into your account."
class UserProfile(LoginRequiredMixin, generic.DetailView):
model = models.UserProfile
template_name = "profile.html"
class UserProfileUpdate(LoginRequiredMixin, generic.UpdateView):
model = models.UserProfile
urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^logout/$', views.logout_view, name="logout"),
url(r'^signup/$', views.SignUp.as_view(), name="signup"),
url(r'^profile/(?P<username>[a-zA-Z0-9]+)$',
views.UserProfile.as_view(),
name="profile"),
url(r'^profile/update/(?P<username>[a-zA-Z0-9]+)$',
views.UserProfileUpdate.as_view(),
name="update_profile"),
]
models.py
class UserProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL)
company = models.CharField(max_length=40, null=True)
position = models.CharField(max_length=40, null=True)
bio = models.CharField(max_length=140, blank=True, default="")
avatar = models.ImageField(blank=True, null=True, upload_to="avatars",
height_field=None, width_field=None)
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
post_save.connect(create_user_profile, sender=User)
Your mistake is very small, the regular expression provided in url for profile, (?P<username>[a-zA-Z0-9]+) does not match brian_weber because of the _.
You can simply update the regex to match _ too.
username_regex = r'[a-zA-Z0-9_]+'
urlpatterns = [
url(r'^logout/$', views.logout_view, name="logout"),
url(r'^signup/$', views.SignUp.as_view(), name="signup"),
url(r'^profile/(?P<username>{username})$'.format(username=username_regex),
views.UserProfile.as_view(),
name="profile"),
url(r'^profile/update/(?P<username>{username})$'.format(username=username_regex),
views.UserProfileUpdate.as_view(),
name="update_profile"),
]
I am new in Django and I am creating a form,
#forms.py
class SetupForm(forms.Form):
pass
and corresponding view is
#views.py
class SetupView(FormView):
template_name = 'template/setup_form.html'
form_class = SetupForm
success_url = 'template/base_collect'
def form_valid(self,form):
return super(SetupView, self).form_valid(form)
def base(request):
return render_to_response('template/base_collect.html')
and url patterns are,
#urls.py
urlpatterns = patterns(url(r'^setup-form/$', views.SetupView.as_view(), name='setup-form'),
url(r'^base_collect/$', views.base),)
After submitting the form, the redirected URL is shown as
http://127.0.0.1:8000/template/setup-form/template/base_collect.html instead of http://127.0.0.1:8000/template/base_collect.
What am I missing here? How to achieve later?
Modify as below :
#urls.py
urlpatterns = patterns(
url(r'^setup-form/$', views.SetupView.as_view(), name='setup-form'),
url(r'^base_collect/$', views.base, name = 'base-form'),
)
And
Replace
success_url = 'template/base_collect.html'
with
success_url = reverse('base-form')
Import
from django.core.urlresolvers import reverse
In your views.py
You mistakenly put the template name in the success_url property for the class. You also don't need the other two methods, as they aren't adding any functionality to what the default FormView class provides.
class SetupView(FormView):
template_name = 'template/setup_form.html'
form_class = SetupForm
success_url = 'collect/base_collect' # the URL goes here
#def form_valid(self,form):
# return super(SetupView, self).form_valid(form)
#def base(request):
# return render_to_response('template/base_collect.html')