所以我是django的初学者,我正在尝试通过我的日历网站实现登录系统。
我遇到的麻烦是在日历上显示仅已登录用户发布的事件,而不是在日历上查看数据库中的所有事件。
from datetime import datetime, timedelta, date
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.views import generic
from django.urls import reverse
from django.utils.safestring import mark_safe
import calendar
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from django.contrib.auth import logout
from django.views.generic import View
from .models import *
from .utils import Calendar
from .forms import EventForm
from .forms import UserForm
class CalendarView(generic.ListView):
model = Event
template_name = 'cal/calendar.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
d = get_date(self.request.GET.get('month', None))
cal = Calendar(d.year, d.month)
html_cal = cal.formatmonth(withyear=True)
context['calendar'] = mark_safe(html_cal)
context['prev_month'] = prev_month(d)
context['next_month'] = next_month(d)
return context
def event(request, event_id=None):
instance = Event()
if event_id:
instance = get_object_or_404(Event, pk=event_id)
else:
instance = Event()
form = EventForm(request.POST or None, instance=instance)
if request.POST and form.is_valid():
form.save()
return HttpResponseRedirect(reverse('cal:calendar'))
return render(request, 'cal/event.html', {'form': form})
def login_user(request):
if request.method == "POST":
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return render(request, 'cal/calendar.html', {'calendar': calendar})
else:
return render(request, 'cal/login.html', {'error_message': 'Your account has been disabled'})
else:
return render(request, 'cal/login.html', {'error_message': 'Invalid login'})
return render(request, 'cal/login.html')
from django.db import models
from django.urls import reverse
from django.contrib.auth.models import Permission, User
class Event(models.Model):
title = models.CharField(max_length=200)
description = models.TextField()
start_time = models.DateTimeField()
end_time = models.DateTimeField()
@property
def get_html_url(self):
url = reverse('cal:event_edit', args=(self.id,))
return f'<a href="{url}"> {self.title} </a>'
{% extends 'cal/base.html' %}
{% block title %}
Calendar
{% endblock %}
{% block content %}
<div class="clearfix">
<a class="btn btn-info left" href="{% url 'cal:calendar' %}?{{ prev_month }}"> Previous Month </a>
<a class="btn btn-info right" href="{% url 'cal:calendar' %}?{{ next_month }}"> Next Month </a>
<a class="btn btn-info right" href="{% url 'cal:event_new' %}"> New Event </a>
</div>
{{ calendar }}
{% endblock %}
{% extends 'cal/base.html' %}
{% block title %}
Event
{% endblock %}
{% block content %}
<div class="clearfix">
<a class="btn btn-info left" href="{% url 'cal:calendar' %}"> Calendar </a>
</div>
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
<div class="alert alert-danger">
{{ field.label }} <strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endfor %}
{% for error in form.non_field_errors %}
<div class="alert alert-danger">
{{ field.label }} <strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endif %}
<form method="post">
{% csrf_token %}
<table class="form form-table">
{{ form }}
<tr><td colspan="2"><button type="submit" class="btn btn-info right"> Submit </button></td></tr>
</table>
</form>
{% endblock %}
{% extends 'cal/base_visitor.html' %}
{% block title %}Log In{% endblock %}
{% block login_active %}active{% endblock %}
{% block body %}
<div class="container-fluid">
<div class="row">
<div class="col-sm-12 col-md-6">
<div class="panel panel-default">
<div class="panel-body">
<h3>Log In</h3>
{% if error_message %}
<p><strong>{{ error_message }}</strong></p>
{% endif %}
<form class="form-horizontal" role="form" action="{% url 'cal:login_user'%}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="form-group">
<label class="control-label col-sm-2" for="id_username">
Username:
</label>
<div class="col-sm-10">
<input id="id_username" maxlength="30" name="username" type="text">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="id_password">
Password:
</label>
<div class="col-sm-10">
<input id="id_password" maxlength="30" name="password" type="password">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
</form>
</div>
<div class="panel-footer">
Don't have an account? <a href="{% url 'cal:register' %}">Click here</a> to register.
</div>
</div>
</div>
</div>
</div>
{% endblock %}
from django.conf.urls import url
from . import views
app_name = 'cal'
urlpatterns = [
url(r'^index/$', views.index, name='index'),
url(r'^calendar/$', views.CalendarView.as_view(), name='calendar'),
url(r'^register/$', views.register, name='register'),
url(r'^login_user/$', views.login_user, name='login_user'),
url(r'^logout_user/$', views.logout_user, name='logout_user'),
url(r'^event/new/$', views.event, name='event_new'),
url(r'^event/edit/(?P<event_id>\d+)/$', views.event, name='event_edit'),
]
from django.forms import ModelForm, DateInput
from .models import Event
from django.contrib.auth.models import User
from django import forms
class EventForm(forms.ModelForm):
class Meta:
model = Event
# datetime-local is a HTML5 input type, format to make date time show on fields
widgets = {
'start_time': DateInput(attrs={'type': 'datetime-local'}, format='%Y-%m-%dT%H:%M'),
'end_time': DateInput(attrs={'type': 'datetime-local'}, format='%Y-%m-%dT%H:%M'),
}
fields = '__all__'
def __init__(self, *args, **kwargs):
super(EventForm, self).__init__(*args, **kwargs)
# input_formats parses HTML5 datetime-local input to datetime field
self.fields['start_time'].input_formats = ('%Y-%m-%dT%H:%M',)
self.fields['end_time'].input_formats = ('%Y-%m-%dT%H:%M',)
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = ['username', 'email', 'password',]