好吧,看来我在这个小任务上已经超出了我的想法。我想询问一个人如何提交到表单,而不依赖于URL值?
在我的示例中,用户必须先登录才能看到他们的图库图片。确定这是通过“上下文”,它具有分配给它的活动用户(如登录)。道具@ chem1st& @ Daniel-Roseman早些时候帮助我解决这个问题。现在,它可以在登录后在主页中显示自己的用户图库。
我不想上传“blahblah.com/bobby/upload”,因为它似乎不太安全。我想通过“blahblah.com/upload/”让登录用户上传。这意味着view.py中的表单必须以某种方式获取登录用户的上下文,并将数据保存到该帐户下的数据库中。
我一直在四处寻找,并寻找答案,但找不到任何东西。有人可以帮助我指出正确的方向吗?
这是我的models.py
class UserProfile(models.Model):
user = models.OneToOneField(User)
activation_key = models.CharField(max_length=40, blank=True)
key_expires = models.DateTimeField(default=datetime.date.today())
def __str__(self):
return self.user.username
class Meta:
verbose_name_plural='User profiles'
class ImageDoc(models.Model):
user = models.ForeignKey(UserProfile)
imgfile = models.ImageField(upload_to='images/')
forms.py:
class RegistrationForm(UserCreationForm):
email = forms.EmailField(required=True, widget=forms.TextInput(attrs={'placeholder': 'E-mail address'}))
first_name = forms.CharField(required=True)
last_name = forms.CharField(required=True)
class Meta:
model = User
fields = ('first_name', 'last_name', 'email', 'username', 'password1', 'password2')
class ImgDocForm(forms.Form):
user_file = forms.ImageField()
def clean_user_file(self, *args, **kwargs):
cleaned_data = super(ImgDocForm,self).clean()
user_file = cleaned_data.get("user_file")
if user_file:
if user_file.size > 5 * 1024 * 1024:
raise forms.ValidationError("Filesize is too big.")
if not os.path.splitext(user_file.name)[1].strip().lower() in ['.jpg','.png','.gif','.jpeg']:
raise forms.ValidationError("File does not look like as picture.")
return user_file
class UserForm(forms.Form):
class Meta:
model = User
fields = ['first_name', 'last_name', 'password', 'email', 'username']
我的views.py文件(编辑:更改了索引以显示用户详细信息,图库和快速上传功能):
def sign_in(request):
context = RequestContext(request)
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user:
if user.is_active:
login(request, user)
return HttpResponseRedirect('/', context)
else:
return HttpResponse("Verify your account!")
else:
return HttpResponse("Invalid login details supplied.")
def populateContext(request, context):
context['authenticated'] = request.user.is_authenticated()
if context['authenticated'] == True:
context['username'] = request.user.username
def index(request):
user_details = UserProfile.objects.get(user=request.user)
gallery = ImageDoc.objects.filter(user_id=request.user.id)
if request.method == 'POST':
form = ImgDocForm(request.POST, request.FILES)
if form.is_valid():
origin_form = form.cleaned_data["user_file"]
origin_name = origin_form.name
original_name = ImageDoc(user_id=request.user.id, imgfile=origin_name)
original_name.save()
return HttpResponse('Saved!')
else:
form = ImgDocForm()
documents = ImageDoc.objects.all()
return render(request, 'test.html', {'documents': documents, 'form': form, 'user_details': user_details, 'gallery': gallery})
def upload(request):
data = {}
thumb_size = (100,100)
micro_thumb_size = (50,50)
if request.method == 'POST':
userform = ImgDocForm(request.POST, request.FILES)
if userform.is_valid():
origin_form = userform.cleaned_data["user_file"]
origin_name = origin_form.name
original_file = os.path.join(settings.MEDIA_ROOT, origin_name)
.
.
.
original_name = ImageDoc(imgfile=origin_name)
original_name.save()
.
.
.
userform = ImgDocForm()
else:
return HttpResponse('Nooo!')
else:
userform = ImgDocForm()
data.update(image_gallery = ImageDoc.objects.only('imgfile'))
data.update(userform=userform)
data.update(csrf(request))
return render(request, 'upload.html', data)
编辑:我相信大家可以大大清理索引文件。此外,底部不是很优雅,但它有效。
upload.html文档:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<div>
<form method="post" action="" enctype="multipart/form-data">
{% csrf_token %}
{{ userform.as_p }}
<input type="submit">
</form>
<br><br>
<h2>{{ origin_name }} (original)</h2>
{% if origin_name %}
<img src="{{ MEDIA_URL }}{{ origin_name }}">
{% endif %}
<br><br>
{% if image_gallery %}
{% for image in image_gallery %}
<img src="/{{ image.thumbfile }}">
{% endfor %}
{% endif %}
</div>
</body>
</html>
谢谢!
答案 0 :(得分:1)
您可以在视图中以[{1}}。
获取当前登录的用户