I am making a form using Django 1.8 and Python 3.5
But the form is not showing up,IDK why ?
This are my files respectivel
urlpatterns = [
url(r'^login', 'login.views.login', name='login'),
url(r'^admin/', include(admin.site.urls)),
] + static(settings.STATIC_URL , document_root=settings.STATIC_ROOT)
login/view.py==
from django.shortcuts import render
from .forms import allusers1
# Create your views here.
def login(request):
form1=allusers1()
context = {
"form1": form1
}
return render(request, "login.html",context)
login/forms.py==
from django import forms
from .models import allusers1
class signupform(forms.ModelForm):
class Meta:
model = allusers1
fields = ['name','phoneno']
login/models.py
from django.db import models
# Create your models here.
class allusers1(models.Model):
name=models.CharField(max_length=400)
phoneno=models.CharField(max_length=10)
otp=models.IntegerField()
# def __str__(self):
# return self.name
login.html
{{form1}}
output
allusers1 object
But output should have been Name and ,Email fields for input
WHAT IS THE ERROR ?
Your form is actually named signupform, and not allusers1.
In your views.py, you should import your form like this:
from django.shortcuts import render
from .forms import signupform # <= here
# Create your views here.
def login(request):
form1=signupform() # <= and here
context = {
"form1": form1
}
return render(request, "login.html",context)
Related
I get this error: The included URLconf 'liskerproject.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.
liskerproject is the root directory and contains the root "urls.py".
Lisk is another directory that contains "url.py"
This is how my root urls look like:
from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.urls import path,include
from users import views as user_views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('edit/',user_views.edit,name='edit'),
path('',include('Lisk.url')),
path('register/',user_views.register,name='register'),
path('login/',auth_views.LoginView.as_view(template_name='user_templates/login.html'),name='login'),
path('logout/',auth_views.LogoutView.as_view(template_name='user_templates/logout.html'),name='logout')
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
This is how Lisk.url looks like:
from django.urls import path
from .views import Politics_topic,Questionpolitics,Updatepolitics,Politics_post_details,Deletepoliticspost,Profile,home
from . import views
urlpatterns = [
path('',home,name='home'),
path('about/',views.about,name = 'about Lisk'),
path('interests/',views.interests,name='interests'),
path('profile/',Profile.as_view(template_name='lisk_templates/profile.html'),name = 'profile'),
path('politics_topic/', Politics_topic.as_view(template_name='lisk_templates/politics_topic_template.html'),
name='Politics_topic'),
path('ask_politics/', Questionpolitics.as_view(template_name='lisk_templates/ask_politics_template.html'),
name='ask_politics'),
path('politicspost/<int:pk>/',Politics_post_details.as_view(template_name='lisk_templates/politics_post_details.html'),
name='politics_post_details'),
path('politicspost/<int:pk>/update/',Updatepolitics.as_view(template_name='lisk_templates/ask_politics_template.html'),
name='updatepoliticspost'),
path('politicspost/<int:pk>/delete/',Deletepoliticspost.as_view(template_name='lisk_templates/delete_politics_confirmation.html'),name ='deletepoliticspost')
]
This how Lisk.views look like:
from django.shortcuts import render
from django.http import HttpResponse
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from .models import Post, PoliticsPost
from django.contrib.auth.decorators import login_required
from django.urls import reverse_lazy
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
def home(request):
return render(request, 'lisk_templates/home_template.html')
def about(request):
return render(request, 'lisk_templates/about_template.html')
#login_required
def interests(request):
return render(request, 'lisk_templates/interests_template.html')
class Profile(LoginRequiredMixin,ListView):
model = Post
context_object_name = 'post'
ordering = ['-date_posted']
#POLITICS-------------
class Politics_topic(ListView):
model= PoliticsPost
context_object_name = 'politicsposts'
ordering = ['-date_posted']
class Politics_post_details(DetailView):
model = PoliticsPost
context_object_name = 'politicsposts'
class Questionpolitics(LoginRequiredMixin, CreateView):
model = PoliticsPost
fields =['question','description']
success_url = reverse_lazy('Politics_topic')
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
class Updatepolitics(LoginRequiredMixin,UserPassesTestMixin,UpdateView):
model = PoliticsPost
fields = ['question','description']
success_url = reverse_lazy('Politics_topic')
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
def test_func(self):
post = self.get_object()
if self.request.user == post.author:
return True
return False
class Deletepoliticspost(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
model = PoliticsPost
success_url = reverse_lazy('Politics_topic')
def test_func(self):
post = self.get_object()
if self.request.user == post.author:
return True
return False
#POLITICS-------------
I found a solution guys, it is pretty simple.
I removed
from .views import Politics_topic,Questionpolitics,Updatepolitics,Politics_post_details,Deletepoliticspost,Profile,home
In Lisk.url
I only used from . import views and I called all the functions in views,py with the dot operator.
Don't ask me how it worked, but it did work.
I am following this tutorial to create a video uploader in my Django project and have run into this error:
..src/video/views.py", line 9, in showvideo
videofile= lastvideo.videofile
AttributeError: 'NoneType' object has no attribute 'videofile'
I'm sure I am missing something obvious and have been looking for the answer for a while now. Would be grateful for any help.
views.py
from django.shortcuts import render
from .models import VideoUpload
from .forms import VideoForm
def showvideo(request):
lastvideo= VideoUpload.objects.last()
videofile= lastvideo.videofile
form= VideoForm(request.POST or None, request.FILES or None)
if form.is_valid():
form.save()
context= {'videofile': videofile,
'form': form
}
return render(request, 'video.html', context)
forms.py
from django import forms
from .models import VideoUpload
class VideoForm(forms.ModelForm):
class Meta:
model = VideoUpload
fields = ["name", "videofile"]
models.py
from django.db import models
class VideoUpload(models.Model):
name= models.CharField(max_length=500)
videofile= models.FileField(upload_to='videos/', null=True, verbose_name="")
def __str__(self):
return self.name + ": " + str(self.videofile)
from django.conf import settings
from django.contrib import admin
from django.urls import path
from django.conf.urls.static import static
from video.views import (
showvideo,
)
urlpatterns = [
path('showvideo', showvideo, name='showvideo'),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
FYI I updated the name of the model to 'VideoUpload' vs the tutorial.
There is no last_video record in your database. To prevent this from erroring out in such and instance, you could change the line: videofile= lastvideo.videofile into
videofile = lastvideo.videofile if lastvideo else None
This will prevent an error from being thrown. Alternatively you could put the whole bit in a try/except block.
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',
]
I am trying to define a class in views.py which is inheriting generic view. The code is as follows. On running server I get the error that
class UserFormView(View):
NameError: name 'View' is not defined
although I have imported generic. Please let me know the reason.
from django.views import generic
from django.utils import timezone
from django.shortcuts import render, get_object_or_404,render_to_response,redirect
from django.http import HttpResponseRedirect
from django.contrib import auth
from django.contrib.auth import authenticate,login
from django.core.context_processors import csrf
from .forms import UserForm
# Create your views here.
def home(request):
return render(request, 'fosssite/home.html')
def login(request):
c={}
c.update(csrf(request))
return render_to_response('fosssite/login.html',c)
class UserFormView(View):
form_class=UserForm
template_name='fosssite/signup.html'
def get(self,request):
form=self.form_class(None)
return render(request,self.template_name,{'form':form})
#validate by forms of django
def post(self,request):
form=self.form_class(request.POST)
if form.is_valid():
# not saving to database only creating object
user=form.save(commit=False)
#normalized data
username=form.cleaned_data['username']
password=form.cleaned_data['password']
#not as plain data
user.set_password(password)
user.save() #saved to database
def auth_view(request):
username=request.POST.get('username', '')
password=request.POST.get('password', '')
user=auth.authenticate(username=username,password=password)
if user is not None:
auth.login(request,user)
return HttpResponseRedirect('/loggedin')#url in brackets
else:
return HttpResponseRedirect('/invalid')
def loggedin(request):
return render_to_response('fosssite/loggedin.html',{'fullname':request.user.username})
def logout(request):
auth.logout(request)
return render_to_response('fosssite/logout.html')
def invalid_login(request):
return render_to_response('fosssite/invalid_login.html')
`
You need to either import View explicitly:
from django.views.generic import View
or refer to it as generic.View:
class UserFormView(generic.View):
# ...
The View name needs to be imported. Add the following import statement:
from django.views.generic import View
Or use the already imported generic module in
class UserFormView(generic.View)
# ^
in urls.py
from my_app import views
eg code:
urls.py
from django.conf.urls import url
from django.contrib import admin
from pro1 import views
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^admin/', admin.site.urls),
]
views.py
from django.shortcuts import render
def home(request):
template="home.html"
context={}
return render(request,template,context)
guess it will solve the problem.
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">