在注册用户时,我希望他选中一个复选框(如果他来自访问挑战区)。如果用户选中“访问挑战区域”复选框,我只想显示他的电子邮件地址,并隐藏他的城市名称和地址。
我在用户模型中添加了一个字段access_challenge = BooleanField(default = False)。
我在注册html模板中创建了一个复选框。
在我的其他html帖子列表中:
{% if user.access_challenge %}
<p> {{ post.email }} </p>
{% else %}
<p> {{ post.country }} </p>
<p> {{ post.city }} </p>
<p> {{ post.address }} </p>
<p> {{ post.email }} </p>
我的models.py
from PIL import Image
from django.db import models
from django.urls import reverse
from django.utils import timezone
from django.db.models.signals import post_save
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
first_name = models.CharField(verbose_name="First name", max_length=255)
last_name = models.CharField(verbose_name="First name", max_length=255)
country = models.CharField(verbose_name="Country name", max_length=255)
city = models.CharField(verbose_name="City name", max_length=255)
email = models.EmailField(verbose_name="Email", max_length=255)
access_challenge = models.BooleanField(default=False)
def __str__(self):
return self.username
class Post(models.Model):
title = models.CharField(max_length=255)
country = models.CharField(max_length=255)
city = models.CharField(max_length=255)
address = models.CharField(max_length=255)
email = models.EmailField(max_length=255)
phone = models.CharField(max_length=255)
website = models.URLField(max_length=255)
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('users:blog')
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
def __str__(self):
return f'{self.user.username} Profile'
def create_profile(sender, **kwargs):
if kwargs['created']:
user_profile = Profile.objects.create(user=kwargs['instance'])
post_save.connect(create_profile, sender=User)
我的views.py
from django.shortcuts import render, redirect
from django.urls import reverse_lazy
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.views.generic import CreateView, DetailView, ListView, UpdateView, DeleteView
from .forms import UserCreationModelForm
from .models import User, Post
class UserRegistrationView(CreateView):
form_class = UserCreationModelForm
success_url = reverse_lazy('login')
template_name = 'users/registration.html'
class PostDetailView(DetailView):
model = Post
class PostCreateView(LoginRequiredMixin, CreateView):
model = Post
fields = ['title', 'country', 'city', 'address', 'email', 'phone', 'website']
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
model = Post
fields = ['title', 'country', 'city', 'address', 'email', 'phone', 'website']
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
def test_func(self):
post = self.get_object()
if self.request.user == post.author:
return True
return False
class PostDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
model = Post
success_url = '/'
def test_func(self):
post = self.get_object()
if self.request.user == post.author:
return True
return False
class CabinetView(LoginRequiredMixin, DetailView):
model = User
def get_object(self):
return self.request.user
def blog(request):
context = {
'posts': Post.objects.filter(author=request.user)
}
return render(request, 'users/post_list.html', context)
def countries(request):
user = User.objects.all().distinct('access_challenge')
country = Post.objects.all().distinct('country')
context = {
'posts': country,
'user': user
}
return render(request, 'users/countries.html', context)
def cities(request, pk):
country = Post.objects.get(id=pk).country
cities = Post.objects.filter(country=country).distinct('city')
context = {
'cities':cities,
'country':country
}
return render(request, 'users/cities.html', context)
def address(request, pk):
city = Post.objects.get(id=pk).city
address = Post.objects.filter(city=city)
context = {
'address': address,
'city': city
}
return render(request, 'users/address.html', context)
def home(request):
return render(request, 'registration/home.html')
我的表格.py
from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django.contrib.auth import get_user_model
from .models import Profile
User = get_user_model()
class UserCreationModelForm(UserCreationForm):
class Meta:
model = User
fields = ['username', 'first_name', 'last_name', 'country', 'city', 'email', 'password1', 'password2', 'access_challenge']
class UserUpdateForm(UserChangeForm):
username = forms.CharField()
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email']
class ProfileUpdateForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['image']
我的urls.py
from django.urls import path
from .views import UserRegistrationView, CabinetView, PostCreateView, PostUpdateView, PostDetailView, PostDeleteView
from . import views
app_name = 'users'
urlpatterns = [
path('accounts/register/', UserRegistrationView.as_view(), name='register'),
path('accounts/cabinet/', CabinetView.as_view(), name='cabinet'),
path('accounts/cabinet/blog/<int:pk>/', PostDetailView.as_view(), name='post-detail'),
path('accounts/cabinet/new/', PostCreateView.as_view(), name='post-create'),
path('accounts/cabinet/blog/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'),
path('accounts/cabinet/blog/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'),
path('', views.home, name='home'),
path('accounts/cabinet/blog/', views.blog, name='blog'),
path('accounts/cabinet/countries/', views.countries, name='countries'),
path('accounts/cabinet/cities/<int:pk>/', views.cities, name='cities'),
path('accounts/cabinet/address/<int:pk>/', views.address, name='address'),
]
我的registration.html
{% extends 'shared/base.html' %}
{% load staticfiles %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section mt-5 pl-5 p-4">
<form method="post">
{% csrf_token %}
<fieldset class="form-group pr-4">
<legend class="mb-4">Join Today</legend>
<div class="form-row">
<div class="form-group col-md-3 mb-0">
{{ form.first_name|as_crispy_field }}
</div>
<div class="form-group col-md-3 mb-0">
{{ form.last_name|as_crispy_field }}
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6 mb-0">
{{ form.username|as_crispy_field }}
<div class="form-row">
<div class="form-group col-md-6 mb-0">
{{ form.country|as_crispy_field }}
</div>
<div class="form-group col-md-6 mb-0">
{{ form.city|as_crispy_field }}
</div>
<div class="form-row">
<div class="form-group col-md-12 mb-0">
{{ form.email|as_crispy_field }}
</div>
<div class="form-row">
<div class="form-group col-md-6 mb-0">
{{ form.password1|as_crispy_field }}
</div>
<div class="form-group col-md-6 mb-0">
{{ form.password2|as_crispy_field }}
</div>
<div class="form-check">
<input type="checkbox" class="form-check-input" id="Checkbox">
<label class="form-check-label" for="Checkbox"> Access Challenge Country</label>
</div>
</fieldset>
<div class="form-group">
<button style="border-radius: 0; width: 200px; padding-left: 4px;" class="btn btn-info btn-block" type="submit">Sign Up</button>
</div>
</form>
<div class="border-top pt-3">
<small class="text-muted">
Already Have An Account? <a class="ml-2" href="{% url 'login' %}">Sign In</a>
</small>
</div>
</div>
{% endblock %}
我的国家/地区