Such a problem: there is an application for viewing and creating news entries. There is a need to save in the database the username of the author (ie, authorized user). Using this material I connected the User model to my news model.

The problem is that django does not automatically enter the name of an authorized user, but offers the author a choice of any name that exists in User:

enter image description here

models.py:

from django.db import models from django.utils import timezone from django.contrib.auth.models import User class NewsContent(models.Model): title = models.CharField(max_length = 130) post = models.TextField() date = models.DateTimeField(default=timezone.now) autor = models.ForeignKey( 'auth.User',on_delete=models.CASCADE, null=True) def __str__(self): return self.title 

I understand why this does not work correctly, but I do not have enough knowledge and experience to solve the problem. Thank you in advance.

  • should be select? or you can just display the username of the user in the template? - m0nte-cr1st0

1 answer 1

If you want the author field to be automatically set for the current user when creating an object from the admin area, register NewsContent as admin.py as follows:

 @admin.register(NewsContent) class NewsContentAdmin(admin.ModelAdmin): exclude = ('author',) # скрыть author поле, чтобы оно не отображалось в форме изменений def save_model(self, request, obj, form, change): if not obj.pk: obj.author = request.user super().save_model(request, obj, form, change) 

When creating an application on a page, we similarly remove the author field for the form:

 class NewsContentForm(forms.ModelForm): class Meta: model = NewsContent exclude = ["date", "author"] 

In the view after verifying the form, initialize the author attribute with the value request.user and save the object:

 @login_required def makePost(request): form = NewsContentForm(request.POST or None) if request.method == "POST": if form.is_valid(): new_post = form.save(commit=False) new_post.author = request.user new_post.save() return redirect('/news/') return render(request, 'news/makePost.html', locals()) 
  • No, I need the author to automatically install when creating not from the admin panel, but from the page I created (uploaded a new screen) - Machalka
  • Show how the view looks for this page. - avtomato
  • from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from .forms import NewsContentForm # Create your views here. def news (request): return render (request, 'news / news.html') @login_required def makePost (request): form = NewsContentForm (request.POST or None) if request.method == "POST": new_post = form .save () print (form.cleaned_data.get ('username')) return redirect ('/ news /') return render (request, 'news / makePost.html', locals ()) - Machalka
  • Then too, the form. - avtomato
  • from django import forms from .models import NewsContent class NewsContentForm (forms.ModelForm): class Meta: model = NewsContent exclude = ["date"] - Machalka pm