I have searched for answers to this problem and there are many for how to get the id of the logged in user, all that is need in the template is {{ user.id}}. I have an author name for a post in a forum, {{ item.author }}. This author is not the logged in user. Is it possible to get that author's id without having to do a query in the view?
I did try using a foreign key to relate the topicmodel and the user model but this is giving me problems with a form I have in which a topic and a post are saved together. I am not created the instance cotrrectly. Here is the view that I can't get to work,
def topic_form(request):
if request.method == "POST":
userInstance = get_object_or_404(User, username = request.user)
Tform = TopicForm(request.POST)
Pform = PostForm(request.POST, instance=userInstance)
if Tform.is_valid() and Pform.is_valid():
tform = Tform.save(commit=False)
tform.topicAuthor = request.user
tform.author = userInst #this needs to be a user instance
tform.save() #returns request and id
pform = Pform.save(commit=False)
pform.topic = tform
pform.author = request.user
pform.pub_date = timezone.now()
pform.save()
return redirect('init')
else:
topicform = TopicForm()
postform = PostForm()
return render(request, 'new_topic.html', {'topicform': topicform, 'postform': postform})
These are the models
class TopicModel(models.Model):
topic = models.CharField(max_length = 100)
topicAuthor = models.CharField(max_length = 100)
author = models.ForeignKey(User, related_name = 'id_of_author')
views = models.PositiveIntegerField(default = 0)
def __str__(self): # __unicode__ on Python 2
return self.topic
class PostModel(models.Model):
post = HTMLField(blank = True, max_length = 1000)
pub_date = models.DateTimeField('date published')
author = models.CharField(max_length = 30)
topic = models.ForeignKey(TopicModel, related_name = 'posts')
def __str__(self): # __unicode__ on Python 2
return self.post
我假设作者与用户有关系。
{{item.author.user.id}}
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.