user_idの紐づけ方法を教えて下さい
解決したいこと
投稿にuser_idを紐づけたい
例)
djangoで投稿Webアプリをつくっています。
投稿画面を作成時、投稿にユーザーが紐づけられません。
解決方法を教えて下さい。
発生している問題・エラー
postsテーブルのuser_idがnullになっている
例)
id create_at update_at country_id image_id user_id
1 2024-11-19 00:28:20 2024-11-19 00:28:23 1 1 NULL
または、問題・エラーが起きている画像をここにドラッグアンドドロップ
該当するソースコード
accounts/models.py
from django.db import models
from django.contrib.auth.models import (
BaseUserManager, AbstractBaseUser, PermissionsMixin
)
from django.urls import reverse_lazy
class UserManager(BaseUserManager):
def create_superuser(self, username, email, password=None):
if not email:
raise ValueError('Enter Email')
user = self.model(username=username, email=email)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, username, email, password=None):
user = self.model(username=username, email=email)
user.set_password(password)
user.is_staff = True
user.is_active = True
user.is_superuser = True
user.save(using=self._db)
return user
class Users(AbstractBaseUser, PermissionsMixin):
username = models.CharField(max_length=150)
email = models.EmailField(max_length=255, unique=True)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
objects = UserManager()
def get_absolute_url(self):
return reverse_lazy('accounts:user_login')
posts/models.py
from django.db import models
from accounts.models import Users
from django.contrib.auth import get_user_model
class PostCountry(models.Model):
COUNTRY = [
]
country = models.CharField(choices=COUNTRY, max_length=100)
"""
class Meta:
db_table = 'post_country'
def __str__(self):
return self.country
"""
def __str__(self):
return dict(self.COUNTRY).get(self.country,"不明")
class PostPictures(models.Model):
image = models.FileField(upload_to='image/')
def __str__(self):
return self.image.name
class Post(models.Model):
PARKING = [
('1', 'あり(無料)'),
('2', 'あり(有料)'),
('3', 'なし'),
('4', '不明'),
]
BABY = [
('1', 'おむつ台・授乳室あり'),
('2', 'おむつ台あり'),
('3', '授乳室あり'),
('4', 'なし'),
('5', '不明'),
]
user = models.ForeignKey(Users, on_delete=models.CASCADE, null=True)
image = models.ForeignKey(PostPictures, on_delete=models.CASCADE)
spot_name = models.CharField(max_length=50)
country = models.ForeignKey(PostCountry, on_delete=models.CASCADE)
address = models.CharField(max_length=100, null=True,blank=True)
free = models.PositiveIntegerField(null=True,blank=True)
parking = models.CharField(choices=PARKING, max_length=10)
baby_station = models.CharField(choices=BABY, max_length=50)
other = models.TextField(null=True,blank=True)
create_at = models.DateTimeField(null=True)
update_at = models.DateTimeField(null=True)
class Meta:
db_table = 'posts'
def __str__(self):
return self.spot_name
posts/views.py
from django.http import HttpResponse
from django.shortcuts import render
from django.views.generic import ListView, CreateView
from django.urls import reverse_lazy
from .forms import PostForm
from .models import Post
from django.views import View
from django.contrib.auth.mixins import LoginRequiredMixin
import os
class ListView(LoginRequiredMixin, ListView):
template_name = 'list.html'
model = Post
context_object_name = 'posts'
def get_queryset(self):
print(Post.objects.all())
return super().get_queryset()
class PostView(LoginRequiredMixin, CreateView):
template_name = 'post.html'
model = Post
form_class = PostForm
#fields = ('image','spot_name', 'country', 'address', 'free', 'parking', 'baby_station', 'other')
success_url = reverse_lazy('posts:list')
class MyPageView(ListView):
template_name = 'my_page.html'
model = Post
def get_queryset(self):
return Post.objects.filter(user=self.request.user)
class PostSearchView(LoginRequiredMixin, View):
template_name = 'search.html'
model = Post
posts/forms.py
from django import forms
from .models import Post
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ['image','spot_name','country','address','free','parking','baby_station','other']
labels = [
{"spot_name","施設名"},
{"country","区"},
{"address","以下住所"},
{"free","料金"},
{"parking","駐車場"},
{"baby_station","赤ちゃん休憩室"},
{"other","その他"}
]
widgets = {
'country': forms.Select(attrs={'class':'form-control'}),
'image': forms.Select(attrs={'class':'form-control'}),
}
自分で試したこと
posts/models.pyとaccounts/models.py内のUsersを外部キーで紐づけしましたが、user_idと紐づけできません。
0