Question

For my Django custom user model, I have a license_key field. On the admin interface, for ease of usability, I am trying to create a button, which generates a new license_key for the user you are currently looking at. Here is me overriding the change_form.html, like suggested in the Django docs.

/main/templates/admin/main/MyUser/change_form.html:

{% extends "admin/change_form.html" %}
{% load i18n admin_urls %}

{% block form_top %}

    <form class="form-horizontal" method="POST" action="/auth/gen_new_aero_license/">
        {% csrf_token %}

        <div class="control-group">
            <div class="controls controls-row">
                <button type="submit" class="btn btn-primary">
                    Generate new license
                </button>
            </div>
        </div>
    </form>
{% endblock %}

This form calls a function I have defined in my main views file...

main/views.py:

def auth_gen_new_aero_license(request):
    u = MyUser.objects.get(username=request.user.username)
    u.license_key = 'XXX'
    u.save()
    return redirect('/')

And here's my urls.py definition for this new function, because it may help:

url(r'^auth/gen_new_aero_license/$', 'main.views.auth_gen_new_aero_license', name='auth_gen_new_aero_license'),

I am not even calling the script to generate a new dynamic license_key within views.py. I am just setting it to some random value for testing purposes.

So here's the problem: when I click the button, it just refreshes the current user I am on and all the values have been deleted, thus giving me errors. It is as if it tried to delete all the fields and then save that user, which is now an invalid user.

I tried debugging, and it seems as though it is never even going into the function in my views.py file. I also updated my urls.py, so the function in my views.py should be valid.

Is what I am trying to do even possible? Or is there a better way? Or what may be going wrong.

If you need more clarification, please ask!

Thanks

Edit: Also, now none of the built in admin buttons work on the user page, i.e. - Save, Save and add another, Save and continue editing...

Était-ce utile?

La solution

A form isn't necessary for what you are trying to accomplish. You can replace the form with:

<a href="{% url "auth_gen_new_aero_license" %}" class="btn btn-primary">Generate new licence</a>

Autres conseils

Have you tried u = MyUser.objects.get(username__iexact=request.user) instead?

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top