Django - OneToOneField продолжает возвращать None - PullRequest
0 голосов
/ 07 мая 2020

My OneToOneField продолжает возвращать None. Я пытаюсь зайти на свой сайт go, чтобы в форме можно было автоматически указать автора сообщения в качестве текущего пользователя, вошедшего в систему. Я огляделся и увидел, что OneToOneField может это сделать. Он продолжает возвращать None, когда у меня действительно есть пользователи в модели User. Что на Земле происходит?

Models.py: - Здесь происходит основная проблема

from django.db import models
from datetime import datetime
from django import forms
from django.forms import ModelForm
from django.contrib.auth.models import User
from django.conf import settings
from django.contrib.auth import get_user_model



class MainPost(models.Model):
    post_author = models.OneToOneField(User, on_delete=models.CASCADE)
    post_title = models.CharField(max_length=200)
    post_content = models.TextField()
    post_published = models.DateTimeField("date published", default=datetime.now())



    def __str__(self):
        return self.post_title

class MainPostForm(ModelForm):
    class Meta:
        model = MainPost
        fields = ["post_title", "post_content", "post_author"]
        readonly_fields = "post_published"

Views.py - Важная вещь - create_request () внизу

from django.shortcuts import render, redirect
from django.shortcuts import render, redirect
from django import forms
from django.http import HttpResponse
from django.views.generic import CreateView
from django.contrib.auth.forms import AuthenticationForm
from .models import MainPost, MainPostForm
from .forms import NewUserForm

from django.contrib import messages
from django.contrib.auth import login, logout, authenticate
from django.contrib.auth.models import User
from datetime import datetime

def homepage(request):
    return render(request, template_name="trymysite/home.html", context=             
    {"posts":MainPost.objects.order_by('-post_published')})

def register(request):
    if request.method == "POST":
        form = NewUserForm(request.POST)
        if form.is_valid():
            user = form.save()
            username = form.cleaned_data.get("username")
            messages.success(request, f"New Account Created: {username}")
            login(request, user)
            messages.info(request, f"You are now logged in as {username}")
            return redirect("mymainapp:homepage")  # Goes to urls and to the homepage path

        else:
            for msg in form.error_messages:
                messages.error(request, f"{msg}: {form.error_messages[msg]}")

    form = NewUserForm
    return render(request, "trymysite/register.html", context={"form": form})


def login_request(request):
    if request.method == "POST":
        form = AuthenticationForm(request, data=request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            user = authenticate(username=username, password=password)
            if user is not None:
                login(request, user)
                messages.info(request, f"You are now logged in as {username}")
                return redirect("mymainapp:homepage")
            else:
                messages.error(request, "Invalid username or passowrd!")
        else:
            messages.error(request, "Invalid username or passowrd!")

    form = AuthenticationForm()
    return render(request, "trymysite/login.html", {"form":form})

def logout_request(request):
    logout(request)
    messages.info(request, "Logged out Successfully!")
    return redirect("mymainapp:homepage")

def create_request(request):
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = MainPostForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            form.save()
            return redirect("mymainapp:homepage")

    form = MainPostForm()

 return render(request, "trymysite/create.html", {"form":form})from django import forms

Forms.py - это часть регистрации пользователя на случай, если это проблема.

from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User



class NewUserForm(UserCreationForm):
    email = forms.EmailField(required=True)

    class Meta:
        model = User
        fields = ("username", "email", "password1", "password2")

    def save(self, commit=True):
        user = super(NewUserForm, self).save(commit=False)
        user.email = self.cleaned_data["email"]
        if commit:
            user.save()
        return user

Пожалуйста, помогите

1 Ответ

0 голосов
/ 07 мая 2020

Попробуйте это:

def create_request(request):
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = MainPostForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            main_post = form.save(commit=False)
            main_post.post_author = request.user
            main_post.save()
            return redirect("mymainapp:homepage")

    form = MainPostForm()
    return render(request, "trymysite/create.html", {"form":form})
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...