Home > Back-end >  Foreign key is not assigned to a model in database
Foreign key is not assigned to a model in database

Time:06-19

I recently started learning django and was making a CRM.

models.py:

class Complaint(models.Model):

SOURCE_CHOICES=(
    ('email','E-mail'),
    ('call','Call'),
    ('ticket','Ticket')
)

store_name=models.CharField(max_length=20)
store_contact_no=models.IntegerField(max_length=10)
store_id=models.CharField(max_length=7)
source=models.CharField(choices=SOURCE_CHOICES, max_length=10)
agent=models.ForeignKey("Agent", null = True, blank = True, on_delete=models.SET_NULL)
category=models.ForeignKey("Category", related_name="complaints", null = True, blank = True, on_delete=models.SET_NULL)
description = models.TextField()
customer = models.ForeignKey("Customer", null = True, blank = True, on_delete=models.SET_NULL)

def __str__(self):
    return f"{self.store_name} {self.store_id}"


class Customer(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)

def __str__(self):
    return self.user.username

forms.py

class CustomerComplaintForm(forms.ModelForm):
    class Meta:
        model = Complaint
        fields = (
            'store_name',
            'store_id',
            'store_contact_no',
            'description',  
        )

views.py

class 
CustomerComplaintCreateView(OwnerCustomerAndLoginRequiredMixin, 
generic.CreateView):
    template_name = "customercomplaint_create.html"
    form_class = CustomerComplaintForm

    def get_success_url(self):
        return "/complaints"

    def form_valid(self, form):
        complaint = form.save(commit=False)
        complaint.Customer = self.request.user.username
        complaint.source = 'ticket'
        complaint.save()
        return super(CustomerComplaintCreateView, 
    self).form_valid(form)

html template:

{% extends "base.html" %}    
{% load tailwind_filters %}

{% block content %}

<div >
    <a  href="/complaints">Go back to complaints </a>  
    <div >       
    <h1 > Create a new complaint  </h1>  
    </div>
    <form method='post' >  
        {% csrf_token %}
        {{ form|crispy }} 
        <button type="submit" >Create</button>
    </form>
</div>                

{% endblock content %}

mixins.py

class OwnerCustomerAndLoginRequiredMixin(AccessMixin):
"""Verify that the current user is authenticated and is an owner or customer"""

def dispatch(self, request, *args, **kwargs):
    if not request.user.is_authenticated or not request.user.is_owner and not request.user.is_customer:
        return redirect("/complaints")
    return super().dispatch(request, *args, **kwargs)

The problem here is that, the source field gets filled in the database with Ticket as intended. But the 'Customer' field is not populated with the username. 'Self.request.user.username' is not the problem here as the username is being printed correctly in the console.

CodePudding user response:

The issue is complaint.Customer = self.request.user.username, you're trying to assign a username to a supposedly Customer object. Here's an approach you could take to solve the issue though.

Within the views.py file, the view class.

You could get the customer object and then assign it to the customer field on the complaint object.

from django.shortcuts import get_object_or_404

def form_valid(self, form):
    complaint = form.save(commit=False)
    customer = get_object_or_404(Customer, user=self.request.user)  # recommended

    # or 
    # customer = get_object_or_404(Customer, user__username__iexact=self.request.user.username)

    if customer:
         # Here on your model you have a lowercase `c` for the customer field, not 'C`
         complaint.customer = customer  # -> This will assign the customer object, "FK".

    complaint.source = 'ticket'
    complaint.save()
    return super(CustomerComplaintCreateView, self).form_valid(form)

That should work.

CodePudding user response:

this must be the User not the user name Because Cutomer is User object not only the Uesrname

def form_valid(self, form):
        complaint = form.save(commit=False)
        complaint.Customer = self.request.user
        complaint.source = 'ticket'
        complaint.save()
  • Related