Django:根据用户是否创建了用户个人资料显示不同的导航栏选项?

时间:2018-09-25 08:06:39

标签: django python-3.x

我有一个问题,即如果用户未创建用户个人资料,如何显示导航栏的不同选项。我尝试了许多选项,包括在base.html上使用{%ifprofiles_list%}以及{%ifequal user userprofiles.objects.all%}以及在templatetags上创建一个简单标签,但是它似乎不起作用。

我也尝试过更改视图,但是由于我是编码的新手,所以我更喜欢使用“ base.html”。但是,任何建议都会受到欢迎。我希望选项以某种方式显示,如果用户尚未创建个人资料,则只会显示搜索,消息,关于我们以及创建新个人资料的选项。并且,如果他们已经创建了配置文件,则创建新的配置文件将被编辑配置文件替换,并且还将显示“删除配置文件”和“查看配置文件”的其他选项。

我的代码如下:

   base.html

<div class="container">
  <nav class="navbar navbar-expand-lg navbar-light bg-light">
    <a class="navbar-brand" href="{% url 'home:index' %}">  <img src="{% static "images/rainbow.jpg" %}" width="100" height="100" alt=""></a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarNav">
      <ul class="navbar-nav">
        {% if user.is_authenticated %}
        <li class="nav-item active">
          <a class="nav-link" href="{% url 'home:about' %}">About Us <span class="sr-only">(current)</span></a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="{% url 'userprofile:editprofile' user.pk %}">Edit Profile</a>
          <li class="nav-item">
            <a class="nav-link" href="{% url 'userprofile:profileview' user %}">View Profile</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="{% url 'userprofile:deleteprofile' user %}">Delete Profile</a>
  </li>
          <li class="nav-item">
            <a class="nav-link" href="{% url 'userprofile:newprofile' %}">Create New Profile</a>



        <li class="nav-item">
          <a class="nav-link" href="{% url 'userprofile:profilesearch' %}">Search</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Messages</a>
        </li>
        <li class="nav-item">
            <!-- login/logout dont need namespace app -->
          <a class="nav-link" href="{% url 'logout' %}">Logout</a>
        </li>
            {% else %}
        <li class="nav-item active">
          <a class="nav-link" href="{% url 'home:about' %}">About Us <span class="sr-only">(current)</span></a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="{% url 'home:signup' %}">Sign Up</a>
        </li>
        <li class="nav-item">
          <!-- login/logout dont need namespace app -->
          <a class="nav-link" href="{% url 'login' %}">Login</a>
        <li>
          {% endif %}
      </ul>
    </div>
  </nav>


  </div>

  {% block content %}
      {% endblock %}

views.py

class NewUserProfileView(FormView,LoginRequiredMixin):
    template_name = "userprofile/user_profile.html"
    form_class = UserProfileForm

    def form_valid(self, form):
        try:
            form.save(self.request.user)
            return super(NewUserProfileView, self).form_valid(form)
        except IntegrityError:
            return HttpResponse("You have already created a profile, please click back and click on My Profile.")

    def get_success_url(self, *args, **kwargs):
        return reverse("home:index")


class EditUserProfileView(UpdateView, LoginRequiredMixin):

    model = UserProfiles
    form_class = UserProfileForm
    template_name = "userprofile/user_profile.html"
    slug_field = 'slug'

    def get_object(self, *args, **kwargs):

        user = get_object_or_404(User, pk=self.kwargs['pk'])
        return user.userprofiles

    def form_valid(self, form):
        print(form.cleaned_data)
        return super().form_valid(form)

    def get_success_url(self, *args, **kwargs):
         return reverse('home:index')


@login_required
def profiles_list(request):
    filter = UserProfilesFilter(request.GET, queryset = UserProfiles.objects.all())
    return render(request,"userprofile/user_list.html", {'filter': filter})

@login_required
def profile_details(request,slug):
    profile = get_object_or_404(UserProfiles, slug=slug)
    return render(request, 'userprofile/profile_detail.html', {'profile': profile})

class UserProfileDelete(DeleteView, LoginRequiredMixin):
    model = UserProfiles
    success_url = reverse_lazy('home:index')
    template_name = "userprofile/profile_delete.html"

     # override the delete function to check for a user match
    def delete(self, request, *args, **kwargs):
        # the Post object
        self.object = self.get_object()
        if self.object.user == request.user:
            success_url = self.get_success_url()
            self.object.delete()
            return HttpResponseRedirect(success_url)
        else:
            return HttpResponse("Cannot delete other's profiles")

models.py

class UserProfiles(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    slug = models.SlugField(unique=True, null=True)
    gender = models.CharField(choices=GENDER_CHOICES, max_length=50)
    age= models.IntegerField()
    Nationality= models.CharField(max_length=100, null=True, blank=True, verbose_name = 'Ethnicity:', choices = ETHNIC_CHOICES)
    image= models.ImageField(upload_to = 'pic_folder/', null=True, blank=False, verbose_name="your profile photo (required):")
    height= models.IntegerField(blank=True, null=True, verbose_name = "your height in cms:")
    weight= models.IntegerField(blank=True, null=True, verbose_name = 'Your weight in kgs:')
    description= models.TextField(max_length=500, verbose_name = 'Introduce yourself:')
    lookingfor= models.TextField(max_length=500, verbose_name= 'Your ideal soulmate:')
    preference = models.CharField(max_length=300, choices=LOOKING_CHOICES, verbose_name= "Preference:", null=True)
    Country = CountryField()
    City = models.CharField(verbose_name= 'city', max_length=120, null=True, blank = True)
    hobbies= models.CharField(max_length=200, null=True, blank=True)
    profession= models.CharField(max_length=200, null=True, blank=True)

    def __str__(self):
        return str(self.user)

    def summary(self):
        return self.description[:150]

    def save(self, *args, **kwargs):
        self.slug = slugify(self.user)
        super(UserProfiles, self).save(*args, **kwargs)

urls.py(对于应用程序)

urlpatterns = [

path('new/', views.NewUserProfileView.as_view(), name = 'newprofile'),
path('users/<int:pk>/edit/', views.EditUserProfileView.as_view(), name="editprofile"),
path('search/', views.profiles_list, name="profilesearch"),
re_path(r'^(?P<slug>[\w-]+)/$', views.profile_details, name="profileview"),
re_path(r'^del/(?P<slug>\w+)/$', views.UserProfileDelete.as_view(), name="deleteprofile"),

] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

1 个答案:

答案 0 :(得分:0)

User和UserProfiles之间的关系是一对一的,因此没有all(无论如何,检查列表是否等于用户是没有意义的)。您应该只检查user.userprofiles

{% if user.userprofiles %}
  ... show edit links ...
{% else %}
  ... show create links ...
{% endif %}

注意,Django风格是对模型类使用单数名称:它应该是UserProfile。无论如何,这更有意义,因为这样的关系就是user.userprofile