ValueError:字段“ length”应为数字,但得到了“

时间:2020-10-04 10:22:55

标签: python django

models

from django.db import models
from django.contrib.auth.models import User
from django.utils.timezone import now
from django.contrib.auth.models import User

# Create your models here.

class Allmusic(models.Model):
    sno=models.AutoField(primary_key=True)
    name=models.CharField(max_length=100,default="")
    author=models.CharField(max_length=100,default="")
    description=models.TextField(default="")
    movie=models.CharField(max_length=100,default="")
    category=models.CharField(max_length=100,default="")
    subcategory=models.CharField(max_length=100,default="")
    image=models.ImageField(upload_to='images', default="")
    musicfile=models.FileField(upload_to='music_file', default="")

    def __str__(self):
        return self.name  

class Watchlater(models.Model):
    watch_id=models.AutoField(primary_key=True)
    user=models.ForeignKey(User,on_delete=models.CASCADE)
    video_id=models.CharField(max_length=100000,default="")
    

class BlogComment(models.Model):
    sno=models.AutoField(primary_key=True)
    comment=models.TextField()
    user=models.ForeignKey(User,on_delete=models.CASCADE)
    post=models.ForeignKey(Allmusic,on_delete=models.CASCADE)
    timestamp=models.DateTimeField(default=now)


class History(models.Model):
    history_id=models.AutoField(primary_key=True)
    user=models.ForeignKey(User,on_delete=models.CASCADE)
    music_id=models.CharField(max_length=100000,default="")
    

views.py

from django.shortcuts import render,HttpResponse,redirect
from .models import Allmusic,Watchlater,BlogComment,History
from math import ceil
from django.contrib.auth.models import User
from django.contrib.auth import login,authenticate,logout
from django.contrib import messages
from django.db.models import Case,When

# Create your views here.

def home(request):  
    return render(request,'home.html')

def index(request):
    allProds = []
    catprods = Allmusic.objects.values('category', 'sno')
    cats = {item['category'] for item in catprods}
    for cat in cats:
        prod = Allmusic.objects.filter(category=cat)
        n = len(prod)
        nSlides = n // 4 + ceil((n / 4) - (n // 4))
        allProds.append([prod, range(1, nSlides), nSlides])
    params = {'allProds':allProds}
    return render(request,'index.html',params)

def indexmovie(request):
    allProds = []
    catprods = Allmusic.objects.values('movie', 'sno')
    cats = {item['movie'] for item in catprods}
    for cat in cats:
        prod = Allmusic.objects.filter(movie=cat)
        n = len(prod)
        nSlides = n // 4 + ceil((n / 4) - (n // 4))
        allProds.append([prod, range(1, nSlides), nSlides])
    params = {'allProds':allProds}
    return render(request,'indexmovie.html',params)
    
def about(request):
    return render(request,'about.html')

def contact(request):
    return render(request,'contact.html')

#Authenciation APIs
def handleSignup(request):
     if request.method=='POST':
          #Get the post parameters
          username=request.POST['username']
          fname=request.POST['fname']
          lname=request.POST['lname']
          email=request.POST['email']
          pass1=request.POST['pass1']
          pass2=request.POST['pass2']

          #checks for errorneous input
          #username should be <10
          # username shouldbe alphanumeric

          if len(username)>10:
                messages.error(request,"username must be less than 10 characters")
                return redirect('/')
          if not username.isalnum():
                messages.error(request,"username should only contain letters and numbers")
                return redirect('/')
          if pass1!=pass2:
               messages.error(request,"Password do not match")
               return redirect('/')

          #Create the user
          myuser=User.objects.create_user(username,email,pass1)
          myuser.first_name=fname
          myuser.last_name=lname
          myuser.save()

          messages.success(request,"your Musify account has been created succesfully Now go enter your credentials into the login form")
          return redirect('/')

     else:
          return HttpResponse('404 - Not Found')

def handleLogin(request):
     if request.method=='POST':

          #Get the post parameters
          loginusername=request.POST['loginusername']
          loginpassword=request.POST['loginpassword']

          user=authenticate(username=loginusername,password=loginpassword)

          if user is not None:
               login(request,user)
               messages.success(request,"succesfully Logged In")
               return redirect('/')              
          else:
               messages.error(request,"Invalid credentials Please try again")
               return redirect('/')
               
               
     return HttpResponse('404 - Not Found')

def handleLogout(request):
    logout(request)
    messages.success(request,"succesully Logout")
    return redirect('/')


