model forms were not generated automatically using django model forms - python

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.

Related

Value matching query does not exist

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.

Django form are not working in html template its just show button

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__'

NoReverseMatch at /add_post

I have been working on a blog site using django and I made a way to add post within the home page without going to the admin page but when I post using the new way I get this error
This is my models.py file
from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse
class Post(models.Model):
title = models.CharField(max_length=255)
title_tag = models.CharField(max_length=255)
author = models.ForeignKey(User, on_delete=models.CASCADE)
body = models.TextField(max_length=3500)
def __str__(self):
return (self.title + " | " + str(self.author))
def get_absolute_url(self):
return reverse("article-view", args=(str(self.id)))
This is the views.py file
from django.views.generic import ListView, DetailView, CreateView
from .models import Post
class HomeView(ListView):
model = Post
template_name = "home.html"
class ArticleDetailView(DetailView):
model = Post
template_name = "detail_view.html"
class AddPostView(CreateView):
model = Post
template_name = "add_post.html"
fields = "__all__"
This is the polls/urls.py
from django.urls import path
from .views import HomeView, ArticleDetailView, AddPostView
urlpatterns = [
path('', HomeView.as_view(), name='home'),
path('article/<int:pk>', ArticleDetailView.as_view(), name='article-view'),
path('add_post/', AddPostView.as_view(), name='add_post'),
]
This is the add_post.html file
{% extends 'base.html' %}
{% block content %}
<head>
<title>Adding Post</title>
</head>
<h1>Add Blog Posts</h1>
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<button class="btn btn-secondary">Post</button>
</form>
{% endblock %}
Thank you.
Okay, so it looks like this is caused by the model's get_absolute_url reverse args=(). I changed the below code in models.py from:
def get_absolute_url(self):
return reverse("article-view", args=(str(self.id)))
Into
def get_absolute_url(self):
return reverse("article-view", args=[self.id])
The problem seems to be args=(), it is iterating over the str(self.id). So id=10 would actually be returned as a tuple (1,0). I also removed the str() around the self.id since the URL takes in an int.

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 Contact Form using ModelForm

I am trying to create a contact form that will both email and store the message. I think I got the model.py, forms.py and admin.py right, and I am able to create and store (not email) a message from the admin. But I am struggling with the view.py that has to both email and store the message.
model.py:
from django.db import models
from django.contrib import admin
class Contact(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField()
message = models.TextField(max_length=10)
date_created = models.DateField(verbose_name="Created on date", auto_now_add="True")
class ContactAdmin(admin.ModelAdmin):
list_display = ('name', 'email', 'message', 'date_created')
forms.py:
from django import forms
from .models import Contact
class ContactForm(forms.Form):
name = forms.CharField()
email = forms.EmailField()
When it comes to the views.py, I need some guidance in order to put together the code for the def contact(request):. I think I will have to include these modules:
from django.conf import settings
from django.shortcuts import render, HttpResponseRedirect, HttpResponse, Http404
from django.core.mail import send_mail
from .forms import ContactForm
from .models import Contact
When it comes to the template part, I am not sure on how to use the template tags to render the contact form in html.
So, I need help to figure out the correct view and template code.. I am of course open to suggestions for the rest of the code as well - As you might guessed, this is my first real Django app.
Thank you!
Something like this:
I would use a django ModelForm to generate the form:
class ContactForm(forms.ModelForm):
class Meta:
model = Contact
exclude = ('date_created', )
Docs: https://docs.djangoproject.com/en/1.7/topics/forms/modelforms/#modelform
And FormView for the actual view:
from django.conf import settings
from django.core.mail import send_mail
from django.views.generic import FormView
from .forms import ContactForm
class ContactFormView(FormView):
form_class = ContactForm
template_name = "email_form.html"
success_url = '/email-sent/'
def form_valid(self, form):
message = "{name} / {email} said: ".format(
name=form.cleaned_data.get('name'),
email=form.cleaned_data.get('email'))
message += "\n\n{0}".format(form.cleaned_data.get('message'))
send_mail(
subject=form.cleaned_data.get('subject').strip(),
message=message,
from_email='contact-form#myapp.com',
recipient_list=[settings.LIST_OF_EMAIL_RECIPIENTS],
)
form.save()
return super(ContactFormView, self).form_valid(form)
Docs: https://docs.djangoproject.com/en/1.7/ref/class-based-views/generic-editing/#formview
And your template:
{% extends 'base.html' %}
{% block title %}Send an email{% endblock %}
{% block content %}
<div class="row">
<div class="span6">
<h1>Send an email</h1>
<form action="." method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit" />
</form>
</div>
</div>
{% endblock %}
{% block extrajs %}
<script src="{{ STATIC_URL }}js/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$(function() {
$('#id_name').focus()
});
</script>
{% endblock %}
Docs: https://docs.djangoproject.com/en/1.7/topics/forms/#the-template

Categories