0

I tried to search for the username of (default) auth_user table in Django. But I got an error. Can I get/access data from the table as in SQL "SELECT username FROM auth_user"?

(Pdb) n
> /views.py(43)home()
-> if form.is_valid():
(Pdb) n
> /views.py(54)home()
-> errors = form.errors
(Pdb) n
> /views.py(55)home()
-> searched_user = ""
(Pdb) print(errors)
<ul class="errorlist"><li>username<ul class="errorlist"><li>同じユーザー名が既に登録済みです。</li></ul></li></ul>

"同じユーザー名が既に登録済みです" means "same username is already registered".

views.py:

@login_required(login_url='/')
def home(request):
    from myapp.forms import UserSearch
    formset = UserSearch
    if request.method == 'POST':
        form = formset(request.POST)
        if form.is_valid():
            from myapp.models import User
            try:
                username = form.cleaned_data['username']
                searched_user = User.objects.filter(username=username)
            except ObjectDoesNotExist:
                errors = form.errors
                searched_user = ""
            return redirect('/home/')
        else:
            errors = form.errors
            searched_user = ""

forms.py:

from django.contrib.auth.models import User

class UserSearch(forms.ModelForm):  # ModelForm
    class Meta:
        model = User        
        fields = ('username',)
        widgets = {
            'username': forms.TextInput(attrs={'class': 'char', 'placeholder': 'username'}),
        }

python: 3.5.1, Django 1.9.2, python-social-auth: 0.2.14

moopet
  • 6,014
  • 1
  • 29
  • 36
yamachan
  • 1,029
  • 2
  • 12
  • 28
  • 1
    dajngo user will have unique username, you cannot create user with existing username. – navyad Mar 16 '16 at 08:32
  • Thank you for your reply. Ah, really? But if so, I have two questions. One is that I use python-social-auth. If I register users with facebook, I guess some people who have the same name which is registered cannot sigh up. The other is that I just want to check if the username is registered or not, not INSERT INTO the username. Why I got error and cannot check that? – yamachan Mar 16 '16 at 08:48
  • 3
    I guess better would be to get the username from post request data and then check if user exists with given username before creating form instance. – navyad Mar 16 '16 at 08:57
  • #searched_user = User.objects.filter(username=username) Even if I do this, the Error occured. So, when I ask User model through ModelForm, the Error occurs. There might not be solution...I guess. – yamachan Mar 16 '16 at 10:44
  • As you write, I have to check before form instance. But, how can I validate or cleaned_data() the POST? – yamachan Mar 16 '16 at 11:00

0 Answers0