Home > OS >  How set username to ForeignKey
How set username to ForeignKey

Time:04-08

I want to set value, but i don't know how do it. Error:

RelatedObjectDoesNotExist at /comments/ commentsTabl has no avtor. Request Method: GET Request URL: http://localhost:8000/comments/ Django Version: 4.0.2 Exception Type: RelatedObjectDoesNotExist Exception Value:
commentsTabl has no avtor. Exception Location: D:\python39\lib\site-packages\django\db\models\fields\related_descriptors.py, line 197, in get Python Executable: D:\python39\python.exe Python Version: 3.9.6 Python Path:
['D:\Django\ForumXT\first', 'D:\python39\python39.zip', 'D:\python39\DLLs', 'D:\python39\lib', 'D:\python39', 'D:\python39\lib\site-packages'] Server time: Thu, 07 Apr 2022 12:20:35 0000

models.py

class commentsTabl(models.Model):
    Text = models.TextField(verbose_name='Text')
    date = models.DateTimeField(default=timezone.now, verbose_name='date')
    avtor = models.ForeignKey(User, verbose_name='avtor', on_delete=models.CASCADE, to_field="username")

     def __str__(self):
         return f'Comment {self.avtor} at {self.date}'

     class Meta:
         verbose_name = "Comment"
         verbose_name_plural = "Comments"

views.py

def comments(request):
     data = {
         'com': reversed(commentsTabl.objects.all())
     }
     if request.method =="POST":
         form = commentsTabl(request.POST)
         if form.is_valid():
             form.save()
     else:
         form = commentsTabl()
     return render(request, 'home/comments.html', data, {'form':form})

CodePudding user response:

In models.py

class Comment(models.Model):
    Text = models.TextField(verbose_name='Text')
    date = models.DateTimeField(auto_add_now=True, verbose_name='date')
    avtor = models.ForeignKey(User, verbose_name='avtor', on_delete=models.CASCADE)

    def __str__(self):
        return 'Comment {} at {}'.format(self.avtor, self.date)

    class Meta:
        # Order comments in reverse order
        # ordering = ["-id"]

In views.py

from .forms import CommentForm
from .models import Comments
from django.http import HttpResponseRedirect
from django.urls import reverse


def comments(request):
    # Retrive all comments from database
    comments = Comment.objects.all()
    # Reverse ...
    comments = reversed(comments)

    # Form with no data (unbound form)
    form = CustomerForm()
    context = {"comments": comments, "form": form}
    # when method is post
    if request.method == "POST":
        form = CommentForm(request.POST)
        if form.is_valid():
            # Don't save the form to database
            comment = form.save(commit=False)
            # Add user to the comment
            comment.avtor = request.user
            # Save comment to database
            comment.save() 
            return HttpResponseRedirect(reverse('some url name'))
        
        # when form is invalid
        else:
            # Re-render the form with errors and data
            context["form"] = form
            return render(request, "home/comments.html", context)

    # when method is not post
    else:
        return render(request, "home/comments.html", context)

In forms.py

from django.forms import ModelForm
from .models import Comment

# Create your forms here
class CommentForm(ModelForm):
    class Meta:
        model = Comment
        fields = ("Text", "date",)
        # or
        # exclude = ("avtor",)
        # fields = "__all__"

Important

  1. python manage.py makemigrations
  2. python manage.py migrate
  3. In comments.html you will have access to form and comments
  • Related