简体   繁体   中英

I need save info + User.id or username to database in Django

I have some problem with save info about authentificate user with info. I didnt have some id but django have exception. My model.py

from django.contrib.auth.models import User
from django.db import models
from hashlib import md5
from django.conf import settings


# Create your models here.
class Url(models.Model):
    long_url = models.CharField(unique=True,max_length=500)
    short_url = models.CharField(unique=True, max_length=100)
    user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
    id = models.BigAutoField(primary_key=False, null=True)

    @classmethod
    def create(self, long_url, user, id):
        tmp = md5(long_url.encode()).hexdigest()[:6]
        tmp = '127.0.0.1:8000' + '/' + tmp

        try:
            obj = self.objects.create(id=id,long_url=long_url, short_url=tmp, user=user)
        except:
            obj = self.objects.get(long_url=long_url, user=user)
        return obj

My views.py

from django.contrib.auth.models import User
from django.shortcuts import render, redirect
from .forms import  UserRegistration, UserLogIn
from .models import Url
from django.http import HttpResponse
from django.contrib.auth import authenticate, login

# Create your views here.

def register(request):
    if request.method == 'POST':
        user_form = UserRegistration(request.POST)
        if user_form.is_valid():
            new_user = user_form.save(commit=False)
            new_user.set_password(user_form.cleaned_data['password'])
            new_user.save()
            return render(request, 'register.html', {'new_user': new_user})
    else:
        user_form = UserRegistration()
    return render(request, 'register.html', {'user_form': user_form})

def shorter(request):
    if request.method == 'POST':
        long_url = request.POST.get('long_url')
        obj = Url.create(long_url, User)
        return render(request, 'short.html', {
            'short_url': request.get_host() + '/' + obj.short_url[-6:]})
    return render(request, 'shorter.html')

My forms.py

    from django.contrib.auth.models import User
from django import forms


class UserRegistration(forms.ModelForm):
    password = forms.CharField(label='Password', widget=forms.PasswordInput)
    password2 = forms.CharField(label='Repeat password', widget=forms.PasswordInput)

    class Meta:
        model = User
        fields = ('username', 'first_name', 'email')

    def clean_password2(self):
        cd = self.cleaned_data
        if cd['password'] != cd['password2']:
            raise forms.ValidationError('Passwords don\'t match.')
        return cd['password2']

class UserLogIn(forms.Form):
    username = forms.CharField()
    password = forms.CharField(widget=forms.PasswordInput)

When I want to save i have exception Field 'id' expected a number but got <class 'django.contrib.auth.models.User'>. Can you help me with this exception.But I'm begginer from Django and this case i think so simple but doesn't work.

In shorter function in views.py change

obj = Url.create(long_url, User)

to

obj = Url.create(long_url, request.user)

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