我是Django的新手,我想创建一个应用程序,使选定的用户能够登录,然后上传文件,然后再对其进行处理。
models.py
class Profile(models.Model):
username = models.OneToOneField(User, on_delete=models.CASCADE)
password = models.TextField(max_length=80,blank=True)
company = models.TextField(max_length=80, blank=True)
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()
class Document(models.Model):
uploaded_by = models.ForeignKey(Profile,on_delete=models.CASCADE)
date_uploaded = models.DateTimeField(auto_now_add=True)
forms.py
class LoginForm(forms.Form):
username = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput)
company = forms.CharField()
class DocumentForm(forms.Form):
docfile = forms.FileField(label='Select a file')
malex.urls(应用程序网址)
from malex.views import list
from malex.views import login
urlpatterns = [
url(r'^list/$', list, name='list'),
url(r'^login/$', login, name='login'),
]
项目/网址
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^newp/', include('malex.urls')),
]
views.py
def login(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
user = authenticate(user=cd['user'],password=cd['password'],company=cd['company'])
if user is not None:
if user is active:
login(request,user)
return HttpResponse('Authenticated successfully')
else:
return HttpResponse('Disabled account')
else:
return HttpResponse('Invalid login')
else:
form=LoginForm()
return render(request,'account/login.html',{'form': form})
def list(request):
# Handle file upload
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
newdoc = Document(docfile=request.FILES['docfile'])
newdoc.save()
# Redirect to the document list after POST
return HttpResponseRedirect(reverse('list'))
现在,登录和上传操作已分开。 如何更改我的视图和网址以先登录然后再上传? 我需要在装饰器中使用基于类的视图吗?
答案 0 :(得分:3)
创建自定义登录表单并查看。
使用您的localhost:8000地址作为登录模板
(app) urlpatterns = [path('',views.loginview,name = 'login')]
(project) urlpatterns = [path('', include('malex.urls')),)]
使用{% block content %}{% endblock %}
在模板或视图中使用通过限制{% if request.user.is_authenticated %}
,让他们访问upload section
。