def watchlater(request):
    if request.method=="POST":
        user=request.user
        video_id=request.POST['video_id']

        watch=Watchlater.objects.filter(user=user)
        for i in watch:
            if video_id==i.video_id:
                messages.success(request,"Song is already added")
                break
        else:
            wl=Watchlater(user=user,video_id=video_id)
            wl.save()
            messages.success(request,"Song added to watch later")
        return redirect(f"/index/subpage/{video_id}")
    wl=Watchlater.objects.filter(user=request.user)
    ids=[]
    for i in wl:
        ids.append(i.video_id)
    
    preserved=Case(*[When(pk=pk,then=pos) for pos,pk in enumerate(ids)])
    song=Allmusic.objects.filter(sno__in=ids).order_by(preserved)
    
    return render(request,'watchlater.html',{'song':song})

def subpage(request,sno):
    post=Allmusic.objects.filter(sno=sno)
    comment=BlogComment.objects.filter(post=sno)
    context={'post':post,'comment':comment}
    return render(request,'subpage.html',context)

def postComment(request):
    comment=request.POST.get("comment")
    user=request.user
    postSno=request.POST.get("postSno")
    post=Allmusic.objects.get(sno=postSno)
    comment=BlogComment(comment=comment,user=user,post=post)
    comment.save()
    messages.success(request,"your comment has been posted")
    return redirect(f"index/subpage/{post.sno}")
   


def history(request):
    if request.method == "POST":
        user=request.user
        music_id=request.POST['music_id']
        history=History(user=user,music_id=music_id)
        history.save()

        print(history)
        return redirect(f"/index/subpage/{music_id}")

    history=History.objects.filter(user=request.user)
    ids=[]
    for i in history:
        ids.append(i.music_id)
    
    preserved=Case(*[When(pk=pk,then=pos) for pos,pk in enumerate(ids)])
    song=Allmusic.objects.filter(sno__in=ids).order_by(preserved)
    
    return render(request,'history.html',{"history":song})

Error

Operations to perform:
  Apply all migrations: admin, auth, contenttypes, ddsmusic, sessions
Running migrations:
  Applying ddsmusic.0014_allmusic_length...Traceback (most recent call last):
  File "C:\Users\sdhru\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\fields\__init__.py", line 1774, in get_prep_value
    return int(value)
ValueError: invalid literal for int() with base 10: ''

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    main()
  File "manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "C:\Users\sdhru\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line       
    utility.execute()
  File "C:\Users\sdhru\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 395, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Users\sdhru\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Users\sdhru\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 371, in execute
    output = self.handle(*args, **options)
  File "C:\Users\sdhru\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 85, in wrapped
    res = handle_func(*args, **kwargs)
  File "C:\Users\sdhru\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\migrate.py", line 243, in handle
    post_migrate_state = executor.migrate(
  File "C:\Users\sdhru\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "C:\Users\sdhru\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "C:\Users\sdhru\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\migrations\executor.py", line 227, in apply_migration
    state = migration.apply(state, schema_editor)
  File "C:\Users\sdhru\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\migrations\migration.py", line 124, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "C:\Users\sdhru\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\migrations\operations\fields.py", line 104, in database_forwards        
    schema_editor.add_field(
  File "C:\Users\sdhru\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\sqlite3\schema.py", line 328, in add_field
    self._remake_table(model, create_field=field)
  File "C:\Users\sdhru\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\sqlite3\schema.py", line 189, in _remake_table
    self.effective_default(create_field)
  File "C:\Users\sdhru\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\base\schema.py", line 303, in effective_default
    return field.get_db_prep_save(self._effective_default(field), self.connection)
  File "C:\Users\sdhru\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\fields\__init__.py", line 823, in get_db_prep_save
    return self.get_db_prep_value(value, connection=connection, prepared=False)
  File "C:\Users\sdhru\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\fields\__init__.py", line 818, in get_db_prep_value
    value = self.get_prep_value(value)
  File "C:\Users\sdhru\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\fields\__init__.py", line 1776, in get_prep_value
    raise e.__class__(
ValueError: Field 'length' expected a number but got ''.

0014_allmusic_length.py

# Generated by Django 3.1 on 2020-10-03 12:49

from django.db import migrations, models


class Migration(migrations.Migration):

    dependencies = [
        ('ddsmusic', '0013_auto_20201002_2135'),
    ]

    operations = [
        migrations.AddField(
            model_name='allmusic',
            name='length',
            field=models.IntegerField(default=2),
        ),
    ]

0 个答案:

没有答案