I have made the simple form using django, i am new to django,yesterday, i have wrote some code to practice,from today it is not working,but it is working yesterday.
template file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form method="POST" novalidate>
{% csrf_token %}
{{form.as_p}}
<input type="submit" value="Submit">
</form>
</body>
</html>
from django.http import HttpResponse
from django.shortcuts import render
from .forms import FeedBackFormCustom
from .models import FeedBack
# Create your views here.
def home(req):
if req.method == "POST":
form = FeedBackFormCustom(req.POST)
if form.is_valid():
nm = form.cleaned_data['name']
ag = form.cleaned_data['age']
em = form.cleaned_data['email']
st = form.cleaned_data['state']
inst = FeedBack(name=nm, age=ag, email=em, state=st)
inst.save()
return HttpResponse('<h2>Form successfully submitted.</h2>')
else:
form = FeedBackFormCustom()
context = {'form': form}
return render(req, 'home/index.html', context)
Models.py
from pyexpat import model
from django.db import models
# Create your models here.
class FeedBack(models.Model):
STATES_AVAILABLE = (
('ap', 'Andhra Pradesh'),
('mp', 'Madhya Pradesh'),
('kn', 'kutub nagar'),
('mu', 'Mumbai'),
('de', 'Delhi'),
('ch', 'Chennai'),
)
name = models.CharField(max_length=30)
age = models.PositiveIntegerField()
email = models.EmailField(max_length=200)
state = models.CharField(max_length=3, choices=STATES_AVAILABLE)
def __str__(self):
return self.name
ModelForm.py
from django import forms
from .models import FeedBack
from django.contrib.auth.forms import UserChangeForm, UserCreationForm, PasswordChangeForm, SetPasswordForm
class FeedBackFormCustom(forms.ModelForm):
class Meta:
model = FeedBack()
fields = '__all__'
I am trying since last 2 hours but not able to find out what mistake i did? Django is also not telling on which the error is occurred 'FeedBack' object is not callable
On your ModelForm.py change your Model name inside Meta class as
from django import forms
from .models import FeedBack
from django.contrib.auth.forms import UserChangeForm, UserCreationForm, PasswordChangeForm, SetPasswordForm
class FeedBackFormCustom(forms.ModelForm):
class Meta:
model = FeedBack #<--------------- change here
fields = '__all__'
This is because you have called your model that is model = FeedBack() in your forms.py. It should be model = FeedBack, this error means It is not callable object, it requires only its name.
Replace model=FeedBack() to model=FeedBack, only give name not ().
Related
I am a beginner in Django. I recently came across a problem: When I am trying to fetch objects, it is saying
DoesNotExist: Value matching query does not exist.
I searched the web but still I got no clue as to why this is happening.
My models.py
from django.db import models
class Value(models.Model):
eq_input = models.CharField(max_length=20, default='x**2 + y**2')
color = models.CharField(max_length=20, default='Magma')
My forms.py
from django import forms
from .models import Value
class ViewForm(forms.ModelForm):
Equation = forms.CharField(max_length=20, label='Equation')
Color = forms.CharField(max_length=20,label='Color')
class Meta:
model = Value
fields = {
'Equation',
'Color'
}
My views.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import Value
from .forms import ViewForm
def home_view(request):
if request.method == "POST":
form = ViewForm(request.POST)
if form.is_valid():
form.save()
else:
form = ViewForm()
context = {
'form': form
}
return render(request, "home.html", context)
My home.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>3D Graph Plotter</title>
</head>
<body>
<center><h1>This is a 3D plotter</h1></center>
<center>
<form action="." method="POST">{% csrf_token %}
{{ form.as_p }}
<input type="submit" name="Save" />
</form>
</center>
</body>
</html>
and my urls.py
from django.contrib import admin
from django.urls import path, include
from equation.views import eq, home_view
urlpatterns = [
path('admin/', admin.site.urls),
path('', home_view, name='hv')
]
Is there something I am missing or something is wrong there? Can you point that out?
the problem is inside your forms.py try this
from django import forms
from .models import Value
class ViewForm(forms.ModelForm):
class Meta:
model = Value
fields = ['eq_input','color']
and if you want to add label
class Value(models.Model):
eq_input = models.CharField(max_length=20,verbose_name='Equation', default='x**2 + y**2')
color = models.CharField(max_length=20,verbose_name='Color' ,default='Magma')
after that do not forget to run makemigrations and migrate.
I'm trying to create a form in Django template but it is just not showing the fields.
my files:
models.py where i created the desired table
from django.db import models
from django.contrib.auth.models import User
from django.db.models.deletion import CASCADE
STATUS = (
(0,"Draft"),
(1,"Publish")
)
class Post(models.Model):
title = models.CharField(max_length=50)
slug = models.SlugField(max_length=200)
auther = models.ForeignKey(User,on_delete=CASCADE,related_name="blog_posts")
updated_on = models.DateTimeField(auto_now=True)
created_on = models.DateTimeField( auto_now_add=True)
status = models.IntegerField(choices=STATUS,default=0)
body = models.TextField()
def __str__(self):
return self.title
views.py where i created the view for the form
from post.models import Post
from django.shortcuts import redirect, render
from . forms import PostForm
def post_list(request):
posts = Post.objects.all
form = PostForm(request.POST)
if request.method == "POST":
if form.is_valid():
form.save(commit=False)
form.auther = request.user
form.save()
return redirect("/")
else:
form = PostForm()
context = {
"posts":posts,
"form":form,
}
return render(request,'index.html',context)
forms.py where i created the form to edit only one field in the table
from django import forms
from django.db.models import fields
from django import forms
from . models import Post
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields='__all__'
index.html here is how i used the form in the html template
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Blog App</title>
</head>
<body>
{% for post in posts %}
<div>
<h1>{{post.title}}</h1>
</div>
{{post.body}}
{% endfor %}
<form method="post" action="/">
{% csrf_token %}
{{form}}
<input type="submit" value="save">
</form>
</body>
</html>
You did not add any field to the PostForm class:
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields='__all__'
Since u have no field, nothing will be displayed.
class PostForm(forms.ModelForm):
user_name=forms.CharField()
class Meta:
model = Post
fields='__all__'
I am building a form where a user can upload an image. After clicking on the submit button he/she will be redirected to a preview page to see all submitted image. But the image is not showing up in the review page whereas the image is visible from the admin site. After clicking on the inspect, it shows the image source is unknown. Here's my code:
models.py
from django.db import models
from phonenumber_field.modelfields import PhoneNumberField
# Create your models here.
class Register(models.Model):
name = models.CharField(max_length=50)
idCard = models.ImageField(upload_to='idCard', null=True)
def __str__(self):
return self.name
forms.py
from django import forms
from django.forms import ModelForm
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from .models import *
class RegisterForm(ModelForm):
name = forms.CharField(widget=forms.TextInput(attrs={'placeholder':'Your full name...'}))
class Meta:
model = Register
fields = '__all__'
views.py
from django.shortcuts import render, redirect
from .models import *
from .forms import *
# Create your views here.
def index(request):
form = RegisterForm()
if request.method == 'POST':
form = RegisterForm(request.POST, request.FILES)
if form.is_valid():
instance = form.save()
return redirect('preview', pk=instance.id)
context = {'form':form}
return render(request, 'event/index.html', context)
def preview(request, pk):
reg = Register.objects.get(id=pk)
prev = RegisterForm(instance=reg)
if request.method == 'POST':
form = RegisterForm(request.POST, instance=reg)
if form.is_valid():
form.save()
return redirect('/')
context = {'reg':reg, 'prev':prev}
return render(request, 'event/preview.html', context)
urls.py
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from . import views
urlpatterns = [
path('', views.index, name='home'),
path('preview/<str:pk>', views.preview, name="preview"),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
preview.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Preview</title>
</head>
<body>
Hey {{prev.name}},
your idCard photo is <img src="{{prev.idCard.url}}" alt="idcard">
</body>
</html>
index.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Event Registration</title>
<link rel="stylesheet" href="{% static 'css/style.css' %}">
<script src="{% static 'js/script.js' %}"></script>
</head>
<body>
<div class="mobile-screen">
<div class="header">
</div>
<div class="logo"></div>
<form id="login-form" method="POST" action="" enctype="multipart/form-data">
{% csrf_token %}
{{form.name}}
<legend style="color: aliceblue;">Upload ID card: </legend>{{form.idCard}}
<input class="btn btn-sm btn-primary" type="submit" value="Register" name="Register">
</form>
</div>
</body>
</html>
Help me load the image in the preview page
It seems like you haven't created User class yet. You need related_name to reference the Register model through User
models.py:
from django.db import models
from phonenumber_field.modelfields import PhoneNumberField
from django.contrib.auth.models import User
# Create your models here.
class Register(models.Model):
username = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile")
name = models.CharField(max_length=50)
idCard = models.ImageField(upload_to='idCard', null=True)
def __str__(self):
return self.name
forms.py:
from django import forms
from django.forms import ModelForm
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from .models import *
class UserForm(ModelForm):
class Meta():
model = User
fields = ('username')
class RegisterForm(ModelForm):
name = forms.CharField(widget=forms.TextInput(attrs={'placeholder':'Your full name...'}))
class Meta:
model = Register
fields = '__all__'
preview.html:
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Preview</title>
</head>
<body>
Hey {{prev.name}},
your idCard photo is <img src="{{prev.profile.idCard.url}}" alt="idcard">
</body>
</html>
I'm creating Django forms using model forms because u I wanted the forms to be created automatically, but when I created this code the forms do not appear in the index.html page
models.py
from django.db import models
class BaseCase(models.Model):
base_case_name = models.CharField(primary_key=True, max_length=255)
version = models.TextField(blank=True, null=True)
default = models.TextField(blank=True, null=True) # This field type is a guess.
class Meta:
managed = False
db_table = 'base_case'
forms.py
from django import forms
from SFP.models import *
class BaseCaseForm(forms.ModelForm):
class Meta :
model = BaseCase
fields='__all__'
views.py
from django.shortcuts import render,redirect
from .models import *
from .forms import *
def addbc(self, request):
bcform=BaseCaseForm(request.POST)
bcform.save()
basecasename = bcform.cleaned_data['post']
version = bcform.cleaned_data['post']
default = bcform.cleaned_data['post']
bcform = BaseCaseForm()
return redirect('index.html')
args = {'bcform':bcform,
'basecasename': basecasename,
'version': version,
'default' :default}
return render(request, 'index.html', args)
index.html
<!DOCTYPE html>
<html>
<head>
<title>S&FP</title>
</head>
<body>
<h1>Forms</h1>
{% csrf_token %}
{{ bcform }}
<input type="submit" value="add">
</body>
</html>
and i think that this is important too
urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index),
url(r'^$', views.addbc),
]
I was expecting the form fields to be generated automatically but they don't appear!
You can try CreateView which will create forms for your model. Find more about it in the docs
In your case, create a view like this:
views.py
class BaseCaseCreate(CreateView):
model = BaseCase
template_name = 'index.html'
success_url = reverse_lazy('app:home')
fields = ('base_case_name','version','default')
index.html
<!DOCTYPE html>
<html>
<head>
<title>S&FP</title>
</head>
<body>
<h1>Forms</h1>
{% csrf_token %}
{{ form }}
<input type="submit" value="add">
</body>
I hope this helps.
I wrote in results.html,
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Score</title>
</head>
<body>
<h1>Score</h1>
<h2>Your score is {{ scoreresults.result }}</h2>
</body>
</html>
But now, this part {{ user.result }} of <h2>Your score is {{ user.result }}
</h2> is blank in my browser.
I wrote in models.py
from django.db import models
from django.contrib.auth.models import User
class ImageAndUser(models.Model):
user = models.ForeignKey("auth.User", verbose_name="imageforegin")
result = models.CharField(max_length=64, null=True)
def __str__(self):
return '{} {}'.format(self.user,self.id)
So,ImageAndUser model has result data.
I cannot understand how to designate ImageAndUser model in results.html.
Furthermore,
I wrote in serializer.py
from .forms import UserImageForm
from rest_framework import serializers
from .models import ImageAndUser
class ImageSerializer(serializers.ModelSerializer):
class Meta:
model = ImageAndUser
fields =(
'image',
'result',
'user',
'id',
)
read_only_fields = (
'user',
)
def create(self, attrs):
attrs['user'] = self.context.get('request').user
print(attrs)
return super(ImageSerializer,self).create(attrs)
Now,I wrote in views.py
def scoreresults(request):
d = {
'scoreresults': ImageAndUser.objects.result(),
}
return render(request, 'registration/accounts/results.html', d)
in urls.py
from django.conf.urls import url
from . import views
from django.views.generic import TemplateView
urlpatterns = [
url(r'^scoreresults$', TemplateView.as_view(template_name='registration/accounts/results.html'),
name='tcresults'),
]
But it did not work.
So,how can I fix this?
You have a lot of bits here but none of them are linked up to one another.
The main problem is your url; it does not point to your view. Instead of using a TemplateView declared in the url itself, you should point it to the view function you have defined:
url(r'^scoreresults$', views.scoreresults, name='tcresults')
You don't seem to be using the serializer at all; and you don't need it.