Я создал приложение для опросов из Django Documentation, но я хочу добавить в него еще несколько функций, таких как
- Не только администратор, но и каждый пользователь без регистрации должен получить возможность добавить вопрос
- При добавлении вопроса должна быть указана действительная дата, до которой можно голосовать, в противном случае она должна отображаться как «Опросы закрыты» и должна быть перенаправлена на страницу результатов.
Это мой проект Опрос:
poll
|_ __init__.py
|_ settings.py
|_ urls.py
|_ wsgi.py
polls
|_ static
|_ templates
|_ polls
|_ contains base.html, index.html, detail.html, results.html
|_ __init__.py
|_ admin.py
|_ models.py
|_ apps.py
|_ views.py
|_ urls.py
|_ tests.py
from django.contrib import admin
from .models import Question, Choice
class ChoiceInline(admin.TabularInline):
model = Choice
extra = 4
class QuestionAdmin(admin.ModelAdmin):
list_display = ('topic', 'question_text', 'pub_date', 'date_valid')
list_filter = ['pub_date']
search_fields = ['topic']
fieldsets = [
(None, {'fields': ['topic', 'question_text']}),
('Date Information', {'fields': ['pub_date', 'date_valid'], 'classes': ['collapse']}),
]
inlines = [ChoiceInline]
admin.site.register(Question, QuestionAdmin)
from django.db import models
import datetime
from django.utils import timezone
from django.urls import reverse
class Question(models.Model):
topic = models.CharField(max_length=200)
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
date_valid = models.DateField('validity date')
def __str__(self):
return self.topic
def was_published_recently(self):
now = timezone.now()
return now - datetime.timedelta(days=30) <= self.pub_date <= now
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from .models import Question, Choice
from django.utils import timezone
from django.views import generic
import datetime
from django.views.generic.edit import CreateView
from .models import Question, Choice
class IndexView(generic.ListView):
template_name = 'polls/index.html'
context_object_name = 'latest_question_list'
def get_queryset(self):
return Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:10]
class DetailView(generic.DetailView):
model = Question
template_name = 'polls/detail.html'
class ResultsView(generic.DetailView):
model = Question
template_name = 'polls/results.html'
def vote(request, question_id):
question = get_object_or_404(Question, pk=question_id)
if 1==0: #question.date_valid<=timezone.now():
return render(request, 'polls/results.html question.id', {'error_message': "The Question is no longer available for voting."})
else:
try:
selected_choice = question.choice_set.get(pk=request.POST['choice'])
except(KeyError, Choice.DoesNotExist):
return render(request, 'polls/detail.html', {'question':question, 'error_message':"You didnt select any choice."})
else:
selected_choice.votes+=1
selected_choice.save()
return HttpResponseRedirect(reverse('polls:results',args=(question.id,))
from django.contrib import admin
from django.urls import path, include
from django.views.generic import RedirectView
urlpatterns = [
path('admin/', admin.site.urls),
path('polls/', include('polls.urls')),
path('', RedirectView.as_view(url='/polls/', permanent=True)),
]
from django.urls import path
from . import views
app_name = 'polls'
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('<int:pk>/', views.DetailView.as_view(), name='detail'),
path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),
path('<int:question_id>/vote/', views.vote, name='vote'),
path('question/create/', views.QuestionCreate.as_view(), name='question-create'),
]
Это github Ссылка:
https://github.com/priyanshu-panwar/Django-Polls-App
Любой может даже вытащить запрос ...