简体   繁体   中英

Django - Many to Many Model Returning None

Long time listener, first time poster. Hoping to get some help with my models issue.

I'm having trouble with my many to many relationship. When I submit a form, I want to have my user's info associated with the post that they create. I'm using a many to many because I will have an additional feature where other users can join in on that same trip.

Currently my data for my Trip tables creates fine, but my user isn't being linked to the Trip id so I can't render out their name on the template.

Below is my code. Appreciate any help! Cheers

Here are my models.py:

class User(models.Model):
    name = models.CharField(max_length=45)
    username = models.CharField(max_length=255)
    password = models.CharField(max_length=255)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    objects = UserManager()

class Trip(models.Model):
    destination = models.CharField(max_length=45)
    description = models.CharField(max_length=255)
    datefrom = models.CharField(max_length=255)
    dateend = models.CharField(max_length=255)
    user = models.ManyToManyField(User)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

Here is my views.py:

def travels(request):
    user = User.objects.get(id=request.session['logged_user'])
    all_trips = Trip.objects.all().order_by('-id')
    user_trips = Trip.objects.filter(user=request.session['logged_user'])
    context = {
        "user_trips": user_trips,
        "all_trips": all_trips,
        "user": user,
    }
    return render(request, 'belt_exam/travels.html', context)

def addtrip(request):
    user_id = request.session['logged_user']
    createdtrip = Trip.objects.create(destination=request.POST['destination'], description=request.POST['description'], datefrom=request.POST['datefrom'], dateend=request.POST['dateend'])
    createdtrip.user.add(User.objects.get(id=user_id))    
    return redirect('/travels')

Here's my template:

{% for alltrip in all_trips.all %}
    <tr>
        <td>{{alltrip.name}}</td>
        <td><a href="travels/destination/{{alltrip.id}}">{{alltrip.destination}}</a></td>
        <td>{{alltrip.datefrom}}</td>
        <td>{{alltrip.dateend}}</td>
        <td>
        <form class="" action="travels/destination/{{alltrip.id}}" method="POST">
        {% csrf_token %}
        <input type="submit" value="Join">
        </form>
        </td>
    </tr>
{% endfor %}

In the line

user_trips = Trip.objects.filter(user=request.session['logged_user'])

you are comparing the user id from the session with the User object. That will not work. Correct would be

user_trips = Trip.objects.filter(user=user)

But there is a better way to get the user trips. To every relation Django create a reverse relation. The name can be set as the related name attribute of the ManyToManyField

user = models.ManyToManyField(User, related_name='trips')

Now you can just use that attribute on the target model as an object manager (like objects )

user_trips = user.trips.all()

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