I have a model in which a unique serial number is generated, and there is a quantity field in which the user can select how many parts they'd like made. Think of it like a shopping order. I'd like that if the user selects a quantity of more than one, a serial number be assigned to each individual part.
Models:
from __future__ import unicode_literals
from tande.models import Project, Person
from django.db import models
from django.utils import timezone
from django.utils.text import slugify
from django.core.exceptions import NON_FIELD_ERRORS, ValidationError
from django.utils.translation import ugettext_lazy as _
from django.core.urlresolvers import reverse
from django.db.models.signals import pre_save
from django.conf import settings
# Create your models here.
class buildrisk(models.Model):
risk = models.CharField(max_length=20, default = 'Select Risk')
def __unicode__ (self):
return self.risk
class sens(models.Model):
sens = models.CharField(max_length=20, default = 'Select Sensitivity')
def __unicode__ (self):
return self.sens
class MOI(models.Model):
method = models.CharField(max_length=20, default = 'Select Method')
def __unicode__ (self):
return self.method
def number():
no = PartRequest.objects.count()
if no == None:
return "PR00001"
else:
return "PR00" + str(no + 100)
def snumber():
no = PartRequest.objects.count()
add = sum(map(int, str(no)))
if no == None:
return "SN00001"
else:
return "SN00" + str(no + 100 + add)
# while n:
# sn, n = sn + n % 10, n // 10
# return sn
class PartRequest(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
part_request_number = models.CharField(_('Part Request Number'),max_length=10, default = number)
serialnumber = models.CharField(_('Serial Number'),max_length=10, default= snumber)
project_manager = models.ForeignKey(Person, related_name = 'Manager', null = True)
requester = models.ForeignKey(Person, related_name = 'Requester', null = True) #drop down
project_id = models.ForeignKey(Project, related_name = 'Project', null=True)
ordernumber = models.PositiveIntegerField(_('Order Number'), default=0)
description = models.CharField(_('Description'), max_length=500)
quantityrequired = models.PositiveIntegerField(_('Quantity'), default=0)
sensitivity = models.ForeignKey(sens, related_name='sensitivity', null=True) #drop down
identification_method = models.ForeignKey(MOI, related_name= 'MOI', null=True)
build_risk = models.ForeignKey(buildrisk, related_name= 'Risk', null=True)
daterequired = models.DateField(_('Date Required'), default = '04/08/16')
slug = models.SlugField(unique=True, null=True)
def __str__(self):
return unicode(self.requester)
def get_absolute_url(self):
return "/buildpage/%s/" %(self.slug)
#return ("buildpage:page3", kwargs = {"slug": self.slug})
def create_slug(instance, new_slug=None):
slug = slugify(instance.part_request_number)
if new_slug is not None:
slug = new_slug
qs = PartRequest.objects.filter(slug=slug).order_by("-id")
exists = qs.exists()
if exists:
new_slug = "%s-%s" %(slug, qs.first().id)
return create_slug(instance, new_slug=new_slug)
return slug
def pre_save_receiver(sender, instance, *args, **kwargs):
if not instance.slug:
instance.slug = create_slug(instance)
pre_save.connect(pre_save_receiver, sender = PartRequest)
Views:
from django.shortcuts import render, get_object_or_404, redirect, get_object_or_404
from django.contrib import messages
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.template import RequestContext, loader
from django.contrib.auth.decorators import login_required
from .forms import PartRequestForm
from .models import PartRequest
from tande.models import Project, Person
# Create your views here.
#login_required
def home(request):
latest_project_list = Project.objects.all()
context = {'latest_project_list': latest_project_list}
return render(request, 'buildpage/home.html', context)
def partrequestinfo(request):
if not request.user.is_staff or not request.user.is_superuser:
raise Http404
req_form = PartRequestForm(request.POST or None, request.FILES or None)
if req_form.is_valid():
instance = req_form.save(commit=False)
instance.user = request.user
print request.POST
print req_form.cleaned_data.get("requester")
print instance
instance.save()
messages.success(request, "Successfully Created")
return HttpResponseRedirect(instance.get_absolute_url())
else:
context = {
"req_form": req_form
}
return render(request, "buildpage/partrequestinfo.html", context)
def partrequestdetail(request, slug=None):
print "in partrequestdetail function"
instance = get_object_or_404(PartRequest, slug=slug)
context = {
"project_id": instance.project_id,
"instance": instance,
}
return render(request, 'buildpage/partrequestdetail.html', context)
def partrequestupdate(request, slug=None):
if not request.user.is_staff or not request.user.is_superuser:
raise Http404
instance = get_object_or_404(PartRequest, slug=slug)
req_form = PartRequestForm(request.POST or None, request.FILES or None, instance=instance)
if req_form.is_valid():
instance = req_form.save(commit=False)
print request.POST
print req_form.cleaned_data.get("requester")
print instance
instance.save()
messages.success(request, "Saved")
return HttpResponseRedirect(instance.get_absolute_url())
context = {
"project_id": instance.project_id,
"instance": instance,
"req_form": req_form,
}
return render(request, 'buildpage/partrequestinfo.html', context)
def partrequestdelete(request, slug=None):
if not request.user.is_staff or not request.user.is_superuser:
raise Http404
instance = get_object_or_404(PartRequest, slug=slug)
messages.success(request, "Successfully Deleted")
return redirect("buildpage:home")
def preparebuildlist(request, slug=None):
return render(request, 'buildpage/preparebuildlist.html')
I can't really understand your models, but I think what you need (if you don't already have it) is a Part model. Have one field in the Part model be the serial number of the part, which can be automatically generated if you want, and so when a user requests X number of parts you can just create and save X Part objects.
Related
I am working on a Todo list which has seperate users with their own list.
Initially I had the models.py as:
from django.db import models
from django.contrib.auth.models import User
class Todo(models.Model):
text = models.CharField(max_length=40, default='Test User')
complete = models.BooleanField(default = False)
task_priority = models.CharField(max_length=40, default='high')
def __str__(self):
return self.text
But then when im trying to link single user with its own set of todotask(text field) and its priorites and status.
I added one to one field like this:
from django.db import models
from django.contrib.auth.models import User
class Todo(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE,primary_key='user_id') #new
text = models.CharField(max_length=40, default='Test User')
complete = models.BooleanField(default = False)
task_priority = models.CharField(max_length=40, default='high')
def __str__(self):
return self.text
It threw an error like this:
FieldError at /
Cannot resolve keyword 'id' into field. Choices are: complete, task_priority, text, user, user_id
I didnt completely understand the concept of one to one fields and looking at the tutorials online im confused weather I need to make another table and link it to the Todo table or add another field with some primary key?
Help me understand this concept.
Thanks in advance.
EDIT:
views.py file:
from django.shortcuts import render, redirect
from .models import Todo
from .form import TodoForm,ContactForm
import datetime
from django.conf import settings
from django.utils import timezone
from django.views.decorators.http import require_POST
from django.core.mail import send_mail, BadHeaderError
from django.http import HttpResponse, HttpResponseRedirect
import json
def index(request):
todo_list = Todo.objects.order_by('id')
form = TodoForm()
mydate = datetime.datetime.now()
context = {'todo_list': todo_list, 'form': form, 'mydate':mydate}
return render(request,'todo/index.html',context)
def login(request):
return render(request, 'todo/login.html')
#require_POST
def addTodo(request):
form = TodoForm(request.POST)
text_input = form.get_cleaned_data['text']
priority_input = form.get_cleaned_data['task_priority']
if form.is_valid():
new_todo = Todo(text = text_input, task_priority = priority_input)
# new_todo = Todo(text = request.POST['text'])
new_todo.save()
return redirect('index')
def completeTodo(request, todo_id):
todo = Todo.objects.get(pk=todo_id)
todo.complete = True
todo.save()
return redirect('index')
def deleteCompleted(request):
Todo.objects.filter(complete__exact=True).delete()
return redirect('index')
def deleteAll(request):
Todo.objects.all().delete()
return redirect('index')
def emailView(request):
todo = Todo.objects.all();
task_list = []
status_list = []
for item in todo:
stritem=str(item)
task_list.append(stritem)
if item.complete == True:
status_list.append('complete')
else:
status_list.append('incomplete')
if request.method == 'GET':
form = ContactForm()
else:
form = ContactForm(request.POST)
if form.is_valid():
from_email = form.cleaned_data['from_email']
message = form.cleaned_data['message']
#maillist = Todo.objects.all()
email_list=dict(zip(task_list,status_list))
strlist = json.dumps(email_list)
content = message + strlist
try:
send_mail('Todo List', content ,settings.EMAIL_HOST_USER,[from_email])
except BadHeaderError:
return HttpResponse('Invalid header found.')
return redirect('success')
return render(request, "email.html", {'form': form})
def successView(request):
return HttpResponse('Success! Thank you for your message.')
New models.py:
from django.db import models
from django.contrib.auth.models import User
class Todo(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
text = models.CharField(max_length=40, default="")
complete = models.BooleanField(default = False)
task_priority = models.CharField(max_length=40, default='high')
def __str__(self):
return self.text
Encountered
IntegrityError at /add NOT NULL constraint failed: todo_todo.user_id
This:
user = models.OneToOneField(User,on_delete=models.CASCADE,primary_key='user_id')
isn't at all doing what you think it is. primary_key expects a boolean, not a field name, and isn't to do with the relationship at all. Because the string 'user_id' is not empty, this is being interpreted as True, and is equivalent to:
user = models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True)
which means that user is now the primary key for the Todo model. This is not what you want.
Remove that primary_key clause.
i spend a lot of hours searching for such an error but didn't found anything,
as you know Djangov2.00 requires you to set on_delete=*** with ForeignKey and here i can't do a ForeignKey anymore.
my Models.py
from django.db import models
class makereport(models.Model):
Name = models.CharField(max_length=50)
VID = models.IntegerField()
Callsign = models.CharField(max_length=6)
Date = models.DateField(default='yy-mm-dd')
SelectAward = models.CharField(max_length=50, choices=(('1', 'Division Online Day'), ('2', 'Pilot Event'), ('3', 'ATC Event'), ('4', 'Pilot Event')))
done = models.ForeignKey('reports', on_delete=models.CASCADE)
# reports.ATC = reports.ATC + 1
def __str__(self):
return self.Name
class reports (models.Model):
Name = models.CharField(max_length=50)
VID = models.IntegerField()
DivisionOnline = models.IntegerField(default=0)
ATCEvent = models.IntegerField(default=0)
PilotEvent = models.IntegerField(default=0)
PilotSupport = models.IntegerField(default=0)
ATC = 0
def __str__(self):
return self.Name
and the Error
django.db.utils.IntegrityError: Not Null constraint failed: report_makereport.done_id
i don't know what to do with that id ,versions before V2 was working.
Views.py
from django.db import IntegrityError
from django.http import HttpResponse, request
from django.shortcuts import render, redirect
# Create your views here.
from django.views import View
from report import models
from report.forms import RepForm
from report.models import makereport, reports
class home(View):
def get(self,request):
form = RepForm()
reps = reports.objects.all()
rep = makereport.objects.all()
context = {
'rep':rep,
'form' : form,
'reps':reps
}
return render(request,'home.html',context)
def post(self,request):
form = RepForm(request.POST)
if form.is_valid():
repo = makereport()
repo.Name = form.cleaned_data['Name']
repo.VID = form.cleaned_data['VID']
repo.Callsign = form.cleaned_data['Callsign']
repo.Date = form.cleaned_data['Date']
repo.SelectAward = form.cleaned_data['SelectAward']
repo.done = None
try:
repo.save()
return redirect('/')
except IntegrityError:
context = {'form':form,
'error_msg': 'Error,Please Check your Information'}
return render(request, 'home.html', context)
else:
return self.get(request)
The way you set up this field done = models.ForeignKey('reports', on_delete=models.CASCADE) means that this field can't remain empty nor null.
When you createe a makereport object, this field must have a report instance, if not IntegrityError: Not Null will raise
In case of creating makereport object without a report instance. the following can do it
done = models.ForeignKey('reports',
on_delete=models.SET_NULL,null=True,blank=True)
in your views, try this:
''' codes '''
repo.done = None
repo.save()
I will be really grateful if anyone can help to resolve the issue below.
I have the following Django project coding. The problem is: when the browser was given "/posts/remove/<post_id>/" or "/posts/edit/(<post_id>/" as the url, it will allow the second user (not owner) to perform the remove and edit jobs, respectively.
How can I allow only the owner of a new post to edit or delete the post?
account.models.py:
from django.db import models
from django.conf import settings
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL)
def __str__(self):
return 'Profile for user {}'.format(self.user.username)
posts.models.py:
from django.db import models
from django.conf import settings
from django.utils import timezone
from django.utils.text import slugify
from django.core.urlresolvers import reverse
from taggit.managers import TaggableManager
class PublishedManager(models.Manager):
def get_queryset(self):
return super(PublishedManager, self).get_queryset().filter(status='published')
class Post(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
related_name='posts_created')
title = models.CharField(max_length=200)
slug = models.SlugField(max_length=200, unique_for_date='created')
image = models.ImageField(upload_to='images/%Y/%m/%d', null=True, blank=True)
description = models.TextField(blank=True)
created = models.DateTimeField(default=timezone.now,
db_index=True)
updated = models.DateTimeField(auto_now=True)
users_like = models.ManyToManyField(settings.AUTH_USER_MODEL,
related_name='posts_voted',
blank=True)
status = models.CharField(max_length=10, default='published')
objects = models.Manager() # The default manager.
published = PublishedManager() # The Dahl-specific manager.
tags = TaggableManager()
class Meta:
ordering = ('-created',)
def __str__(self):
return self.title
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
super(Post, self).save(*args, **kwargs)
def get_absolute_url(self):
return reverse('posts:detail', args=[self.id, self.slug])
posts.view.py:
from django.views.decorators.http import require_POST
from django.shortcuts import render, redirect, get_object_or_404, render_to_response
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.conf import settings
from django.core.context_processors import csrf
from .forms import PostCreateForm, EmailPostForm, CommentForm, SearchForm
from .models import Post
from actions.utils import create_action
#login_required
def post_create(request):
"""
View for creating a new post.
"""
if request.method == 'POST':
# form is sent
form = PostCreateForm(data=request.POST, files=request.FILES)
if form.is_valid():
cd = form.cleaned_data
new_item = form.save(commit=False)
# assign current user to the item
new_item.user = request.user
tags = form.cleaned_data['tags']
new_item.save()
for tag in tags:
new_item.tags.add(tag)
new_item.save()
create_action(request.user, 'created a post:', new_item)
messages.success(request, 'Post added successfully')
form = PostCreateForm()
else:
messages.error(request, 'Error adding new post')
else:
# build form
form = PostCreateForm(data=request.GET)
return render(request, 'posts/post/create.html', {'section': 'posts',
'form': form})
#login_required
def post_remove(request, post_id):
Post.objects.filter(id=post_id).delete()
return redirect('posts:mypost')
#login_required
def post_edit(request, post_id):
item = Post.objects.get(pk=post_id)
if request.method == 'POST':
form = PostCreateForm(request.POST, instance=item)
if form.is_valid():
form.save()
return redirect('posts:mypost')
else:
form = PostCreateForm(instance=item)
args = {}
args.update(csrf(request))
args['form'] = form
return render_to_response('posts/post/post_edit.html', args)
posts.urls.py
from django.conf.urls import url
from . import views
from .feeds import LatestPostsFeed
urlpatterns = [
url(r'^create/$', views.post_create, name='create'),
url(r'^remove/(?P<post_id>\d+)/$', views.post_remove, name='post_remove'),
url(r'^edit/(?P<post_id>\d+)/$', views.post_edit, name='post_edit'),
]
Add request.user == item.user check inside your method.
#login_required
def post_remove(request, post_id):
item = Post.objects.get(pk=post_id)
if request.user == item.user:
Post.objects.filter(id=post_id).delete()
return redirect('posts:mypost')
#login_required
def post_edit(request, post_id):
item = Post.objects.get(pk=post_id)
if request.user == item.user:
...
//write your code here
I am trying to have users delete and edit post they create. I was told "Post.user needs to be an object instance what you wrote is incorrect." but I am still newer to django and would like to know the steps to do this as I created this project with some help.
here is my models
from django.db import models
from django.db.models import Count, QuerySet, F
from django.utils import timezone
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.core.urlresolvers import reverse
from django.db.models.signals import pre_save
from django.utils.text import slugify
from markdown_deux import markdown
from django.utils.safestring import mark_safe
from taggit.managers import TaggableManager
from comments.models import Comment
def upload_location(instance, filename):
return "%s/%s" %(instance.slug, filename)
class Post(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1 )
title = models.CharField(max_length=75)
slug = models.SlugField(unique=True)
image = models.ImageField(
upload_to=upload_location,
null=True,
blank=True,
width_field="width_field",
height_field="height_field")
height_field = models.IntegerField(default=0)
width_field = models.IntegerField(default=0)
description = models.TextField()
tags = TaggableManager()
public = models.BooleanField(default=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
created = models.DateTimeField(auto_now_add=True, auto_now=False)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("posts:detail", kwargs={"slug": self.slug})
class Meta:
ordering = ["-created", "-updated" ]
def get_markdown(self):
description = self.description
markdown_text = markdown(description)
return mark_safe(markdown_text)
#property
def comments(self):
instance = self
qs = Comment.objects.filter_by_instance(instance)
return qs
#property
def get_content_type(self):
instance = self
content_type = ContentType.objects.get_for_model(instance.__class__)
return content_type
def create_slug(instance, new_slug=None):
slug = slugify(instance.title)
if new_slug is not None:
slug = new_slug
qs = Post.objects.filter(slug=slug).order_by("-id")
exists = qs.exists()
if exists:
new_slug = "%s-%s" %(slug, qs.first().id)
return create_slug(instance, new_slug=new_slug)
return slug
def pre_save_post_receiver(sender, instance, *args, **kwargs):
if not instance.slug:
instance.slug = create_slug(instance)
pre_save.connect(pre_save_post_receiver, sender=Post)
Here is my views
from django.contrib import messages
from django.contrib.contenttypes.models import ContentType
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.db.models import Q
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.shortcuts import render, get_object_or_404, redirect
from django.core.exceptions import PermissionDenied
from comments.forms import CommentForm
from comments.models import Comment
from .forms import PostForm
from .models import Post
def post_main(request):
return render(request, "base2.html")
#login_required
def post_create(request):
form = PostForm(request.POST or None, request.FILES or None)
if form.is_valid():
instance = form.save(commit=False)
instance.user = request.user
instance.save()
# message success
messages.success(request, "Successfully Created")
return HttpResponseRedirect(instance.get_absolute_url())
context = {
"form": form,
}
return render(request, "post_form.html", context)
#login_required
def post_update(request, slug=None):
instance = get_object_or_404(Post, slug=slug)
form = PostForm(request.POST or None, request.FILES or None, instance=instance)
if form.is_valid():
instance = form.save(commit=False)
instance.save()
messages.success(request, "Post Saved")
return HttpResponseRedirect(instance.get_absolute_url())
context = {
"title": instance.title,
"instance": instance,
"form":form
}
return render(request, "post_form.html", context)
def post_user(request):
return HttpResponse("<h1>Users Post</h1>")
#login_required
def post_detail(request, slug=None):
instance = get_object_or_404(Post, slug=slug)
initial_data = {
"content_type": instance.get_content_type,
"object_id": instance.id
}
form = CommentForm(request.POST or None, initial=initial_data)
if form.is_valid() and request.user.is_authenticated():
c_type = form.cleaned_data.get("content_type")
content_type = ContentType.objects.get(model=c_type)
obj_id = form.cleaned_data.get('object_id')
content_data = form.cleaned_data.get("content")
parent_obj = None
try:
parent_id = int(request.POST.get("parent_id"))
except:
parent_id = None
if parent_id:
parent_qs = Comment.objects.filter(id=parent_id)
if parent_qs.exists() and parent_qs.count() == 1:
parent_obj = parent_qs.first()
new_comment, created = Comment.objects.get_or_create(
user = request.user,
content_type= content_type,
object_id = obj_id,
content = content_data,
parent = parent_obj,
)
return HttpResponseRedirect(new_comment.content_object.get_absolute_url())
comments = instance.comments
context = {
"title": instance.title,
"instance": instance,
"comments": comments,
"comment_form":form,
}
return render(request, "post_detail.html", context)
#login_required
def post_feed(request):
queryset_list = Post.objects.all()
query = request.GET.get("q")
if query:
queryset_list = queryset_list.filter(
Q(title__icontains=query)|
Q(tags__icontains=query)|
Q(content__icontains=query)|
Q(user__first_name__icontains=query) |
Q(user__last_name__icontains=query)
).distinct()
paginator = Paginator(queryset_list, 8) # Show 25 contacts per page
page_request_var = "page"
page = request.GET.get(page_request_var)
try:
queryset = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
queryset = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
queryset = paginator.page(paginator.num_pages)
context = {
"object_list": queryset,
"title": "List",
"page_request_var": page_request_var,
}
return render(request, "post_feed.html", context)
#login_required
def post_delete(request, slug=None):
instance = get_object_or_404(Post, slug=slug)
if request.user == Post.user:
instance.delete() # or save edits
messages.success(request, "Successfully Deleted")
return redirect("posts:feed")
else:
raise PermissionDenied # import it from django.core.exceptions
return redirect("posts:feed")
def privacy(request):
return render(request, "privacy.html")
def post_about(request):
return HttpResponse("<h1>About Page</h1>")
def home(request):
return render(request, "base2.html")
Let me know if any other information is needed.
You are almost there.
in delete, your check should be:
request.user == instance.user
instead of
request.user == Post.user
Similarly in post_update, you could do:
if instance.user == request.user:
#Now, allow update
Also, it might be a good idea to check for the request type. Example:
if request.method == "POST":
This way, this check would only happen if it is a POST type
i am new to this language and trying to create a form from the 2 models that i have creates
models.py
from locpick.field import LocationField
from django.db import models
from django.db.models import permalink
from django.contrib import admin
from PIL import Image
from time import time
def get_upload_file_name(instance, filename):
return "photo/%s_%s" % (str(time()).replace('.','_'), filename)
class Journey(models.Model):
name = models.CharField(max_length=250)
location = LocationField()
description = models.TextField()
date = models.DateTimeField()
class Meta:
ordering = ['name']
def __unicode__(self):
return self.name
#permalink
def get_absolute_url(self):
return ('item_detail', None, {'object_id': self.id})
class Photo(models.Model):
item = models.ForeignKey(Journey)
upload = models.ImageField(upload_to=get_upload_file_name)
class Meta:
ordering = ['title']
def __unicode__(self):
return self.title
#permalink
def get_absolute_url(self):
return ('photo_detail', None, {'object_id': self.id})
class PhotoInline(admin.StackedInline):
model = Photo
class JourneyAdmin(admin.ModelAdmin):
inlines = [PhotoInline]
list_display = ('name', 'location','description')
admin.site.register(Journey, JourneyAdmin)
forms.py
from django import forms
from models import Journey, Photo
class JourneyForm(forms.ModelForm):
class Meta:
model = Journey
fields = ('name','location','description','date')
class PhotoForm(forms.ModelForm):
class Meta:
model = Photo
exclude = ('item')
views.py
from django.template import loader, Context
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.http import HttpResponse
from locpick.models import Journey , Photo
from forms import JourneyForm, PhotoForm
from django.core.context_processors import csrf
def journeys(request):
return render_to_response('journeys.html',{'journey':Journey.objects.all()})
def journey(request, locpick_id=1):
return render_to_response('journey.html',{'journey':Journey.objects.get(id=locpick_id)})
def photo(request):
return render_to_response('journey.html',{'photo':Photo.objects.all(get(id=photo_id))})
def create(request):
if request.POST:
form1 = JourneyForm(request.POST )
form2 = PhotoForm(request.POST, request.FILES)
if form1.is_valid() and form2.is_valid():
b = form1.save()
c = form2.save(commit=False)
c.b = b
c.save()
return HttpResponseRedirect('/journey/all')
else:
form1 = JourneyForm(prefix="form1")
form2 = PhotoForm(prefix="form2")
args = {}
args.update(csrf(request))
args['form'] = form
return render_to_response('create_journey.html',args)
i am getting the error that create ddidnt return a HttpResponse object
where am i going wrong
thankyou
In def create(request): method in views.py you have only handled for POST requests. What about if there is a GET request. You are returning None which is wrong according to Django.
Django views.py methods should always return a HttpResponse (or a subclass) object of it. That could be causing your crash.
So it should be something like -
def create(request):
if request.POST:
...
return render_to_response(...)
elif request.GET:
...
return render_to_response(...)
def create(request):
if request.POST:
form1 = JourneyForm(request.POST )
form2 = PhotoForm(request.POST, request.FILES)
if form1.is_valid() and form2.is_valid():
b = form1.save()
c = form2.save(commit=False)
c.b = b
c.save()
return HttpResponseRedirect('/journey/all')
else:
form1 = JourneyForm(prefix="form1")
form2 = PhotoForm(prefix="form2")
args = {}
args.update(csrf(request))
args['form'] = form
return render_to_response('create_journey.html',args)