简体   繁体   中英

How do I set my foreign key to the current user in my views

I am developing an app that needs users to login and create posts. The post model has an image and a caption (the user inputs) and a profile foreign key that should to automatically pick the logged in users profile. The app however isnt autopicking the profile

Can someone spot what am doing wrong? I feel like the particular issue is in this line of code in my views

form.instance.profile = self.request.Image.profile

models

from django.db import models
from django.contrib.auth.models import User
import PIL.Image
from django.urls import reverse

# Create your models here.
class Image(models.Model):

    image = models.ImageField(upload_to='images/')
    caption = models.TextField()
    profile = models.ForeignKey('Profile', default='1', on_delete=models.CASCADE)
    likes = models.ManyToManyField(User, blank=True)
    created_on = models.DateTimeField(auto_now_add=True)

    def get_absolute_url(self):
    return reverse('vinsta-home')

class Profile(models.Model):

    user = models.OneToOneField(User, on_delete=models.CASCADE)
    photo = models.ImageField(upload_to = 'photos/',default='default.jpg')
    bio = models.TextField(max_length=500, blank=True, default=f'I love vinstagram!')   

    def __str__(self):
    return f'{self.user.username}' 

views

from django.shortcuts import render
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.views.generic import (ListView,CreateView,)
from .models import Image


def home(request):
    context = {
    'posts': Image.objects.all()
    }
    return render(request, 'vinsta/home.html', context)

class ImageListView(ListView):
    model = Image
    template_name = 'vinsta/home.html'  # <app>/<model>_<viewtype>.html
    context_object_name = 'posts'
    ordering = ['-created_on']    

class ImageCreateView(LoginRequiredMixin, CreateView):
    model = Image
    fields = ['image', 'caption']

    def form_valid(self, form):
    
        form.instance.profile = self.request.Image.profile
        return super().form_valid(form)    

I think you're just about right as to which line isn't working. Instead of

form.instance.profile = self.request.Image.profile

try

form.instance.profile = Profile.objects.get(user=self.request.user)

(Don't forget to add the import for your Profile model.) I don't think Image exists as a property of request , but user does.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM