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.
Related
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 ().
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 get my head around Django and understand how I can show results of Python functions in Django's templates. As a simple example, let's say I have a model with a list of questions and I want to use a function to return the number of questions and for this result to be shown in a template. How can I do it?
I tried to do it below but it doesn't work!
Thanks in advance
models.py
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length=200)
views.py
from django.shortcuts import render
from django_app import models
from django.views.generic import ListView
from django_app.models import Question
class TestListView(ListView):
model = Question
context_object_name = 'test_details'
def Test(self):
return Question.objects.count()
urls.py
from django.urls import path
from django_app import views
from django_app.views import TestListView
app_name = 'django_app'
urlpatterns = [
path('',TestListView.as_view(), name='Test'),
]
question_list.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
{% for item in test_details %}
{{Test}}
{{item.question_text}}
{% endfor %}
</body>
</html>
You can override the get_context_data method of your view to add extra variable into your context
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['Test'] = Question.objects.count()
return context
You can also get the count of the questions without having to alter the context. You can get it from the queryset
{{ test_details.count }}
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 have two models: User and UserProfile the first one contains fields like username, first_name, etc. And the second one contains all extra fields that Django admin does not provide but I need it, like: reputation. My question is, how to get all data from both models?
urls.py
from django.conf.urls import patterns, include, url
from userprofiles.views import UserDetailView
urlpatterns = patterns('',
url(r'^profile/username/(?P<slug>[\w.#+-]+)/$', UserDetailView.as_view()),
)
models.py
class UserProfile(models.Model):
user = models.OneToOneField(User)
reputation = models.IntegerField(default=1, null=True)
views.py
from django.views.generic.detail import DetailView
# from .models import UserProfile (This contains custom fields)
from django.contrib.auth.models import User
class UserDetailView(DetailView):
model = User
slug_field = 'username'
def get_template_names(self):
return 'profile.html'
profile.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Profile</title>
</head>
<body>
<section>
{{user.username}}<br>
{{userprofile.reputation}}<br>
</section>
</body>
</html>
At this point I'm getting only username without reputation in my profile.html when I access to: http://localhost:8000/profile/username/MY_USERNAME/
Only the User object is present in the context. Use the reverse relationship to access the profile from the User model:
{{ user.userprofile.reputation }}
More info in the docs