Value matching query does not exist - python

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.

Related

model forms were not generated automatically using django model forms

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.

why data in django framework is not storing in the database while i have done with all the migrations?

I am learning Django I have done everything that was explained in javatpoint (learning website),i have done all the migrations ,i have executed python manage.pymigrate,makemigrations,sqlmigrate appname 0001_initial everything , the form is created successfully but the data uploading is not storing in the database.
i just want the data (first name and lastname ) to be stored to the employee table and the data to be downloaded as csv file.
views.py
from django.http import HttpResponse
from django.shortcuts import render
# Create your views here.
from django.shortcuts import render, redirect
from name.forms import EmployeeForm
from name.models import Employee
import csv
def index(request):
if request.method == "POST":
form = EmployeeForm(request.POST)
if form.is_valid():
try:
return redirect('/')
except:
pass
else:
form = EmployeeForm()
return render(request,'index.html',{'form':form})
def getfile(request):
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="file.csv"'
employees = Employee.objects.all()
writer = csv.writer(response)
for employee in employees:
writer.writerow([employee.id,employee.first_name,employee.last_name])
return response
forms.py
from django import forms
from name.models import Employee
class EmployeeForm(forms.ModelForm):
class Meta:
model = Employee
fields = "__all__"
models.py
from __future__ import unicode_literals
from django.db import models
class Employee(models.Model):
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=30)
class Meta:
db_table = "employee"
script.js
alert("Hello, Welcome to Javatpoint");
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Index</title>
</head>
<body>
<form method="POST" class="post-form" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default">Save</button>
</form>
</body>
</html>
style.css
h1{
color:red;
}
urls.py
from django.contrib import admin
from django.urls import path
from name import views
urlpatterns = [
path('admin/', admin.site.urls),
path('index/', views.index),
path('csv',views.getfile)
]
0001_initial.py(after migration)
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Employee',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('first_name', models.CharField(max_length=20)),
('last_name', models.CharField(max_length=30)),
],
options={
'db_table': 'employee',
},
),
]
Django ModelForms have a save method to actually insert the form data into the database.
So you just need to alter part of your view to include this statement, as follows:
if request.method == "POST":
form = EmployeeForm(request.POST)
if form.is_valid():
try:
form.save()
return redirect('/')
except:
pass

error in database saving

I am trying to create a form and save data to database when the submit button is clicked. But the data is not getting saved to database. i dont get any error. I am django 1.11. I referred to few stackoverflow question and that answers doesnt solve my issue. Could someone help in fixing it? Thanks in advance.
model.py
from __future__ import unicode_literals
from django.db import models
class NameForm(models.Model):
your_name = models.CharField(max_length=200)
views.py
from __future__ import unicode_literals
from django.shortcuts import render
from django.http import HttpResponseRedirect, HttpResponse
from django.views import generic
from django.template.response import TemplateResponse
from home.models import NameForm
from .forms import NameForm
class NameView(generic.View):
model_class = NameForm
initial = {'key': 'value'}
template_name = 'home/name.html'
def get(self, request, *args, **kwargs):
model = self.model_class()
return render(request, self.template_name, {'model': NameForm})
def post(self, request, *args, **kwargs):
if request.method == 'POST':
form = NameForm(request.POST)
if form.is_valid():
return HttpResponseRedirect('thanks/')
if form.is_valid():
form.save()
else:
form = NameForm()
return render(request, 'name.html', {'form': form})
urls.py
from django.conf.urls import url
from . import views
app_name = 'home'
urlpatterns = [
url(r'^$', views.NameView.as_view(), name='name'),
url(r'^your-name/$', views.NameView.as_view(), name='name'),
url(r'^your-name/thanks/$', views.NameView.as_view(), name='name'),
]
home/name.html
<form action="your-name/" method="post">
{% csrf_token %}
<label for="your_name">Your name: </label>
<input id="your_name" type="text" name="your_name" value="{{ current_name }}">
<input type="submit" value="OK">
</form>
forms.py
from .models import NameForm
from django import forms
class NameForm(forms.Form):
your_name = forms.CharField(label='Your name', max_length=100)
class Meta:
model = NameForm
fields = ['your_name']
You'll get by much easier if you use the batteries included in Django. Here's a list of the fixes in the version below...
Don't reuse names. NameModel is a model, NameForm is a form. (However, you'd usually really elide Model from a model name – it's just that Name sounded like a silly name for a model...)
Use ModelForms when you're managing models. They automatically validate input against your models, let you save the models easily, etc.
Use the CreateView/UpdateView/FormView generic views to deal with model creation, updates, inputs, etc. No code needed, just configuration!
Don't template forms yourself. form.as_p will get you a barebones form; form.your_name would render that field, etc.
Just a fair warning: this is dry-coded, so there might be typos or other small silliness.
models.py
from django.db import models
class NameModel(models.Model):
your_name = models.CharField(max_length=200)
forms.py
from django import forms
class NameForm(forms.ModelForm):
class Meta:
model = NameModel
fields = ['your_name']
views.py
from django.views.generic import CreateView
from django.urls import reverse_lazy
from .models import NameModel
from .forms import NameForm
class NameView(CreateView):
model_class = NameModel
form_class = NameForm
success_url = reverse_lazy('name-thanks')
initial = {'your_name': 'value'}
template_name = 'home/name.html'
urls.py
from django.conf.urls import url
from django.views.generic import FormView
from .views import NameView
app_name = 'home'
urlpatterns = [
url(r'^$', NameView.as_view(), name='name'),
url(r'^your-name/thanks/$', TemplateView.as_view({'template_name': 'home/thanks.html'}), name='name-thanks'),
]
home/name.html
<form action="your-name/" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="OK">
</form>
That's beacuse you've been redirected (return HttpResponseRedirect('thanks/')) before save
Your version:
if form.is_valid():
return HttpResponseRedirect('thanks/')
if form.is_valid():
form.save()
else:
...
And the version you seek, with redirect only after form saving and removed redundant second form.is_valid() check:
if form.is_valid():
form.save()
return HttpResponseRedirect('thanks/')
else:
...

