Django - CRUD功能,编辑配置文件详细信息

x8diyxa7  于 2022-12-14  发布在  Go
关注(0)|答案(1)|浏览(132)

我是Django的新手,但我正在创建一个房地产经纪人应用程序,我希望用户能够使用UI中的CRUD功能更新他们的详细信息。
但我的请求无法实现:
下面是我的代码(views.py):

from django.shortcuts import render, redirect
 from django.contrib import messages, auth
 from django.contrib.auth.models import User
 from django.contrib.auth.decorators import login_required
 from contacts.models import Contact

def register(request):
if request.method == 'POST':
    # Get form values
    first_name = request.POST['first_name']
    last_name = request.POST['last_name']
    username = request.POST['username']
    email = request.POST['email']
    password = request.POST['password']
    password2 = request.POST['password2']

    # Check if passwords match
    if password == password2:
        # Check username
        if User.objects.filter(username=username).exists():
            messages.error(request, 'That username is taken')
            return redirect('register')
        else:
            if User.objects.filter(email=email).exists():
                messages.error(request, 'That email is being used')
                return redirect('register')
            else:
                # Looks good
                user = User.objects.create_user(
                    username=username, password=password, email=email, first_name=first_name, last_name=last_name)  # noqa
                # Login after register
                auth.login(request, user)
                messages.success(request, 'You are now logged in')
                return redirect('index')
                # user.save()
                # messages.success(
                #     request, 'You are now registered and can log in')
                # return redirect('login')
    else:
        messages.error(request, 'Passwords do not match')
        return redirect('register')
else:
    return render(request, 'accounts/register.html')

def login(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']

    user = auth.authenticate(username=username, password=password)

    if user is not None:
            auth.login(request, user)
            messages.success(request, 'You are now logged in')
            return redirect('dashboard')
        else:
            messages.error(request, 'Invalid credentials')
            return redirect('login')
    else:
        return render(request, 'accounts/login.html')

def logout(request):
if request.method == 'POST':
    auth.logout(request)
    messages.success(request, 'You are now logged out')
    return redirect('index')

@login_required(login_url='login')
def dashboard(request):
    user_contacts = Contact.objects.order_by(
        '-contact_date').filter(user_id=request.user.id)

context = {
    'contacts': user_contacts
}
return render(request, 'accounts/dashboard.html', context)

下面是(urls.py)

from django.urls import path

from . import views

urlpatterns = [
    path('register', views.register, name='register'),
    path('login', views.login, name='login'),
    path('logout', views.logout, name='logout'),
    path('dashboard', views.dashboard, name='dashboard'),
    path('edit_profile', views.edit_profile, name='edit_profile'),

]
最后,下面是我从html文件中请求的链接中得到的代码片段:

{% extends 'base.html' %}

{% block title %} | Dashboard {% endblock %}
{% block content %}
<section id="showcase-inner" class="py-5 text-white">
    <div class="container">
      <div class="row text-center">
        <div class="col-md-12">
          <h1 class="display-4">User Dashboard</h1>
          <p class="lead">Manage your BT Real Estate account</p>
        </div>
      </div>
    </div>
  </section>


<!-- Breadcrumb -->
  <section id="bc" class="mt-3">
    <div class="container">
      <nav aria-label="breadcrumb">
        <ol class="breadcrumb">
              <li class="breadcrumb-item">
                <a href="{% url 'index' %}">
                  <i class="fas fa-home"></i> Home
                </a>
              </li>
          <li class="breadcrumb-item active"> Dashboard</li>
        </ol>
      </nav>
    </div>
  </section>

      {% comment %} Alerts {% endcomment %}
      {% include 'partials/__alerts.html' %}

      <section id="dashboard" class="py-4">
        <div class="container">
          <div class="row">
            <div class="col-md-12">
              <h2>Welcome {{ user.first_name }} 
            <a class="btn btn-success" href="{% url 'edit_profile' %}">
            Edit Profile
            </a>
          </h2>
            
          </i>
          {% if contacts %}
            <p>Here are the property listings that you have inquired about</p>
            <table class="table">
              <thead>
                <tr>
                  <th scope="col">#</th>
                  <th scope="col">Property</th>
                  <th></th>
                </tr>
              </thead>
              <tbody>
                {% for contact in contacts %}
                  <tr id="listing">
                  <td>{{ contact.id }}</td>
                    <td>{{ contact.listing }}</td>
                    <td>
                      <a class="btn btn-light" href="{% url 'listing' contact.listing_id %}">View Listing</a>
                    </td>
                  </tr>
                {% endfor %}
              </tbody>
            </table>
          {% else %}
          <p>You have not made any inquiries</p>
          {% endif %}
        </div>
      </div>
    </div>
  </section>

请,任何帮助都将不胜感激,也有我包括我所有的文件正确?
非常感谢

yws3nbqq

yws3nbqq1#

要回答您的最新问题,您必须创建一个新视图:

from django.contrib.auth.decorators import login_required

@login_required(login_url='login')
def updateUser(request, pk):
    
    user=User.objects.get(id=pk)
    
    if request.user != user.logged_in:
        return HttpResponse('Your are not allowed here!!')

    if request.method == 'POST':
        ...
        user.name=request.GET['name']
        user.email_address=request.GET['email_address']

        user.save()
        return redirect('home')

    context = {'user':user}
    return render(request, 'user.html', context)

虽然这与你的问题无关,但我建议你使用Django的form内置库。

def registerPage(request):
    form = MyUserCreationForm()

  if request.method == 'POST':
    form = MyUserCreationForm(request.POST)
    if form.is_valid():
        user = form.save(commit=False)
        user.username = user.username.lower()
        user.save()
        login(request, user)
        return redirect('home')

   ....
   return render(...)

创建新文件forms.py,创建新表单:

from django.contrib.auth.forms import UserCreationForm

class MyUserCreationForm(UserCreationForm):
    class Meta:
        model = User
        fields = ['name', 'username', 'email', 'password1', 'password2']

在html模板中:

<form action="/your-name/" method="post">
    <label for="your_name">Your name: </label>
    <input id="your_name" type="text" name="your_name" ">
    ...
    ...
    <input type="submit" value="OK">
</form>

相关问题