PolarBear10
PolarBear10

Reputation: 2305

Assign selected user to object Django

The following code assigns the logged in user to the object, how can I change it to assign the selected user from the dropdown menu to the object?

<form method='POST' action="{% url 'post:car' post.id %}">
    {% csrf_token %}
    <label for="select1"></label>
    <select class="mdb-select md-form" id="select1" onChange="form.submit();">
        <option value="" disabled selected>Assign</option>
        {% for user in current_users %}
            <option value="{{ user.id }}"> {{ user }} </option>
        {% endfor %}
    </select>

</form>

The goal from the above is to assign the selected {{user.id}} to the {{post.id}}

The urls.py is

path('post/<int:tag>', views.assigned_post, name='car'),

The current_users has been achieved by injection from the views.py using context['current_users'] = ProjectUser.objects.all()

The views.py is

def assigned_post(request, tag):
    as_curr = get_object_or_404(Post, id=tag)

    if request.method == 'POST':
        if as_curr.assigned_to:
            as_curr.assigned_to = None
            as_curr.save()

        else:
            as_curr.assigned_to = request.user # < -- Assign to drop down user instead of current user
            as_curr.save()

    return HttpResponseRedirect(reverse('post:tasks'))

The models.py is

class Post(models.Model):
      assigned_to = models.ForeignKey(ProjectUser, related_name="assigned_user", blank=True, null=True,
                                    on_delete=models.CASCADE)

What I tried:

as_curr.assigned_to = request.POST.get('user_id')

But the views is returning None on the request.POST.get('user_id')

Upvotes: 0

Views: 86

Answers (2)

user9727749
user9727749

Reputation:

Because your model specifies assigned_to as a ForeignKey to ProjectUser, that means you must populate it with a ProjectUser instance, hence the error. So maybe try fetching the ProjectUser before you save it:

# views.py 

user = ProjectUser.objects.get(id=request.POST.get('user_id'))
as_curr.assigned_to = user
as_curr.save()

Upvotes: 2

Tommaso Barbugli
Tommaso Barbugli

Reputation: 12031

You need to give the input form element the correct name in order to get it from the request.POST (eg. name="user_id")

<select name="user_id" class="mdb-select md-form" id="select1" onChange="form.submit();">

Upvotes: 0

Related Questions