How can I show model data's contents in html file?

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.

DJango - My forms.py elements are not showing up in the html template

I am a newbie for Django and working on a project. I am stucked with setting up a forms.py and integrate the same with my template. I did all the required things with the help of all sort of tutorial I got online but I was unable to see the fields I declared in form on the HTML Page. Below is the code I used for each of the module. It would be great if anyone can help me out with this.
models.py
from django.db import models
class EarlyBirds(models.Model):
name = models.CharField(max_length=200)
email = models.CharField(max_length=200)
contact_number = models.IntegerField()
def __str__(self):
return '%s - %s' % (self.name, self.email)
views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.template import RequestContext, loader
from django.shortcuts import render_to_response
from .forms import EarlyBirdsForm
from .models import EarlyBirds
def register(request):
context = RequestContext(request)
success=''
if request.method == 'POST':
form = EarlyBirdsForm(request.POST)
if form.is_valid():
name = request.POST.get('name','')
email = request.POST.get('email','')
number = request.POST.get('number','')
if email:
email_exist = EarlyBirds.objects.filter(email=email)
if email_exist:
success = 'Thankyou for your intrest! This email is already registered with us. We will get back to you soon.'
else:
eb_obj = EarlyBirds(name=name,email=email,contact_number=number)
eb_obj.save()
success = 'Thankyou for your intrest! We will get back to you soon.'
else:
success = 'Please fill out the required fields'
else:
success = form.errors
else:
form = EarlyBirdsForm()
return render_to_response('ComingSoon.html', {'success':success}, context)
forms.py
from django import forms
from django.forms import ModelForm
from app_name.models import EarlyBirds
class EarlyBirdsForm(forms.Form):
name = forms.CharField(required=True,max_length=100)
email = forms.CharField(required=True,max_length=100)
number = forms.IntegerField(required=True)
class Meta:
model = EarlyBirds
fields = ("name", "email", "number")
template
<html xmlns="http://www.w3.org/1999/xhtml">
<body align="center">
<form method="POST" action="{%url 'comingsoon:register'%}">
{% csrf_token %}
<div class="header-blog-comingSoon" align="center">
<!--<form method="post">
<span>{{ form.as_p }}</span>
<br/>
<span><button class="comingsoon-Reg" type="submit">Register</button></span>
<br/><br/>
<br/><label class="successLabel">{{success}}</label>
</div>
</form>
</body>
</html>
project.urls.py
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^ComingSoon/', include('app_name.urls', namespace="comingsoon")),
url(r'^admin/', include(admin.site.urls)),
]
When I try to execute this code, the all I was able to see in the "Register" button on my html page. The three text fields for Name, Email and Contact number were missing. Please let me know what I am missing over here.
You forgot to add the form to your context:
def register(request):
...
return render_to_response('ComingSoon.html', {'success':success, 'form': form}, context)
Maybe you should try writing your form like this:
class EarlyBirdsForm(forms.ModelForm):
class Meta:
model = EarlyBirds
fields = '__all__'
Much easier and simpler. Since you're using all the attributes in the model, might as well connect the form directly with the model.
And César Bustíos said it right. You didn't add the form in the context dictionary for your template.

Categories