/
views.py
101 lines (75 loc) · 2.62 KB
/
views.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
from django.contrib.auth.decorators import login_required
from django.http import Http404
from django.shortcuts import render, redirect
from django.template.defaultfilters import slugify
from collection.forms import ThingForm
from collection.models import Thing
def index(request):
things = Thing.objects.all()
return render(request, 'index.html', {
'things': things,
})
def thing_detail(request, slug):
# grab the object...
thing = Thing.objects.get(slug=slug)
# and pass to the template
return render(request, 'things/thing_detail.html', {
'thing': thing,
})
@login_required
def edit_thing(request, slug):
# grab the object...
thing = Thing.objects.get(slug=slug)
# grab the current logged in user and make sure they're the owner of the thing
if thing.user != request.user:
raise Http404
# set the form we're using...
form_class = ThingForm
# if we're coming to this view from a submitted form,
if request.method == 'POST':
# grab the data from the submitted form
form = form_class(data=request.POST, instance=thing)
if form.is_valid():
# save the new data
form.save()
return redirect('thing_detail', slug=thing.slug)
# otherwise just create the form
else:
form = form_class(instance=thing)
# and render the template
return render(request, 'things/edit_thing.html', {
'thing': thing,
'form': form,
})
def create_thing(request):
form_class = ThingForm
# if we're coming from a submitted form, do this
if request.method == 'POST':
# grab the data from the submitted form and apply to the form
form = form_class(request.POST)
if form.is_valid():
# create an instance but do not save yet
thing = form.save(commit=False)
# set the additional details
thing.user = request.user
thing.slug = slugify(thing.name)
# save the object
thing.save()
# redirect to our newly created thing
return redirect('thing_detail', slug=thing.slug)
# otherwise just create the form
else:
form = form_class()
return render(request, 'things/create_thing.html', {
'form': form,
})
def browse_by_name(request, initial=None):
if initial:
things = Thing.objects.filter(
name__istartswith=initial).order_by('name')
else:
things = Thing.objects.all().order_by('name')
return render(request, 'search/search.html', {
'things': things,
'initial': initial,
})