· 8 years ago · Aug 12, 2018, 02:08 AM
1from django.contrib import admin
2from django.urls import path
3from django.conf.urls import url , include
4from django.conf import settings
5from django.conf.urls.static import static
6from .views import home_page , contact_page , about_page , register_page ,
7login_page
8
9urlpatterns = [
10path('admin/', admin.site.urls),
11url('^blog/', include('enc_vip_blog.urls',namespace='enc_vip_blog')),
12url(r'^$',home_page,name='home'),
13url(r'^login/$',login_page,name='login'),
14url(r'^register/$',register_page,name='register'),
15url(r'^about/$',about_page,name='about'),
16url(r'^contact/$',contact_page,name='contact'),
17
18]
19
20from django.shortcuts import render , redirect
21from django.http import HttpResponse
22from .forms import ContactForm,LoginForm,RegisterForm
23from django.contrib.auth import authenticate,login
24from django.contrib.auth import get_user_model
25
26
27
28
29
30def home_page(r):
31context = {
32 'title':'Hello World!',
33 'content':'Welcome to the Home Page!'
34}
35if r.user.is_authenticated:
36 context['premium_content']='Yeahhhh!'
37return render(r,'home_page.html',context)
38
39def about_page(r):
40context = {
41 'title': 'ABOUT PAGE',
42 'content': 'Welcome to the About Page!'
43}
44return render(r,'about_page.html',context)
45
46def contact_page(r):
47contact_form = ContactForm(r.POST or None)
48context = {
49 'title': 'CONTACT PAGE',
50 'content': 'Welcome to the Contact Page!',
51 'form':contact_form,
52 'brand':'new brand',
53}
54if contact_form.is_valid():
55 print(contact_form.cleaned_data)
56
57return render(r,'contacts/view.html',context)
58
59User = get_user_model()
60#This captures the default fields of User Model
61def register_page(r):
62register_form = RegisterForm(r.POST or None)
63context = {
64 'register_form':register_form
65}
66if register_form.is_valid():
67 username = register_form.cleaned_data.get('username')
68 email = register_form.cleaned_data.get('email')
69 password = register_form.cleaned_data.get('password')
70 new_user = User.objects.create_user(username,email,password)
71 print(new_user)
72 # print(password)
73return render(r,'auth/register.html',context)
74
75
76
77def login_page(r):
78login_form = LoginForm(r.POST or None)
79context = {
80
81 'login_form':login_form
82}
83print('User Logged in :')
84print(r.user.is_authenticated)
85if login_form.is_valid():
86 print(login_form.cleaned_data)
87 username = login_form.cleaned_data.get('username')
88 password = login_form.cleaned_data.get('password')
89 user = authenticate(r,username=username,password=password)
90 print("User Logged in:")
91 print(r.user.is_authenticated)
92 print(user)
93 if user is not None:
94 print(r.user.is_authenticated)
95 login(r,user)
96 # login_form['login_form']=login_form
97 return redirect('/')
98 else:
99 print('Error')
100
101
102return render(r,'auth/login.html',context)
103
104from django import forms
105from django.core.validators import ValidationError
106from django.contrib.auth import get_user_model
107
108
109
110
111
112User = get_user_model()
113class ContactForm(forms.Form):
114fullname = forms.CharField(max_length=100,widget=forms.TextInput(
115 attrs={'class':'form-
116control','placeholder':'Your name here',
117 'id':'fullname'}
118 ),help_text="Max 100
119characters")
120email = forms.EmailField(widget=forms.TextInput(
121 attrs={'class':'form-
122control','placeholder':'Your email here',
123 'id':'email'}
124 ))
125content = forms.CharField(max_length=300,widget=forms.Textarea(attrs=
126{'class':'form-control',
127 'placeholder':'Leave
128your message here',
129 'id':'content'}),
130 help_text='300 characters max')
131
132
133def clean_email(self):
134 email = self.cleaned_data.get('email')
135
136 if not 'gmail.com' in email:
137 raise forms.ValidationError("Email must be Gmail id!")
138 return email
139
140
141class RegisterForm(forms.Form):
142username = forms.CharField()
143email = forms.CharField()
144password = forms.CharField(widget=forms.PasswordInput)
145confirm_password = forms.CharField(label="Confirm
146Password",widget=forms.PasswordInput)
147
148#Unique username constraint setup
149def clean_username(self):
150 username = self.cleaned_data.get('username')
151 #Queryset to get all logged in or registered user objects from User
152model
153 user_queries = User.objects.filter(username=username)#Got all usernames
154that are already registered
155 #Checking if current username matches any other username from the
156results
157 if user_queries.exists():
158 raise forms.ValidationError('Username Exists!')
159 return username
160
161# Unique email id constraint setup
162def clean_email(self):
163 email = self.cleaned_data.get('email')
164 email_queries = User.objects.filter(email=email)
165 if email_queries.exists():
166 raise forms.ValidationError('This Email Id is taken!')
167 return email
168
169
170#Password confirmation during registration
171def clean(self):
172 data = self.cleaned_data
173 password = self.cleaned_data.get('password')
174 confirmation_password = self.cleaned_data.get('confirm_password')
175
176 if password!=confirmation_password:
177 raise forms.ValidationError("Passwords must match!")
178 return data
179
180
181
182
183
184class LoginForm(forms.Form):
185 username = forms.CharField()
186 password = forms.CharField(widget=forms.PasswordInput)
187
188# Create your models here.
189class EntryManager(models.Manager):
190def published(self):
191 return self.get_queryset().filter(publish = True)
192
193
194class Tag(models.Model):
195slug = models.SlugField(max_length=200 , unique=True)
196
197
198def __str__(self):
199 return self.slug
200
201
202class Entry(models.Model):
203title = models.CharField(max_length=100)
204body = models.TextField(max_length=1000)
205short_body = models.CharField(max_length=200,default='Click link to know
206more')
207slug = models.SlugField(max_length=100 , unique=True)
208publish = models.BooleanField(default=True)
209created = models.DateTimeField(auto_now_add=True)
210modified = models.DateTimeField(auto_now=True)
211image = models.ImageField(upload_to='blog/',null=True,blank=True)
212tags = models.ManyToManyField(Tag)
213objects = EntryManager()
214
215def __str__(self):
216 return self.title
217
218def get_absolute_url(self):
219 return reverse('enc_vip_blog:detail',kwargs={'slug':self.slug})
220
221#To make admin representations look better override class Meta
222
223class Meta:
224 verbose_name = 'Blog Entry'
225 verbose_name_plural = 'Blog Entries'
226 #Set ordering to reverse chronological order
227 ordering = ['-created']
228
229app_name = 'enc_vip_blog'
230
231urlpatterns = [
232
233url(r'^$', BlogListView.as_view() , name='list'),
234url(r'^(?P<slug>S+)$', BlogDetailView.as_view() , name='detail'),
235
236]
237
238{%extends 'base/base.html'%}
239{%load static%}
240{%block content%}
241<ul>{%for object in object_list%}
242 {%include 'blog/card.html' with instance=object%}
243 {%endfor%}
244 </ul>
245 {%endblock%}
246
247<div class="card-body">
248 <h5 class="card-title"> <a href="{{ instance.get_absolute_url }}">{{
249 instance.title }}</a></h5>
250 {%if instance.image%}
251<a href="{{ instance.get_absolute_url }}" >
252 <div class="row">
253 <div class="col-md-4"></div>
254 <div class="col-md-4">
255 <img class="card-img-top" src="{{ instance.image.url }}" style="width:
256 100%;" alt="{{ instance.title }}">
257 </div>
258 <div class="col-md-4"></div>
259 </div>
260 </a>
261 {%endif%}
262 <p class="card-text">{{ instance.short_body }}</p>
263 <p class="Meta">{{ instance.created }}</p>
264 <p class="Meta">tagged under {{ instance.tags.all|join:', ' }}</p>
265 <a href="{{ instance.get_absolute_url }}" class="btn btn-
266 primary">View</a>
267
268 </div>
269 </div>
270
271django.urls.exceptions.NoReverseMatch: Reverse for 'detail' not found.
272 'detail' is not a valid view function or pattern name.