NameError: name 'Video' is not defined - python

I have little problem, I tryed make video uploader but something go wrong
models.py
class Video(models.Model):
name= models.CharField(max_length=500)
videofile= models.FileField(upload_to='videos/', null=True, verbose_name="")
def __str__(self):
return self.name + ": " + str(self.videofile)
Forms.py
from django import forms
class VideoForm(forms.ModelForm):
class Meta:
model=Video
fields=["name", "videofile"]
views.py
from django.shortcuts import render
from .models import Video
from .forms import VideoForm
def showvideo(request):
lastvideo= Video.objects.last()
videofile= lastvideo.videofile
form= VideoForm(request.POST or None, request.FILES or None)
if form.is_valid():
form.save()
context= {'videofile': videofile,
'form': form
}
return render(request, 'Blog/videos.html', context)
And yes I made migrations but he telling me that name 'Video' is not defined

In your forms.py, you specify model = Video, but you forgot to import the Video class, hence in that file, the name Video is not defined.
You can import this like:
# forms.py
from django import forms
from .models import Video
class VideoForm(forms.ModelForm):
class Meta:
model = Video
fields = ["name", "videofile"]
Note that in your view, you should not write form= VideoForm(request.POST or None, request.FILES or None), since then the form becomes invalid if there are simply nor request.POST parameters. You should pass request.POST itself, not request.POST or None.

Related

Own data for everyuser in django

So I am building a to do app in Django. I have created databases for the users and todo items. But I have a problem, how can each user have its own data. Like every user should add their own data. It seems like there is no answer out there.
My models.py
class Task(models.Model):
title = models.CharField(max_length=200)
complete = models.BooleanField(default=False)
created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
My forms.py
class CreateUserForm(UserCreationForm):
class Meta:
model = User
fields = ['username','email','password1','password2']
So how can I connect those both. I have red that I have to use foreign key. But I really don't understand how I can do it
You specify a ForeignKey [Django-doc] in the Task model that refers to the user that constructed it:
# app/models.py
from django.db import models
from django.conf import settings
class Task(models.Model):
title = models.CharField(max_length=200)
complete = models.BooleanField(default=False)
created = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE
)
def __str__(self):
return self.title
You can then make a ModelForm where you exclude the user. For example:
# app/forms.py
from django import forms
from app.models import Task
class TaskForm(forms.ModelForm):
class Meta:
model = Task
exclude = ['user']
Then in the view we can "inject" the user in the instance we create, for example:
# app/views.py
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect
from app.forms import TaskForm
#login_required
def create_task(request):
if request.method == 'POST':
form = TaskForm(request.POST, request.FILES)
if form.is_valid():
form.instance.user = request.user
form.save()
return redirect('name-of-some-view')
else:
form = TaskForm()
return render(request, 'some_template.html', {'form': form})
Note: In case of a successful POST request, you should make a redirect
[Django-doc]
to implement the Post/Redirect/Get pattern [wiki].
This avoids that you make the same POST request when the user refreshes the
browser.

Conecting forms to admin page in django

