hyeonga_code

파이선 웹구축_장고_35_투표 기능까지 구현 본문

Python_Django

파이선 웹구축_장고_35_투표 기능까지 구현

hyeonga 2023. 6. 27. 05:59
반응형

- 투표 기능까지 전체 코드

1. <config> > 'settings.py'

'settings.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
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = 'django-insecure-43yzpkwlua_=x(jm)8%4j7#qth44sr^b3u!1m2@1)!o0x2+j+&'
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'acc.apps.AccConfig',
    'board.apps.BoardConfig',
    'mathfilters'
]
AUTH_USER_MODEL = 'acc.User'
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR/'media'
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'config.urls'
TEMPLATES = [
    {
        'BACKEND''django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR/'templates'],
        'APP_DIRS'True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
WSGI_APPLICATION = 'config.wsgi.application'
DATABASES = {
    'default': {
        'ENGINE''django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}
AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME''django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME''django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME''django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME''django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Seoul'
USE_I18N = True
USE_TZ = False
STATIC_URL = 'static/'
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
cs

2. <config> > 'urls.py'

'urls.py'

=====

1
2
3
4
5
6
7
8
9
10
11
from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from . import settings
 
urlpatterns = [
    path('admin/', admin.site.urls),
    path('acc/', include('acc.urls')),
    path('board/', include('board.urls')),
    path('tr/', include('tr.urls')),
+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
cs

- 투표 기능까지 전체 코드

3. <acc> > 'admin.py'

'admin.py'

=====

1
2
3
4
from django.contrib import admin
from .models import User
 
admin.site.register(User)
cs

4. <acc> > 'models.py'

'models.py'

=====

1
2
3
4
5
from django.db import models
from django.contrib.auth.models import AbstractUser
 
class User(AbstractUser):
    pass
cs

5. <acc> > 'urls.py'

'urls.py'

=====

1
2
3
4
5
6
7
8
9
10
from django.urls import path
from . import views
 
app_name='acc'
urlpatterns = [
    path('index/', views.index, name="index"),
    path('login/', views.ulogin, name='login'),
    path('logout/', views.ulogout, name='logout'),
]
 
cs

6. <acc> > 'views.py'

'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
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.hashers import check_password
 
def index(request):
    
    return render(request, 'acc/index.html')
 
def ulogin(request):
    if request.user.is_authenticated:
        return redirect('acc:index')
    if request.method=="POST":
        un = request.POST.get('uname')
        up = request.POST.get('upass')
        u = authenticate(username=un, password=up)
        if u:
            login(request,u)
            return redirect('acc:index')
        else:
            pass
    return render(request, 'acc/login.html')
 
def ulogout(request):
    logout(request)
    return redirect('acc:index')
cs

7. <vote> > 'admin.py'

'admin.py'

=====

1
2
3
4
5
from django.contrib import admin
from .models import Topic, Choice
 
admin.site.register(Topic)
admin.site.register(Choice)
cs

8. <vote> > 'models.py'

'models.py'

=====

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
from django.db import models
from acc.models import User
 
class Topic(models.Model):
    subject = models.CharField(max_length=100)
    maker = models.ForeignKey(User, on_delete=models.CASCADE,related_name='maker')
    content = models.TextField()
    voter = models.ManyToManyField(User, blank=True, related_name='voter')
    
    def __str__(self):
        return self.subject
 
class Choice(models.Model):
    top = models.ForeignKey(Topic, on_delete=models.CASCADE)
    name = models.CharField(max_length=100)
    num = models.IntegerField(default=0)
    
    def __str__(self):
        return f"{self.top}_{self.name}"
cs

9. <vote> > 'urls.py'

'urls.py'

=====

1
2
3
4
5
6
7
8
9
from django.urls import path
from . import views
 
app_name='vote'
urlpatterns = [
    path('index/', views.index, name="index"),
    path('detail/<vpk>', views.detail, name='detail'),
    path('vote/<vpk>', views.vote, name='vote'),
]
cs

10. <vote> > 'views.py'

'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
from django.shortcuts import render, redirect
from .models import Topic,Choice
 
def vote(request, vpk):
    tp = Topic.objects.get(id=vpk)
    if not request.user in tp.voter.all():
        tp.voter.add(request.user)
        vpk = request.POST.get('cho')
        c = Choice.objects.get(id=vpk)
        c.num +=1
        c.save()
    return redirect('vote:detail', vpk)
 
def detail(request, vpk):
    tp = Topic.objects.get(id=vpk)
    ch = tp.choice_set.all()
    print(ch)
    context = {
        'tp' : tp,
        'cset' : ch,
    }
    return render(request, 'vote/detail.html', context)
 
def index(request):
    tp = Topic.objects.all()
    context = {
        'tp' : tp
    }
    return render(request, 'vote/index.html', context)
cs

- 투표 기능까지 전체 코드

11. <templates> > <acc> > 'index.html'

'index.html'

=====

1
2
3
4
5
6
7
8
<h1><b>MAIN PAGE</b></h1>
{% if user.is_authenticated %}
    <b>{{user}}</b> wellcome!!!<br><br>
    <a href="{% url 'vote:index' %}"><button>Vote</button></a>
    <a href="{% url 'acc:logout' %}"><button>Logout</button></a>
{% else %}
    <a href="{% url 'acc:login' %}"><button>Login</button></a>
{% endif %}
cs

12. <templates> > <acc> > 'login.html'

'login.html'

=====

1
2
3
4
5
6
7
8
<h1><b>LOGIN PAGE</b></h1>
<form method='post'>
    {% csrf_token %}
    <input type='text' name='uname' placeholder="Input ID"><br><br>
    <input type='password' name='upass' placeholder='Input Password'><br><br>
    <button>Login</button>
    <a href="{% url 'acc:index' %}"><button>Cancle</button></a>
</form>
cs

13. <templates> > <vote> > 'index.html'

'index.html'

=====

1
2
3
4
5
6
7
8
9
10
11
12
<h1><b>VOTE PAGE</b></h1>
<b>{{user}}</b> Please vote now!<br><br>
<ul>
    {% for i in tp %}
        <li>
            <a href="{% url 'vote:detail' i.id %}">{{i}}</a>
            {% if user.name in tp.voter.all %}★{% endif %}
        </li>
    {% endfor %}
</ul>
<a href="{% url 'acc:index' %}"><button>Main</button></a>
<a href="{% url 'acc:logout' %}"><button>Logout</button></a>
cs

14. <templates> > <vote> > 'detail.html'

'detail.html'

=====

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
<h1><b>DETAIL PAGE</b></h1>
 
<b>{{tp.subject}}</b> <br><br>
Please vote now!<br><br>
 
made by <b>{{tp.maker}}</b> <br><br>
<textarea cols='50' rows='4' disabled>{{tp.content}}</textarea><br><br>
 
{% load mathfilters %}
{% if user in tp.voter.all %}
    <h4>Vote Result</h4>
    {% for i in cset %}
        <b>{{i.name}}</b> {{i.num | div:tp.voter.count|mul:100 | floatformat:2}} %<br><br>
    {% endfor %}
    <a href="{% url 'vote:index' %}"><button type='button'>Main</button></a>
{% else %}
    <form method='post' action="{% url 'vote:vote' tp.id %}">
        {% csrf_token %}
        {% for i in cset %}
            <input type='radio' name='cho' value="{{i.id}}" {% if forloop.first %}checked{% endif %}>{{i.name}}
        {% endfor %}
        <button>Vote</button>
        <a href="{% url 'vote:index' %}"><button type='button'>Main</button></a>
    </form>
{% endif %}
cs

 

반응형