I am pretty much new for Django and trying to create fields to add a new movie to the existing model. It shows an error : ImportError: cannot import name 'ModelForm'
#forms.py file:
from django import forms
from django import ModelForm
from .models import Movie
class MovieForm(ModelForm):
class Meta:
model = Movie
fields = ['genre', 'price', 'rent_time', 'flag']
class CustForm(forms.Form):
f_name = forms.CharField(label='First_Name', max_length=50)
l_name = forms.CharField(label='Last_Name', max_length=50)
address = forms.CharField(label='Address', max_length=125)
cell = forms.IntegerField(label='Cell')
#------------------------------------------------------------------------
#models.py file:
from django.db import models
from django.forms import ModelForm
class Customer(models.Model):
f_name = models.CharField(max_length=50)
l_name = models.CharField(max_length=50)
address = models.CharField(max_length=125)
cell = models.IntegerField(blank=True, null=True)
class Movie(models.Model):
genre = models.CharField(max_length=50)
price = models.FloatField(blank=True, null=True)
rent_time = models.DateTimeField(auto_now_add=True, blank=True)
flag = models.BooleanField(default=True)
user_id = models.ForeignKey('Customer', on_delete=models.SET_NULL,
null=True)
#------------------------------------------------------------------------
#views.py file:
from django.shortcuts import render
from .models import Customer, Movie
# from django.http import HttpResponseRedirect
from .forms import MovieForm, CustForm
def dashboard(request):
customer_data = Customer.objects.all()
context = {'Customer_List': customer_data}
return render(request, 'movie_renting_app/home.html', context)
def movie_list(request):
movie_data = Movie.objects.all()
context = {"Movie_List": movie_data}
return render(request, 'movie_renting_app/all_movies.html', context)
def rented_movies(request):
rented_movie = Movie.objects.filter(flag=True)
context = {"Rented_Movies_List": rented_movie}
return render(request, 'movie_renting_app/rent.html', context)
def add_movies(request):
if request.POST:
form = MovieForm()
print(request)
# return movie_list(request)
else:
form = MovieForm()
return render(request, 'movie_renting_app/new_movie.html',
{'form': form})
def add_customer(request):
if request.POST:
form = request.POST
print(request)
c = Customer(f_name=form['f_name'], l_name=form['l_name'],
address=form['address'], cell=form['cell'])
c.save()
return dashboard(request)
else:
form = CustForm()
return render(request, 'movie_renting_app/new_customer.html',
{'form': form})
def update_customer_info(request):
pass
def available_list(request):
pass
I am getting an error on command prompt.
I have no clue what is going wrong with my code. I have tried various ways to import the ModelForm but it showing me the same error message. I am using Django 2.0 and Python 3.6
ModelForm class is located in Django forms
so you can import it as shown below.
from django.forms import ModelForm
or use it directly when subclassing your form class
class CustomForm(forms.ModelForm):
# your form fields here
pass
for more information about ModelForms see django docs
The error is probably your second line in forms.py. ModelForm is in django.forms, and can't be imported from django. Try this instead:
from django.forms import ModelForm
Or, change class MovieForm(ModelForm): to class MovieForm(forms.ModelForm): and remove your ModelForm import line.
Replace this wrong code in line 2, "forms.py":
from django import ModelForm # Line 2, "forms.py"
With this correct code:
from django.forms import ModelForm # Line 2, "forms.py"
Related
I have a form to let users make a new poll, it consists of 2 ModelForms one for the Question model and another for the Choice model
a screenshot:
Make new poll form
i want there to be something like a (+) or (add another choice) button where users can add as many choices as they want and then submit it all.
here's the models.py file
models.py
from django.db import models
from django.contrib.auth import get_user_model
User = get_user_model()
class Question(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=False)
questionText = models.CharField(max_length=150)
datePublished = models.DateTimeField(auto_now_add=True)
def str(self):
return self.questionText
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choiceText = models.CharField(max_length=200)
choiceVotes = models.IntegerField(default=0)
def str(self):
return self.choiceText
forms.py
from django import forms
from .models import Question
from .models import Choice
class NewPollForm(forms.ModelForm):
class Meta:
model = Question
labels = {
"questionText":"Poll question"
}
fields = ("questionText",)
class NewChoicesForm(forms.ModelForm):
class Meta:
model = Choice
labels = {
"choiceText":"Choice"
}
fields = ("choiceText",)
the view for this form's page you can see it is set for only one choice field right now
from .forms import NewPollForm
from .forms import NewChoicesForm
def newpoll(request):
if request.user.is_authenticated == True :
pass
else:
return redirect("users:signup")
if request.method == "POST":
qform = NewPollForm(request.POST)
cform = NewChoicesForm(request.POST)
if qform.is_valid():
newpoll = qform.save(commit=False)
newpoll.user = request.user
newpoll.datePublished = timezone.now()
newpoll.save()
cform.instance.question = newpoll
cform.save()
return redirect("polls:details", pollid=newpoll.pk)
else:
return render (request, "polls/newpoll.html", {"qform":qform, "cform":cform})
else:
qform = NewPollForm()
cform = NewChoicesForm()
return render (request, "polls/newpoll.html", {"qform":qform, "cform":cform})
I am trying to make quiz making application, since am new to django am unable to build the logic for saving foreign key field in database table. Someone please help me for the same.
models.py
In models.py , class quiztitle is for title of the quiz and id(foreign key,User model) of user who created that quiz.
class question is for question along with 4 options and the correct answer. Quizid(foreign key,quiztitle model) and id(foreign key,User model)
class answer is for the answer submitted by user who take the quiz.
from django.db import models
from django.contrib.auth.models import User
class quiztitle(models.Model):
Quiz_id = models.AutoField(primary_key=True)
Quiz_title = models.CharField(max_length=600)
id= models.ForeignKey(User, on_delete=models.CASCADE)
class question(models.Model):
Qid = models.AutoField(primary_key=True)
id = models.ForeignKey(User,on_delete=models.CASCADE)
Quiz_id = models.ForeignKey(quiztitle,on_delete=models.CASCADE)
Qques = models.TextField()
Qoption1 = models.TextField()
Qoption2 = models.TextField()
Qoption3 = models.TextField()
Qoption4 = models.TextField()
QAnswer = models.TextField()
class answer(models.Model):
Ansid = models.AutoField(primary_key=True)
Qid = models.ForeignKey(question,on_delete=models.CASCADE)
Quiz_id = models.ForeignKey(quiztitle, on_delete=models.CASCADE)
id = models.ForeignKey(User, on_delete=models.CASCADE)
Answer = models.TextField()
forms.py
from django.forms import ModelForm
from django.contrib.auth.forms import UserCreationForm
from django import forms
from django.contrib.auth.models import User
class CreateUserForm(UserCreationForm):
class Meta:
model = User
fields = ['username','email','password1','password2']
views.py
from django.shortcuts import render,redirect,HttpResponseRedirect
from .models import question ,quiztitle
from django.contrib import messages
from django.contrib.auth import authenticate,login,logout
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.contrib.auth.models import User
from django.forms import inlineformset_factory
from django.contrib.auth.forms import UserCreationForm
from .forms import CreateUserForm
from django.contrib import messages
from django.contrib.auth import authenticate,login,logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import Group
# Create your views here.
#login_required(login_url='home')
def handle_quiz(request):
if request.method=="POST":
# get post parameters
id = request.POST.get('id')
Quiz_title = request.POST.get('Quiz_title')
Quiz_id = request.POST.get('Quiz_id')
Qid = request.POST.get('Qid')
Qques = request.POST.get('Qques')
Qoption1 = request.POST.get('Qoption1')
Qoption2 = request.POST.get('Qoption2')
Qoption3 = request.POST.get('Qoption3')
Qoption4 = request.POST.get('Qoption4')
QAnswer = request.POST.get('QAnswer')
#I guess here is the mistake in saving the data in the mysql database
title = quiztitle(Quiz_title=Quiz_title,Quiz_id=Quiz_id,id=id)
title.save()
detail = question(Qid=Qid,Quiz_id=Quiz_id,id=id,Qques=Qques,Qoption1=Qoption1,Qoption2=Qoption2,Qoption3=Qoption3,Qoption4=Qoption4,QAnswer=QAnswer)
detail.save()
messages.success(request,"Your question has been added succesfully ")
return HttpResponseRedirect('/quizmaker')
return render(request,"createquiz.html")
def logoutUser(request):
logout(request)
return redirect('home')#redirect to login page
def home_page(request):
return render(request,'Home.html')
def registerPage(request):
if request.user.is_authenticated:
return redirect('home')
else:
form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST)
if form.is_valid():
user = form.save()
username = form.cleaned_data.get('username')
messages.success(request, 'account has been created successfully for username' + username)
return redirect('login')
context = {'form':form}
return render(request,'register.html',context)
def handle_login(request):
if request.user.is_authenticated:
return redirect('home')
else:
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('quizmaker')
else:
messages.info(request, 'Incorrect Username or Password')
context = {}
return render(request, 'login.html', context)
#login_required(login_url='login')
def handle_response(request):
data= question.objects.all()
return render(request, "student.html", {"messages": data})
admin.py
from django.contrib import admin
from .models import *
# Register your models here.
class quizadmin(admin.ModelAdmin):
list_display = ['Qid','Quiz_id','Qques','Qoption1','Qoption2','Qoption3','Qoption4','QAnswer']
admin.site.register(question,quizadmin)
admin.site.register(quiztitle)
As you guess your issue lies at title and detail.
To set a value to the ForeignKey you need an object. You can use instead an field with _id at the end.
Behind the scenes, Django appends "_id" to the field name to
create its database column name, see Django ForeignKey
It must be:
title = quiztitle.objects.create(
Quiz_title=Quiz_title,
Quiz_id=Quiz_id,
User_id_id=id # here
)
detail = question.objects.create(
Quiz_id_id=Quiz_id, User_id_id=id # and here,
Qid=Qid, Qques=Qques, Qoption1=Qoption1,
Qoption2=Qoption2, Qoption3=Qoption3,
Qoption4=Qoption4, QAnswer=QAnswer
)
I suggest you to use Django ModelForm here.
Based on the above, I recommend you also to rename your ForeignKey fields:
id > to user
Quiz_id > to quiztitle
Model style (Django Docs):
Use InitialCaps for class names (or for factory functions that return
classes).
Field names should be all lowercase, using underscores instead of
camelCase.
hi i want to show my articles latest article should appear first i used class Meta in models but its not working it does not show any error but it it shows old articles on top. if anyone can please help that would be very helpfull
models.py
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
class Article(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField()
body = models.TextField()
date = models.DateTimeField(default=timezone.now)
thumb = models.ImageField(default='default.png', blank=True)
author = models.ForeignKey(User, on_delete=models.CASCADE, default=None)
class Meta:
ordering = ['-date']
def __str__(self):
return self.title
def snippet(self):
return self.body[:100]+'...'
views.py
from django.http import HttpResponse
from django.shortcuts import render, redirect
from .models import Article
from django.contrib.auth.decorators import login_required
from . import forms
def article_list(request):
articles = Article.objects.all().order_by('date')
return render(request, 'articles/article_list.html', {'articles': articles})
def article_detail(request, slug):
# return HttpResponse(slug)
article = Article.objects.get(slug=slug)
return render(request, 'articles/article_detail.html', {'article': article})
#login_required(login_url="/accounts/login/")
def article_create(request):
if request.method == 'POST':
form = forms.CreateArticle(request.POST, request.FILES)
if form.is_valid():
# save article to db
instance = form.save(commit=False)
instance.author = request.user
instance.save()
return redirect('articles:list')
else:
form = forms.CreateArticle()
return render(request, 'articles/article_create.html', {'form': form})
In your view, you order in ascending order, you should prepend date with a minus (-):
def article_list(request):
articles = Article.objects.order_by('-date')
return render(request, 'articles/article_list.html', {'articles': articles})
or if you do not specify an order, then the ordering defined in Meta will be applied:
def article_list(request):
articles = Article.objects..all()
return render(request, 'articles/article_list.html', {'articles': articles})
When I try to save a post, the post is saved, but current user is not registered and the post is duplicated with a blank entry and the current user is not stored.
For adding the post I use not the admin app but a personal template and form.
See the problem:
This is my view code:
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect
from .forms import NewAdminPostForm
from .models import Post, Category
# Create your views here.
def home(request):
posts = Post.objects.all()
categories = Category.objects.all()
posts_last = Post.objects.order_by('-created_at')[0:3]
return render(request, 'front/blog-list.html', {'posts': posts,
'categories': categories, 'posts_last': posts_last})
#login_required
def newadminpost(request):
if request.method == 'POST':
form = NewAdminPostForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
Post.objects.create(
message=form.cleaned_data.get('message'),
category_id=post.category_id,
created_by=request.user
)
#post.save()
return redirect('listadminpost')
else:
form = NewAdminPostForm()
return render(request, 'back/new-post-blog.html', {'form': form})
#login_required
def listadminpost(request):
posts = Post.objects.all()
return render(request, 'back/list-post-blog.html', {'posts': posts})
Form of my Blog:
from django import forms
from .models import Post, Category
class NewAdminPostForm(forms.ModelForm):
title = forms.CharField(label="Titre de l'article", max_length=255,)
message = forms.CharField(widget=forms.Textarea(),
max_length=4000,
help_text="Contenu de l'article")
pre_message = forms.CharField(label="Message de prévisu",
widget=forms.Textarea(),
max_length=4000,
help_text="Contenu de l'article")
class Meta:
model = Post
fields = ['title','meta_desc','message','pre_message','category']
Model of my Blog:
from django.db import models
from django.contrib.auth.models import User
class Category(models.Model):
name = models.CharField(max_length=255, unique=True)
description = models.TextField(max_length=1000)
def __str__(self):
return self.name
def get_categories_count(self):
return Category.objects.filter(post__category=self).count()
class Post(models.Model):
title = models.CharField(max_length=255)
meta_desc = models.TextField(max_length=320, null=True)
pre_message = models.TextField(max_length=4000, null=True)
message = models.TextField(max_length=4000)
category = models.ForeignKey(Category, on_delete='cascade')
created_at = models.DateTimeField(auto_now_add=True)
created_by = models.ForeignKey(User, on_delete=models.CASCADE,
blank=True, null=True)
def __str__(self):
return self.title
https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.create
your code:
post.save()...Post.objects.create(
from the link above:
A convenience method for creating an object and saving it all in one step. Thus:
p = Person.objects.create(first_name="Bruce", last_name="Springsteen")
and:
p = Person(first_name="Bruce", last_name="Springsteen")
p.save(force_insert=True)
are equivalent.
So what you do in your code:
you save post object created from form
you create and save another Post instance by calling create method
choose any of them, just one, and this will avoid duplicates.
Instead of doing this:
#login_required
def newadminpost(request):
if request.method == 'POST':
form = NewAdminPostForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
Post.objects.create(
message=form.cleaned_data.get('message'),
category_id=post.category_id,
created_by=request.user
)
#post.save()
return redirect('listadminpost')
else:
form = NewAdminPostForm()
return render(request, 'back/new-post-blog.html', {'form': form})
You could do this: cleaner, easier to read, more up-to-date, and easier to maintain:
class AdminCreateView(LoginRequiredMixin, generic.CreateView):
model = Request
form_class = RequestForm
def form_valid(self, form):
result = super(AdminCreateView, self).form_valid(form)
title = form.cleaned_data.get('title')
meta_desc = form.cleaned_data.get('meta_desc')
message = form.cleaned_data.get('message')
# and so on. if there's something you refuse (ex title empty) do this:
if not title:
form.add_error('title', _("Precise the title"))
return self.form_invalid(form)
Post.objects.create(message=message,
meta_desc=meta_desc,
title=title,) # and so on
return result
I still cant seem to put a simple program together. I am thinking of a simple program where my coworkers and I could propose a bet with each other. (example: I bet the detriot Lions dont win another game this season) If someone is feeling up to the task of taking that bet they can just hit an accept button. I want the user to be logged in and upon submitting the bet_name and bet_desc of the bet, their username, bet_name, bet_desc, and timestamp is saved to a table. Then a relationship table would save the bet id, win, tie, created_user_id, accepted_user_id, accepted_timestamp, and cancelled. Then userprofile table to keep their username, wins, losses, ties, bets_made, and bets_accepted.
models.py
from django.db import models
from django.contrib.auth.models import User
from datetime import datetime
class UserProfiles(models.Model):
username = models.OneToOneField(User)
wins = models.PositiveIntegerField(default=0)
losses = models.PositiveIntegerField(default=0)
ties = models.PositiveIntegerField(default=0)
bets_made = models.PositiveIntegerField(default=0)
bets_accepted = models.PositiveIntegerField(default=0)
def __str__(self):
return "%s's profile" % self.username
class Bets2(models.Model):
bet_name = models.CharField(max_length=30)
bet_desc = models.CharField(max_length=300)
timestamp = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
created_user = models.OneToOneField(UserProfiles, primary_key=True)
accepted_user = models.PositiveIntegerField(default=0)
accepted_timestamp = models.DateTimeField(auto_now=True)
win = models.BooleanField(default=True)
tie = models.BooleanField(default=True)
cancelled = models.BooleanField(default=True)
def __str__(self):
return "%s's profile" % self.bet_name
As far as forms.py and views this is all i have so far:
forms.py
from django import forms
from django.core.exceptions import ValidationError
from .models import Bets2, UserProfiles
class BetForm(forms.ModelForm):
class Meta:
model = Bets2
fields = ['bet_name', 'bet_desc',]
def clean_name(self):
bet_name = self.cleaned_data.get('bet_name')
#write code here
return name
def clean_bet(self):
bet_desc = self.cleaned_data.get('bet_desc')
#write code here
return bet
views.py
from django.shortcuts import render
from django.conf import settings
from .forms import BetForm
from .models import Bets2, UserProfiles
def home(request):
title = "2015 Boardbets"
queryset = Bets2.objects.all().order_by('timestamp')
queryuser = UserProfiles.objects.all()
context = {
"title": title,
"queryset" : queryset,
"queryuser" : queryuser,
}
return render(request, "home.html", context)
def boardbet(request):
form = BetForm(request.POST or None)
bet_variables = Bets2.objects.all()
context = {
"form" : form,
"bet_variables" : bet_variables,
}
if form.is_valid():
form.save()
return render(request, "bets.html", context)
This is where i get stumped, i dont know how to incorporate the other two models into the view so that all three tables get created and also how to reference them in the template.
Edit: changed it to one model for Bets