10👍
Your view with the form should look something like this:
def add(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
# do stuff & add to database
my_file = FileField.objects.create()
# use my_file.pk or whatever attribute of FileField your id is based on
return HttpResponseRedirect('/files/%i/' % my_file.pk)
else:
form = UploadFileForm()
return render_to_response('upload_file.html', {
'form': form,
})
21👍
You’ve got the arguments to reverse
wrong in
return HttpResponseRedirect(reverse('/file/', args=[my_file.id]))
reverse
takes a view or the name or a view, not a url.
You don’t say what your view function is called for viewing the file, but lets say it is called view
, then the above should be
return HttpResponseRedirect(reverse('view', args=[my_file.id]))
or maybe
return HttpResponseRedirect(reverse(view, args=[my_file.id]))
Depending on exactly what you wrote in urls.py
You can name the views in urls.py
and use those names instead of the function names- see the documentation for more examples
Using reverse is a good idea if you like shuffling your urls.py
around – you’ll be able to change any of the paths and all your views will just keep working.
- Using django.db.connection.queries
- ValueError: Incorrect timezone setting while migrating manage.py file in Django
- Django redirect to another view with context
- How to display the message passed to Http404 in a custom 404 Error template in Django?
- Pagination and get parameters
1👍
Or you can use simply the redirect(to[, permanent=False], *args, **kwargs)
shortcut function:
-
by passing a model object (if the model’s get_absolute_url method is defined), so in your case:
my_file = FileField.objects.create() return redirect(my_file)
-
by passing a view name and some positional and keyword arguments, in your case:
my_file = FileField.objects.create() return redirect('file', my_file.pk)
or using positional arguments if your url definition requires it:
my_file = FileField.objects.create() return redirect('file', file_id=my_file.pk)
- by passing a relative, absolute, or full URL:
my_file = FileField.objects.create() return redirect('/files/%i/' % my_file.pk)
- You cannot add messages without installing django.contrib.messages.middleware.MessageMiddleware
- How to use Datepicker in django
- How to serialize queryset in get method in Django Rest Framework?
- Django, division between two annotate result won't calculate correctly
0👍
Seems to me that what you want to achieve is exactly what the Django Tutorial explains, step by step. If you have some time, check it out: Django Tutorialhttps://docs.djangoproject.com/en/1.6/intro/tutorial03/
- Django: Change models without clearing all data?
- Saving profile with registration in Django-Registration
- Cannot use environment variables for settings in Django
- Django slice numbers in template
- Libmysqlclient.18.dylib image not found when using MySQL from Django on OS X