I´m making my own portfolio and I wanna be able to see the messages that people sent me in the admin page but I don't seem to be able to make it so when someone submits the message it saves in the model and "broadcasts" in the admin page.
Models.py
from django.db import models
# Create your models here.
class Messages(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField(max_length=50)
website = models.CharField(max_length=50)
text = models.CharField(max_length=500)
Forms.py
from django import forms
from django.core import validators
from django.forms import ModelForm
from .models import Messages
class Messages(forms.ModelForm):
name = forms.CharField(widget=forms.TextInput(attrs={'class' : 'name'}), required=True, label='', max_length=100)
email = forms.EmailField(widget=forms.TextInput(attrs={'class' : 'email'}), required=True, label='', max_length=50)
website = forms.CharField(widget=forms.TextInput(attrs={'class' : 'website'}),required=False, label='', max_length=50)
text = forms.CharField(widget=forms.TextInput(attrs={'class' : 'text'}), required=True, label='', max_length=500)
bot = forms.CharField(required=False, widget=forms.HiddenInput, validators=[validators.MaxLengthValidator(0)])
class Meta():
model = Messages
fields = '__all__'
Views.py
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseNotFound
from django.template import Template, Context
from . import forms
# Create your views here.
def index(request):
return render(request, 'index.html')
def portfolio(request):
return render(request, 'portfolio.html')
def certificate(request):
return render(request, 'certificate.html')
def contact(request):
form = forms.Messages()
if request.method == 'post':
form = form.Messages(request.post)
if form.is_valid():
form.save(commit=True)
return thankyou(request)
else:
print('CONTACT ERROR')
return render(request, 'contact.html', {'form':form})
def thankyou(request):
return render(request, 'thankyou.html')
Admin.py
from django.contrib import admin
from toni.models import Messages
# Register your models here.
admin.site.register(Messages)
Python is case sensitive. The request.method will always be uppercase, and the post data is stored in request.POST. Change the code to:
if request.method == 'POST':
form = forms.Messages(request.POST)
You can debug problems like this by adding more print() lines. For example, you could have added print("in the post") after if request.method == 'post':. Then when you saw that the line was never printed, you could have added print(request.method). Hopefully you would then spot the mismatch between 'post' and 'POST'.

IntegrityError NOT NULL constraint failed

I'm building a simple blog app using Django. I want to realize the function of adding a new blog using form. Some problems occurs.
Here is my models.py
from django.db import models
from django.utils import timezone
from django.template.defaultfilters import slugify
from django.contrib.auth.models import User
class Blog(models.Model):
title=models.CharField(max_length=60)
content=models.TextField()
author=models.ForeignKey('auth.User',on_delete=models.CASCADE,)
date=models.DateTimeField(default=timezone.now)
slug=models.SlugField(null=True,unique=True)
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super(Blog, self).save(*args, **kwargs)
def __str__(self):
return self.title
class UserProfile(models.Model):
user=models.OneToOneField(User)
website=models.URLField(blank=True)
def __str__(self):
return self.user.username
forms.py
from django.template.defaultfilters import slugify
from blog.models import UserProfile
from django.contrib.auth.models import User
class BlogForm(forms.ModelForm):
title=forms.CharField(max_length=60,
help_text="blog title")
content=forms.CharField(help_text="blog content")
author=forms.CharField(help_text="blog author")
date=forms.DateTimeField(help_text="blog date")
class Meta:
model=Blog
fields=('title',)
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())
class Meta:
model=User
fields = ('username','email','password')
class UserProfileForm(forms.ModelForm):
class Meta:
model=UserProfile
fields=('website',)
the add_blog method in views.py
def add_blog(request):
form=BlogForm()
if request.method =='POST':
form=BlogForm(request.POST)
if form.is_valid():
form.save(commit=True)
return index(request)
else:
print(form.errors)
return render(request, 'add_blog.html',{'form':form})
When I want to add a new blog in my webpage, I can't input the record. It shows me
IntegrityError at /add_blog/
NOT NULL constraint failed: blog_blog.author_id
Could anybody help me fix this problem? Thanks a lot!
In your models, your Blog class requires:
Title
An author, of type auth.User
content
The first step, is to remove the author field from your form:
class BlogForm(forms.ModelForm):
title=forms.CharField(max_length=60,
help_text="blog title")
content=forms.CharField(help_text="blog content")
# author=forms.CharField(help_text="blog author")
date=forms.DateTimeField(help_text="blog date")
class Meta:
model=Blog
fields=('title','content','date')
Next, is to add the logged in user as the author in your view:
from django.shortcuts import redirect
from django.contrib.auth.decorators import login_required
# makes sure this view is called with a valid user
# https://docs.djangoproject.com/en/2.0/topics/auth/default/#the-login-required-decorator
#login_required
def add_blog(request):
form = BlogForm(request.POST or {})
if form.is_valid():
temp = form.save(commit=False)
temp.author = request.user # add the logged in user, as the
# author
temp.save()
return redirect('/')
return render(request, 'add_blog.html',{'form':form})
Another way to view this problem... Perhaps you can Try clearing your migration files , and re-run makemigrations to see if it catches anything off about your models. It may ask you for a default value for some of the fields; and this should ring a bell to assign null=True where appropriate. Personally this is quite a common integrity conflict for me (i'm new to the framework) especially when i've done many unplanned on the fly mods to models on the same db.

'CategoryForm' object has no attribute 'save'

Working with tutorial tango with django(fun with forms) ,error is showing 'CategoryForm' object has no attribute 'save' pls help
The project tango_withDjango has a app rango in it p.s. identation are correct in my program unlike here...and using ModelForm will show error
views.py is
from django.http import HttpResponse
from django.template import RequestContext
from django.shortcuts import render_to_response
from rango.models import Category
from rango.models import Page
from rango.forms import CategoryForm
def add_category(request):
# Get the context from the request.
context = RequestContext(request)
# A HTTP POST?
if request.method == 'POST':
form = CategoryForm(request.POST)
# Have we been provided with a valid form?
if form.is_valid():
# Save the new category to the database.
form.save()
# Now call the index() view.
# The user will be shown the homepage.
#return index(request)
else:
# The supplied form contained errors - just print them to the terminal.
print form.errors
else:
# If the request was not a POST, display the form to enter details.
form = CategoryForm()
# Bad form (or form details), no form supplied...
# Render the form with error messages (if any).
return render_to_response('rango/add_category.html', {'form': form}, context)
models.py`
from django.db import models
class Category(models.Model):
name=models.CharField(max_length=128,unique=True)
def __unicode__(self):
return self.name
class Page(models.Model):
category=models.ForeignKey(Category)
title=models.CharField(max_length=128)
url=models.URLField()
views=models.IntegerField(default=0)
def __unicode__(self):
return self.title
forms.py
from django import forms
from rango.models import Page,Category
class CategoryForm(forms.Form):
name=forms.CharField(max_length=128,help_text="Please enter Category name")
views=forms.IntegerField(widget=forms.HiddenInput(),initial=0)
likes=forms.IntegerField(widget=forms.HiddenInput(),initial=0)
class Meta:
model=Category
class PageForm(forms.ModelForm) :
title=forms.CharField(max_length=128,help_text="Please enter title of the Pages")
url=forms.URLField(max_length=200,help_text="please enter url of the page")
views=forms.IntegerField(widget=forms.HiddenInput(),initial=0)
class Meta :
model=Page
fields=('title','url','views')
CategoryForm should extend the ModelForm, not the Form.
And btw, class Meta does not exist for Form

Django: AttributeError form has no attribute 'is_valid'

I'm having an issue saving comments for a blog app I'm writing in Django. The error is: AttributeError at /blog/123456/ 'comment' object has no attribute 'is_valid'
My models.py:
from django.db import models
class comment(models.Model):
comID = models.CharField(max_length=10, primary_key=True)
postID = models.ForeignKey(post)
user = models.CharField(max_length=100)
comment = models.TextField()
pub_date = models.DateTimeField(auto_now=True)
views.py:
from django.http import HttpResponse
from django.shortcuts import render
from django.template import RequestContext, loader
from django.db.models import Count
from blog.models import post, comment
from site.helpers import helpers
def detail(request, post_id):
if request.method == 'POST':
form = comment(request.POST)
if form.is_valid():
com = form.save(commit=False)
com.postID = post_id
com.comID = helpers.id_generator()
com.user = request.user.username
com.save()
return HttpResponseRedirect('/blog/'+post_id+"/")
else:
blog_post = post.objects.get(postID__exact=post_id)
comments = comment.objects.filter(postID__exact=post_id)
form = comment()
context = RequestContext(request, {
'post': blog_post,
'comments': comments,
'form': form,
})
return render(request, 'blog/post.html', context)
I'm not sure what the issue is, from the tutorials/examples I've been looking at, form should have the attribute is_valid(). Could someone help me understand what I'm doing wrong?
comment is a Model. is_valid method are present in forms. I think what you wnat to do is create a ModelForm for comment like this:
from django import forms
from blog.models import comment
class CommentForm(forms.ModelForm):
class Meta:
model=comment
And use CommentForm as IO interface to comment class.
You can learn more about ModelForms at the docs
Hope this helps!

Categories

Resources