Django项目管理

时间:2018-08-05 18:20:43

标签: django model project

我当前面临的问题是我想从主应用程序(博客应用程序)中的另一个应用程序(拥有用户模型的帐户应用程序)调用视图。

这是我得到的错误:

django.core.exceptions.FieldError: Unknown field(s) (username) specified for User

urls.py

...
from quickblog import views as core_views
from accounts import views as views_accounts

...
url(r'^myaccount/$', views_accounts.view_profile, name='myaccount'),

views.py(帐户应用):

from django.shortcuts import render, redirect
from django.urls import reverse

from accounts.forms import (
    RegistrationForm,
    EditProfileForm
)

from django.contrib.auth.models import User
from django.contrib.auth.forms import PasswordChangeForm
from django.contrib.auth import update_session_auth_hash


def register(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect(reverse('accounts:home'))
    else:
        form = RegistrationForm()

        args = {'form': form}
        return render(request, 'reg_form.html', args)


def view_profile(request, pk=None):
    if pk:
        user = User.objects.get(pk=pk)
    else:
        user = request.user
    args = {'user': user}
    return render(request, 'profile.html', args)


def edit_profile(request):
    if request.method == 'POST':
        form = EditProfileForm(request.POST, instance=request.user)

        if form.is_valid():
            form.save()
            return redirect(reverse('accounts:view_profile'))
    else:
        form = EditProfileForm(instance=request.user)
        args = {'form': form}
        return render(request, 'edit_profile.html', args)


def change_password(request):
    if request.method == 'POST':
        form = PasswordChangeForm(data=request.POST, user=request.user)

        if form.is_valid():
            form.save()
            update_session_auth_hash(request, form.user)
            return redirect(reverse('accounts:view_profile'))
        else:
            return redirect(reverse('accounts:change_password'))
    else:
        form = PasswordChangeForm(user=request.user)

        args = {'form': form}
        return render(request, 'change_password.html', args)

profile.html:

{% extends 'quickblog/base.html' %}


{% block head %}
<title>Profile</title>
{% endblock %}

{% block body %}
<div class="container">
    <h1>Profile</h1>
    <p>Username: {{ user }}</p>
    <p>Bio: {{ user.bio }}</p>
    <p>Avatar: {{ user.avatar }}</p>
    {% if user.avatar.image %}
    <img src="{{ user.avatar.image.url }}" width="250">
    {% endif %}
</div>

{% endblock %}

这是我的第一个django应用程序,关于在一个项目中链接两个应用程序,我可能需要了解什么吗?

谢谢

1 个答案:

答案 0 :(得分:0)

在forms.py处发现错误

class RegistrationForm(UserCreationForm):
    user = forms.CharField(required=True)
class Meta:
    model = User
    fields = (
        'username', < has to be user
        'password1',
        'password2',
    )

无论如何,谢谢大家:)