I am trying to create an addform to take input from a user and add it to my model, however, the form is not showing on the page, can someone tell me what I am doing wrong? Here is the code for the forms.py, views.py and add.html:
forms.py
class AddForm(forms.Form):
vehicle = forms.CharField(max_length=10)
carrier = forms.FloatField()
location = forms.ChoiceField(choices=[(1, 'Mathura Installation')])
customer_code = forms.FloatField()
zone = forms.ChoiceField(choices=[('NW', 'North West'),
('NCR', 'North Central'),
('SCR', 'South Central'),
('S', 'South'), ('N', 'North'),
('W', 'West'), ('E', 'East')
])
quantity = forms.FloatField()
load = forms.FloatField()
rtkm = forms.FloatField(label='RTKM')
rate = forms.ChoiceField(label='Rate ', widget=forms.RadioSelect, choices=[('avg', 'Average Rate'),
('user', 'User Rate')])
views.py
def add(request):
addform = forms.AddForm()
dict = {'addform': addform}
return render(request, 'add.html', dict)
urls.py
from django.contrib import admin
from django.urls import path
from searchapp import views
urlpatterns = [
path('', views.search, name='search'),
path('add/', views.add, name='add'),
path('admin/', admin.site.urls),
]
html - add.html
{% load staticfiles %}
<!DOCTYPE html>
<html lang="en">
<link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}">
<head>
<meta charset="UTF-8">
<title>Transport Portal - Add Page</title>
</head>
<body>
<div class="header">
<img src="{% static 'images/hpcl_logo.png' %}">
<h1>Transportation Portal</h1>
</div>
<div class="topnav">
<ul>
<li>Home</li>
<li>Search</li>
<li><a class="active" href="add.html">Add</a></li>
</ul>
</div>
<div class="add">
<form method="POST">
{% csrf_token %}
{{ addform.as_p }}
</form>
</div>
</body>
</html>
I think the problem is how you're getting there.
You have the following in your html
<li><a class="active" href="add.html">Add</a></li>
This is going to pick up the html page but you want href="{% url 'add' %}" which will pick up the django url.
Instead of dict use context
def add(request):
addform = forms.AddForm()
context= {'addform': addform}
return render(request, 'add.html', context)
Please read this. context
Related
I'm working with django ckeditor now and I can't display content that can be saved normally and is displayed in the admin panel. Content is always displayed as textarea
As you can see at the image, editor is working properly, also if i go to admin panel everything is OK, but if i want to display content of "body" ({{ form.body|safe}}), it will display only textarea of HTML code.
models.py
class Stage(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
game_id = models.ForeignKey(Game,
on_delete=models.CASCADE)
name = models.CharField(max_length=128)
sequence = models.IntegerField(null=False)
body = RichTextUploadingField(config_name='LeftFields', blank=True, null=True)
def get_questions(self):
return Question.objects.filter(stage_id = self.id)
def __str__(self):
return str(self.name)
forms.py
class StageForm(ModelForm):
class Meta:
model = Stage
fields = ['body','name']
widgets = {
'name': TextInput(attrs={
'class': "left_input",
'style': "width: 69.3%;",
}),
}
views.py
#login_required(login_url='/signin')
#user_passes_test(lambda u: u.is_staff)
def edit(request, gameid,id):
stage = Stage.objects.get(pk=id)
if request.method == 'POST':
form = StageForm(request.POST, instance=stage)
if form.is_valid():
form.save()
return redirect('/edit/' + gameid + '/' + id)
form = StageForm(instance=stage)
return render(request, "homeSuperuser/edit_stage.html", {'stage': stage, 'form': form,'gameid':gameid})
edit_stage.html
<!doctype html>
<html>
<head> {% load static %}
<link rel="stylesheet" href="{% static 'css/edit_pages.css' %}" />
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script type="text/javascript" src="{% static 'js/edit.js' %}"></script>
</head>
<body>
<div class="row" id="mainDIV">
<form id="main" method="post" action="{{ request.path }}">
{% csrf_token %}
<div class="divs">
<a>Název: </a>
{{ form.name}}
</div>
<div class="divs"><a>Kontent:</a>
{{ form.media }}
{{ form.body}}
</div>
<div class="div_cent"><input type="submit" value="Uložit" class="subm" /></div>
</form>
</div>
{{ form.body|safe}}
</body>
</html>
form.body is the field itself, so includes the HTML textarea markup.
Instead of
{{ form.body|safe}}
try
{{ form.body.value|safe}}
I am an absolute beginner in Django development & I am unable to send the data to my database via the POST method. Please guide me on what is wrong with my approach. My model worked perfectly and I can now access my desired table on my Django admin. The function that I have created in views.py always executes the else condition.
From views.py:
from django.shortcuts import render, HttpResponse, redirect
from app.models import Tbl_Feedback
def myform(request):
return render(request, 'form.html')
def getfeedback(request):
if request == "POST":
a = request.POST.get('a')
objTbl_Feedback = Tbl_Feedback(a="a")
objTbl_Feedback.save()
return redirect("/")
else:
return HttpResponse('Form Not Submitted')
From models.py:
from django.db import models
# Create your models here.
class Tbl_Feedback(models.Model):
fdbk = models.CharField(max_length=120)
From urls.py(app):
from django.contrib import admin
from django.urls import path
from app import views
urlpatterns = [
path('',views.myform,name="form"),
path('getfeedback', views.getfeedback, name="feedback")
]
From urls.py(project):
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path("", include("app.urls"))
]
Html:
<!DOCTYPE html>
<html lang="en">
{% load static %}
<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>Form</title>
{% load static %}
<link rel="stylesheet" href="{%static 'css.css'%}">
</head>
<body>
<form action="getfeedback" method="post" >
{% csrf_token %}
<div class="frame">
<div class="frame-header">FeedBack Please !</div>
<div class="frame-body">
<div class="form-element">
<div class="element-label"><label for="a">FeedBack</label></div>
<div class="element-controller">
<textarea name="a" id="a" cols="30" rows="5" class="controller-input"
autofocus="autofocus" maxlength="120"></textarea>
</div>
</div>
</div>
<div class="frame-footer"><button type="submit">Submit</button> </div>
</div>
</form>
</body>
</html>
In your getfeedback view there are two issues.
You need to write if request.method == 'POST':
"a" is not a field in your model
def getfeedback(request):
if request.method == "POST":
a = request.POST.get('a')
objTbl_Feedback = Tbl_Feedback(fdbk="a")
objTbl_Feedback.save()
return redirect("/")
else:
return HttpResponse('Form Not Submitted')
I am quite new in Django and stuck at specific point. I want to take user input from html that goes into database, process it with specific python script and return result to the same html page.
I want Users to enter score in "exam_score" line, then process that input with specific python script and then to output result to "uni_name_1_result". For now, python script that just prints 'Hello world' is enough, just want to understand the mythology of how it can be done.
Would appreciate any help.
models.py
from django.db import models
from django.core.validators import MaxValueValidator, MinValueValidator
# Create your models here.
class User(models.Model):
first_name = models.CharField(max_length=128)
last_name = models.CharField(max_length=128)
email = models.EmailField(max_length=254,unique=True)
exam_score = models.FloatField(null=True, validators=[MinValueValidator(0.0),MaxValueValidator(700)])
uni_name_1 = models.CharField(max_length=254)
uni_name_1_result = models.CharField(max_length=254)
forms.py
from django import forms
from django.core import validators
from ielts_app.models import User
class NewUserForm(forms.ModelForm):
# validations can be set here
class Meta():
model = User
fields = '__all__'
views.py
from django.shortcuts import render
# from ielts_app import forms
from ielts_app.forms import NewUserForm
# from django.http import HttpResponseRedirect
def index(request):
return render(request,'ielts_app/index.html')
def users(request):
form = NewUserForm()
if request.method == 'POST':
form = NewUserForm(request.POST)
if form.is_valid():
variable:form.cleaned_data
form.save(commit=True) # to save forum data (user data), commit=True to database
# return HttpResponseRedirect('/THANKS/')
return index(request) # return back to homeage after getting user data
else:
print("ERROR!")
return render(request,'ielts_app/users.html',{'form':form})
users.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Users</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<h1>Please Sign Up:</h1>
<div class="container">
<form method="POST">
{{ form.as_p }}
{% csrf_token %}
<input type="submit" class='btn btn-primary' value="Submit">
</form>
</div>
</body>
</html>
You can do following way.
from django import forms
from django.core import validators
from ielts_app.models import User
class NewUserForm(forms.ModelForm):
# validations can be set here
class Meta():
model = User
fields = ('exam_score',)
And in your user.html do this.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Users</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<h1>Please Sign Up:</h1>
<div class="container">
<form method="POST">
{% for field in form %}
{{ form.as_p }}
{{ field }}
{% endfor %}
{% csrf_token %}
<input type="submit" class='btn btn-primary' value="Submit">
</form>
</div>
</body>
</html>
It is better you rename your model to some other model name as it may collide with User Model given by django.
I'm making a simple webapp in django where a user can log in , choose one of the given category and post an article under the chosen category. But when I submit my django form to create a new post, it throws me " IntegrityError NOTNULL constraint failed ". I searched many solutions on internet and implemented the same but still it gives me the same error.
Please help me out as to how I fix this bug??
Here are the code snippets:
Models.py
class Category(models.Model):
name = models.CharField(max_length=128,unique=True)
slug = models.SlugField()
def save(self,*args,**kwargs):
self.slug = slugify(self.name)
super(Category,self).save(*args,**kwargs)
def __unicode__(self):
return self.name
class Post(models.Model):
category = models.ForeignKey(Category,null=True,blank=True)
title = models.CharField(max_length=128,null=True,blank=True)
content = models.TextField(blank=True,null=True)
def __unicode__(self):
return self.title
views.py
def index(request):
category_list = Category.objects.all()
context = {'category_list':category_list}
return render(request,'index.html',context)
def category(request,category_name_slug):
context = {}
try:
category = get_object_or_404(Category,slug=category_name_slug)
context['category_name'] = category.name
post = Post.objects.filter(category=category)
context['post'] = post
context['category'] = category
context['category_name_slug'] = category_name_slug
except Category.DoesNotExist:
pass
return render(request,'category.html',context)
#login_required
def create_post(request,category_name_slug):
created = False
instance = get_object_or_404(Category,slug=category_name_slug)
a = Post(category=instance)
if request.method == 'POST':
form = PostForm(request.POST,instance=a)
if form.is_valid():
post = form.save(commit=False)
post.save()
created = True
else:
print form.errors
else:
form = PostForm()
context={
'form':form,
'instance':instance,
'created':created
}
return render(request,"add_post.html",context)
forms.py
from django import forms
from app.models import Post,Category,UserProfile
from django.contrib.auth.models import User
class CategoryForm(forms.ModelForm):
name = forms.CharField(max_length=128, help_text="Please enter category")
slug = forms.CharField(widget=forms.HiddenInput(), required=False)
class Meta:
model = Category
fields = ('name',)
class PostForm(forms.ModelForm):
title = forms.CharField(max_length=128)
content = forms.CharField(widget=forms.Textarea)
class Meta:
model = Post
fields = ('title','content')
exclude = ('category',)
urls.py
from django.conf.urls import url
from django.contrib import admin
from app import views
urlpatterns = [
url(r'^$',views.index,name='index'),
url(r'^about/$',views.about,name='about'),
url(r'^add_category/$',views.add_category,name="add_category"),
url(r'^category/(?P<category_name_slug>[-\w]+)/create_post/$',views.create_post, name='create_post'),
url(r'^category/(?P<category_name_slug>[-\w]+)/$',views.category, name='category'),
url(r'^(?P<id>\d+)/$',views.post_detail,name='post'),
url(r'^register/$',views.register,name="register"),
url(r'^login/$',views.user_login,name="login"),
url(r'^logout/$',views.user_logout,name="logout"),
url(r'^(?P<username>[-\w]+)/$',views.view_profile,name="profile"),
]
templates/add_post.html
<html>
<head>
<title>Create Post</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
</head>
<body>
<h1>Create Post under {{ instance.name }}</h1>
{% if created %}
<strong>Post created successfully</strong>
<a href='/app/'>Home</a>
{% else %}
<form id='post_form' method='post' action='/app/category/{{ instance.slug }}/create_post/' enctype='multipart/form-data'>
{% csrf_token %}
{{ form.as_p }}
<input type="submit" name="submit" value="Create Post" />
</form>
{% endif %}
</body>
</html>
templates/category.html
<!DOCTYPE html>
<html>
<head>
<title>App</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
</head>
<body>
{% if category %}
<h1>{{ category_name }}</h1>
{% if post %}
<ul>
{% for poste in post %}
<li>{{ poste.title }}</li>
{% endfor %}
</ul>
{% else %}
<strong>No posts in this Category</strong>
{% endif %}
{% else %}
<strong>No Category found with {{ category_name }}</strong>
{% endif %}
<a href='/app/category/{{ category.slug }}/create_post/'>Create post</a>
</body>
</html>
It's shows me an error at " post.save() " line in views.py.
I'm writing a simple chat with ajax and I have a problem with JSON. I need username instead of id.
JSON seems like:
[{"pk": 41, "model": "chat.post", "fields": {"timestamp": "2012-01-27 22:14:46", "user": 1, "text": "weq"}}]`
I need replace "user": 1 to "user": username.
How I can do it?
My model:
from django.db import models
from django.contrib.auth.models import User
class Post(models.Model):
timestamp = models.DateTimeField(auto_now_add=True)
text = models.TextField()
user = models.ForeignKey(User)
class Meta:
ordering = ['-id']
def __unicode__(self):
return "[%s] %s by user: %s" % (
self.timestamp.strftime("%Y-%m-%d %H:%M:%S"),
self.text,
self.user
)
My view:
# -*- coding: utf-8 -*-
#!/usr/bin/env python
from django.http import HttpResponse
from django.core import serializers
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.template import RequestContext
from django.shortcuts import render_to_response
from live.chat.models import Post
#login_required
def updates_after(request, id):
response = HttpResponse()
response['Content-Type'] = "text/javascript"
response.write(serializers.serialize("json",
Post.objects.filter(pk__gt=id)))
# __gt - greaten then > id
return response
#login_required
def saymessage(request):
if request.method == 'POST':
if "text" in request.POST:
text = request.POST["text"]
user = request.user
message = Post()
message.user, message.text = user, text
message.save()
return HttpResponseRedirect('/')
else:
pass
JSON response example:
[
{
"pk": 42,
"model": "chat.post",
"fields": {
"timestamp": "2012-01-28 18:08:44",
"user": 1,
"text": "dasd"
}
}
]
My template:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<!-- Always force latest IE rendering engine (even in intranet) & Chrome Frame
Remove this if you use the .htaccess -->
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<title>templates</title>
<meta name="description" content="" />
<script type="text/javascript" language="javascript" src="/media/js/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
function update() {
update_holder = $("#update_holder");
most_recent = update_holder.find("div:first");
$.getJSON("/live/updates-after/" + most_recent.attr('id') + "/",
function(data) {
cycle_class = most_recent.hasClass("odd") ? "even" : "odd";
jQuery.each(data, function(){
update_holder.prepend('<div id="' + this.pk
+ '" class="update ' + cycle_class
+ '"><div class="timestamp">'
+ this.fields.timestamp
+ '</div><div class="user">'
+ this.fields.user
+ '</div><div class="text">'
+ this.fields.text
+ '</div><div class="clear"></div></div>'
);
cycle_class = (cycle_class == "odd") ? "even" : "odd";
});
}
);
}
$(document).ready(function() {
setInterval("update()", 10000);
})
</script>
<link rel="stylesheet" type="text/css" href="/media/css/main.css" />
</head>
<body>
{% block content %}
<div>
<header>
<h1>Live Update site</h1>
<p>Содержимое обновляется автоматически</p>
</header>
{% if object_list %}
<div id="update_holder">
{% for object in object_list %}
<div class="update {% cycle even,odd %}" id="{{ object.id }}">
<div class="timestamp">
{{ object.timestamp|date:"Y-m-d H:i:s" }}
</div>
<div class="user">
{{ object.user }}
</div>
<div class="text">
{{ object.text|linebreaksbr }}
</div>
<div class="clear"></div>
</div>
{% endfor %}
</div>
{% else %}
<p>Нет обновлений</p>
{% endif %}
</div>
<form enctype="multipart/form-data" action="{% url chat.views.saymessage %}" method="post">{% csrf_token %}
Введите текст сообщения: <input type="text" name="text" id="text">
<input type="submit" name="submit" value="Отправить">
</form>
{% endblock %}
</body>
</html>
Update:
I figure out this problem, we need using natural_key(), and overrive this method in user manager class, add next code to models.py:
class UserManager(models.Manager):
def unatural_key(self):
return self.username
User.natural_key = unatural_key
And dont forget add argument use_natural_keys=True to serializers.serialize()
You might want to look into Natural Keys. Natural keys allow you to specify what foreign key fields are serialized to. By constructing a primary key for your user, you can have the username in the serialization, instead of the ID.
You should change this method to
def __unicode__(self):
return "[%s] %s by user: %s" % (
self.timestamp.strftime("%Y-%m-%d %H:%M:%S"),
self.text,
self.user.username
)
But this is a dirty solution. Your view updates_after is very ugly. I would change updates_after. See a similar view