I get:
IntegrityError at /category/
NOT NULL constraint failed: transactions_category.user_id
here in my view:
elif "create" in request.POST:
createform = CategoryForm(data=request.POST)
createform.save(commit=False)
createform.user = request.user
createform.save() <--- specifically here, the .save with commit=False goes through and I can also set the user
I checked with the debugger and createform.user has a User, that User also has an id.
forms.py:
class CategoryForm(ModelForm):
class Meta:
model = Category
exclude = ["subcategory", "user"]
models.py:
class Category(models.Model):
title = models.CharField(max_length = 100)
subcategory = models.ManyToManyField("self", blank=True, symmetrical=False)
user = models.ForeignKey(User)
User import is:
from django.contrib.auth.models import User
Why will it not save? I set the user before calling .save(), the user is set (and has an id) as far as I can tell with the debugger?
I have run both manage.py migrate and manage.py makemigrations and everything is up to date.
Edit:
the template:
<p>Create new category form</p>
<form action="/category/" method="post">
{% csrf_token %}
{{ createform.as_p }}
<input type="submit" name="create" value="Create new category">
</form>
<hr>
The creation and saving of new Category objects worked before I added the "user" field to the model (and I ran migrate and makemigrations after I did)
Edit 2:
complete view:
def category_view(request):
createform = CategoryForm()
searchform = CategorySearchForm()
categories = Category.objects.all()
categories_left = []
categories_right = []
if request.method == "POST":
if "search" in request.POST:
categories_left = Category.objects.for_title(request.POST["left-search"], user=request.user)
categories_right = Category.objects.for_title(request.POST["right-search"], user=request.user)
elif "create" in request.POST:
createform = CategoryForm(request.POST)
if createform.is_valid():
createform.save(commit=False)
createform.user = request.user
createform.save()
elif "add-subcategory" in request.POST:
left = Category.objects.for_id(request.POST["left-category"], user=request.user)
right = Category.objects.for_id(request.POST["right-category"], user=request.user)
try:
left.subcategory.add(right)
old = left
old.pk = None
old.save()
except IntegrityError:
print("This combination already exists.") # TODO
context = {"createform":createform,
"searchform":searchform,
"categories":categories,
"categories_left":categories_left,
"categories_right":categories_right}
return render(request, "transactions/category_creation.html", context)
Try to save passing an instance of user.
createform.save(commit=False)
createform.instance.user = request.user
createform.save()
The form's save method returns an instance. You should update and save the instance, rather than trying to save the form again.
instance = createform.save(commit=False)
instance.user = request.user
instance.save()
Related
Hi I have written a def clean(self) function in forms to make sure that if there was previously already a post with the same title, they will return a message saying that the title already exists and hence the form cannot be submitted.
Problem now:
When I enter a title that already exists and I try to create the post, all data previously input will be removed and I will be redirected to a fresh form. No errors were raised. What I want is for the error to be raised and shown to the user when I try to click on the create button so all data remains there and the user knows and can change the title before attempting the create the blog post again.
return cleaned_data in forms.py is not defined too...giving a nameerror
Guideline:
Note! There is NO slug field in my form. The slug is only for the url for each individual blogpost. But basically the slug consists of the title. Eg if my username is hello and my chief_title is bye, my slug will be hello-bye. Both the slug and the title has to be unique as you can see in the model, but there is no slug in the form.
models.py
class BlogPost(models.Model):
chief_title = models.CharField(max_length=50, null=False, blank=False, unique=True)
brief_description = models.TextField(max_length=300, null=False, blank=False)
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
slug = models.SlugField(blank=True, unique=True)
views.py
def create_blog_view(request):
context = {}
user = request.user
if not user.is_authenticated:
return redirect('must_authenticate')
if request.method == 'POST':
form = CreateBlogPostForm(request.POST or None, request.FILES or None)
if form.is_valid():
obj= form.save(commit = False)
author = Account.objects.filter(email=user.email).first()
obj.author = author
obj.save()
obj.members.add(request.user)
context['success_message'] = "Updated"
return redirect('HomeFeed:main')
else:
form = CreateBlogPostForm()
context['form'] = form
return render(request, "HomeFeed/create_blog.html", {})
forms.py
class CreateBlogPostForm(forms.ModelForm):
class Meta:
model = BlogPost
fields = ['chief_title']
def clean(self):
chief_title = self.cleaned_data['chief_title']
qs = BlogPost.objects.filter(chief_title=chief_title)
if qs.exists():
raise forms.ValidationError('Post already exists')
return cleaned_data
html
<form class="create-form" method="post" enctype="multipart/form-data">{% csrf_token %}
{% if form.non_field_errors %}
{{form.non_field_errors}}
{% endif %}
<!-- chief_title -->
<div class="form-group">
<label for="id_title">Chief Title!</label>
<input class="form-control" type="text" name="chief_title" id="id_title" placeholder="Title" required autofocus>
</div> {{form.chief_title.errors}}
<button class="submit-button btn btn-lg btn-primary btn-block" type="submit">CREATE</button>
</form>
Well you can create a custom validator to check if the slug exists:
from django.core.exceptions import ValidationError
def validate_slug_exists(value):
blog_post = BlogPost.objects.filter(slug=value)
if blog_post.exists():
raise ValidationError('The post with a given title already exists')
Then in your form add this validator to the fields validators list:
class CreateBlogPostForm(forms.ModelForm):
chief_title = forms.CharField(validators = [validate_slug_exists])
UPDATE
You can also try using validate_unique() in your form class:
def validate_unique(self, exclude=None):
qs = BlogPost.objects.all()
if qs.filter(chief_title=self.chief_title).exists():
raise ValidationError("Blog post with this title already exists")
You can raise a ValidationError as shown in the docs. This would then be displayed in the form for the user.
def clean_slug(self):
slug = slugify(self.cleaned_data.get("chief_title")) if len(self.cleaned_data.get("slug", )) == 0 \
else self.cleaned_data.get("slug", )
if BlogPost.objects.filter(slug=slug).exists():
raise ValidationError(_('Slug already exists.'), code='invalid')
return slug
If you set unique = True Django takes care of checking whether another entry already exists in the database and adds an error in ModelForm.errors.
This is happening inModelForm.validate_unique.
There is no need to bother with this method unless you want to add more info in the error, such as the url of the existing object (it will cost 1 db hit).
Otherwise, the error already exists and you can just return the form with its errors instead of returning a new instance of the form as you currently do in views.py.
Therefore the following views.py as explained in this post should do what you are trying to do:
app/views.py:
def create_blog_view(request):
context = {}
# ...
if request.method == 'POST':
form = CreateBlogPostForm(request.POST or None, request.FILES or None)
if form.is_valid():
# do your thing
else:
context['form'] = form
return render(request, "HomeFeed/create_blog.html", context) # context instead of {}
If you want to get fancier and hit the db once more, you can add the url of the existing object in the errors list as such:
project/settings.py
...
# If you want to provide more info
MY_UNIQUE_BLOGPOST_ERROR_MESSAGE = "This BlogPost already exists"
...
app/models.py
from django.db import models
from django.conf import settings
from django.urls import reverse
class BlogPost(models.Model):
# ...
slug = models.SlugField(
blank=True,
unique=True,
error_messages={"unique": settings.MY_UNIQUE_BLOGPOST_ERROR_MESSAGE),
)
def get_admin_url(self):
return reverse("admin:app_blogpost_change", args=(self.id,))
...
app/forms.py
from django import forms
from django.conf import settings
from django.utils.html import format_html
from itertools import chain
from app.models import BlogPost
class CreateBlogPostForm(forms.ModelForm):
class Meta:
model = BlogPost
fields = '__all__'
def validate_unique(self):
'''
If unique error exists, find the relevant object and return its url.
1 db hit
There is no other need to override this method.
'''
super().validate_unique()
if settings.SHOP_ENTITY_UNIQUE_ERROR in chain.from_iterable(
self.errors.values()
):
instance = BlogPost.objects.get(slug=self.instance.slug)
admin_url = instance.get_admin_url()
instance_name = instance.__str__()
self.add_error(
None,
forms.ValidationError(
format_html(
"This entry already exists: {1}",
admin_url,
instance_name,
),
code="unique",
),
)
I have a simple Django 3.1.0 app I need to create in order to assign Tasks with Tags (or assign tags into tasks).
Model
class Task(models.Model):
user = models.CharField(max_length=33)
time = models.DateTimeField(auto_now_add=True)
task = models.CharField(max_length=500)
tags = models.CharField(max_length=100, default="None", null=True)
class Tag(models.Model):
tag = models.CharField(max_length=30, default="No Tag")
members = models.ManyToManyField('Task', related_name="tag")
class Meta:
verbose_name = "tag"
verbose_name_plural = "tags"
view
def main(request):
model = Task.objects.values().all()
tags = Tag.objects.values().all()
form = TaskForm()
con = {'context': list(model), 'form': form, 'tags': list(tags)}
if request.method == 'POST':
form = TaskForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
else:
form = TaskForm()
return render(request, "tasks.html", con)
form
class TaskForm(ModelForm):
class Meta:
model = Task
fields = ['user', 'task', 'tags']
template_name = 'tasks.html'
tags = ModelMultipleChoiceField(
queryset= Tag.objects.all(),
widget=CheckboxSelectMultiple(), required=False,
)
task_form
<form method="post" class="form">
{% csrf_token %}
{{form}}
<input type="submit" value="Save">
</form>
This returns in the tags list the items listed as:
Tag object (1)
Tag object (2)
And when it saves when i press submit, it fetches in a table (in another template), the values saved in the text of <QuerySet [<Tag: Tag object (2)>]>
That's how it stores them in the database.
I have managed to extract the values as they are ('jenkins','AKS') and send them in the template using this (bootstrapvuejs) : {% for tag in tags %}<b-form-checkbox>{{tag.tag}}</b-form-checkbox>{% endfor %}, which lists them raw values perfectly.
However, when I do that modification, the form submitted is not written to database.
What am I missing?
UPDATE!
I have partly solved it by adding this into the Tag model:
def __str__(self):
return self.tag
but when it persists it on submit, it still saves it as:
<QuerySet [<Tag: jenkins>]>
So, how and where do I strip only the specific tag values to be inserted in the database?
Many Thanks
Alright so there is a couple issues with your code, first off your main view:
Change it from this:
def main(request):
model = Task.objects.values().all() # calling values without specifying an argument makes no sense so just call it like **Task.objects.all()**
tags = Tag.objects.values().all() # same here
form = TaskForm() # don't call your form here it gets reassigned later anyways
con = {'context': list(model), 'form': form, 'tags': list(tags)} # don't define your context here since you are reasigning your form later so the form instance is always TaskForm()
if request.method == 'POST':
form = TaskForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
else:
form = TaskForm()
return render(request, "tasks.html", con)
To this:
def main(request):
model = Task.objects.all()
tags = Tag.objects.all()
if request.method == 'POST':
form = TaskForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
else:
form = TaskForm()
context = {'tasks': model,
'form': form,
'tags': tags}
return render(request, "tasks.html", con)
Then in your template pass your form with as_p method call:
{{ form.as_p }}
Hovewer the error you are getting is not because of your html or your view, it's because your tags field in your Task model is not a ManyToMany relationship to your Tag model but rather a simple CharacterField and you are trying to save objects to the CharField, so rewrite your Task model like this:
class Task(models.Model):
user = models.CharField(max_length=33)
time = models.DateTimeField(auto_now_add=True)
task = models.CharField(max_length=500)
tags = models.ManyToMany(Tags)
Then your form should save them in the tags field of your Task instance and you can view them like this:
task = Task.objects.get(pk=1)
task_tags = task.tags.all() # stores a queryset of all tags of the queried task
and in the template:
{% for tag in task.tags.all %}
...
{% endfor %}
OK , I solved the POST data that is saved in database as Queryset, by extracting in the view where save() is called, the field 'tags' likewise:
f = form.save(commit=False)
f.tags = request.POST['tags']
form.save()
The only problem now is that I have multiple checkboxes in the form but this way it extracts only one of them, whilst I would expect it to return a list like what is printed in the request.POST : <QueryDict: {'csrfmiddlewaretoken': ['XV7HgTFiWXEnrkhqT3IsqUN2JbnT7YIH5r6fKgh2ehqeLsLMpvCPdUU4N2qwWuPk'], 'user': ['afa'], 'task': ['aff'], 'tags': ['jenkins', 'AKS']}> -> from that I call 'tags' but it saves only 'jenkins' ...
UPDATE
OK, I RTFM and saw that there is a method on the QueryDict object that can be passed to request.POST.getlist('tags') , so now it returns the complete value of 'tags' key.
After Submitting the like button data is successfuly updating with the database but after this step it won't redirecting to the successful url. instead of that it is throwing attribute error. If I use HttpResponseRedirect('/album/') instaed of successful url this error is not comming. Please refer this link for the traceback
models.py
Codes in models.py
class VoteManager(models.Manager):
def get_vote_or_unsaved_blank_vote(self,song,user):
try:
return Vote.objects.get(song=song,user=user)
except ObjectDoesNotExist:
return Vote.objects.create(song=song,user=user)
class Vote(models.Model):
UP = 1
DOWN = -1
VALUE_CHOICE = ((UP, "👍️"),(DOWN, "👎️"),)
like = models.SmallIntegerField(null=True, blank=True, choices=VALUE_CHOICE)
user = models.ForeignKey(User,on_delete=models.CASCADE)
song = models.ForeignKey(Song, on_delete=models.CASCADE)
voted_on = models.DateTimeField(auto_now=True)
objects = VoteManager()
class Meta:
unique_together = ('user', 'song')
views.py
codes in views.py
class SongDetailView(DetailView):
model = Song
template_name = 'song/song_detail.html'
def get_context_data(self,**kwargs):
ctx = super().get_context_data(**kwargs)
if self.request.user.is_authenticated:
vote = Vote.objects.get_vote_or_unsaved_blank_vote(song=self.object, user = self.request.user)
vote_url = reverse('music:song_vote_create', kwargs={'song_id':vote.song.id})
vote_form = SongVoteForm(instance=vote)
ctx['vote_form'] = vote_form
ctx['vote_url'] = vote_url
return ctx
class SongVoteCreateView(View):
form_class = SongVoteForm
context = {}
def get_success_url(self,**kwargs):
song_id = self.kwargs.get('song_id')
return reverse('music:song_detail', kwargs={'pk':song_id})
def post(self,request,pk=None,song_id=None):
user = self.request.user
song_obj = Song.objects.get(pk=song_id)
vote_obj,created = Vote.objects.get_or_create(song = song_obj,user = user)
vote_form = SongVoteForm(request.POST, instance=vote_obj)
if vote_form.is_valid():
new_vote = vote_form.save(commit=False)
new_vote.user = self.request.user
new_vote.save()
return new_vote
song_detail.html
codes in html page.
<form action="{{vote_url}}" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ vote_form.as_p }}
<button class="btn btn-primary" type="submit" >Vote</button>
</form>
Error code
Please refer this link for the traceback
'Vote' object has no attribute 'get'
The post method needs to return an HttpResponse, not a Vote object.
But you shouldn't be defining post in the first place. All that code should go in form_valid.
def form_valid(self, form):
user = self.request.user
song_obj = Song.objects.get(pk=self.kwargs['song_id'])
vote_obj, _ = Vote.objects.get_or_create(song = song_obj, user = user)
form.instance = vote_obj
return super().form_valid(form)
Note, you don't need to check is_valid, and you also don't need to set the user as you've already done that in vote_obj.
You are returning Vote object from post method in your SongVoteCreateView view. You should return Response instead. Django doesn't know what to do with model object returned from a view.
I'm trying to create a basic user registration system for clients of a web application.
I've created the appropriate views and templates to create a form page which creates a Django User object and a UserProfile object of my own creation. (These are linked via a 1-1 field).
After visiting and filing in the forms on my registration page, I click submit and the fields related to initializing the UserProfile fields will be cleared and a "This field is required." error will be displayed over each input box (despite being properly filled in previously). If I fill these selected fields in again, and press submit the registration request will be processed correctly.
In the terminal, I've printed out the value of is_valid() for each form. On the first pass, the User form returns true, while the UserProfile form returns false. On the second submission they both return true.
Could you help me understand why this second form is returning false on the first pass and forcing me to resubmit?
Code is below:
models.py
from django.db import models
from django.contrib.auth.models import User
from django.forms import ModelForm
class UserProfile(models.Model):
user = models.OneToOneField(User)
name = models.CharField(max_length=100)
phone = models.CharField(max_length=32)
email = models.CharField(max_length=100)
institute = models.CharField(max_length=100)
address1 = models.CharField(max_length=100)
address2 = models.CharField(max_length=100)
city = models.CharField(max_length=100)
country = models.CharField(max_length=100)
postal_code = models.CharField(max_length=24)
description = models.TextField(max_length=2500)
def __unicode__(self):
return self.name
class UserForm(ModelForm):
class Meta:
model = User
fields = ['username', 'password', 'email']
class UserProfileForm(ModelForm):
class Meta:
model = UserProfile
exclude = ['user']
views.py
def registration(request):
if request.method == 'POST':
print('post')
user_form = UserForm(request.POST, prefix='user')
profile_form = UserProfileForm(request.POST, prefix='userprofile')
print('user form ' + str(user_form.is_valid()))
print('profile form ' + str(profile_form.is_valid()))
if user_form.is_valid() and profile_form.is_valid():
print('both valid')
user = user_form.save(commit=False)
user.is_active = False
user.save()
userprofile = profile_form.save(commit=False)
userprofile.user = user
userprofile.save()
print('success')
return HttpResponseRedirect('registration-success/')
else:
print('unbound')
user_form = UserForm(prefix='user')
profile_form = UserProfileForm(prefix='profile')
context = { 'userform': user_form,
'userprofileform': profile_form,}
return render(request, 'registration/register.html', context)
def success(request):
return render(request, 'registration/success.html', )
template.html
<!DOCTYPE html>
<html>
<body>
<h2> Registration </h2>
<form method="POST">
{% csrf_token %}
{{userform}}
</br></br>
{{userprofileform}}
<input type="submit" value="Submit"/>
</form>
forgot username/password<br />
new user
</body>
</html>
In your POST codepath, you have this:
profile_form = UserProfileForm(request.POST, prefix='userprofile')
In your else codepath, this:
profile_form = UserProfileForm(prefix='profile')
The prefix values need to match so that the POST data will be bound correctly to the profile form. It works on your resubmission because that goes through the POST codepath, so the ids used in the template match those the form object expects.
I can't figure out how to store a simple form in the database. I think I'm quite close but there is probably something wrong in my views.py. Here is my code, any ideas what I'm doing wrong? (also on dpaste)
# models.py
class IngredienceCategory(models.Model):
name = models.CharField(max_length=30, unique=True)
user = models.ForeignKey(User, null=True, blank=True)
class Meta:
verbose_name_plural = "Ingredience Categories"
def __unicode__(self):
return self.name
# forms.py
class CategoryForm(forms.Form):
name = forms.CharField(max_length=30)
# views.py
#login_required
def newCategory(request):
if request.method == 'POST':
username = request.user.username
cform = CategoryForm(request.POST)
if cform.is_valid():
formInstance = cform.save(commit = False)
formInstance.user = username
formInstance.name = cform.cleaned_data['name']
formInstance = IngredienceCategory.objects.filter(name=formInstance.name, user=formInstance.user)
formInstance.save()
# return HttpResponseRedirect('new-category/')
else:
form = CategoryForm()
context = {'form': form}
return render_to_response('new-category.html', context, context_instance=RequestContext(request))
# new-category.html
<h3>Insert New Category</h3>
<form action="/" method="post" id="food-form">{% csrf_token %}
{{ form.as_p }}
<input type="submit" name="foodForm" value="Save" />
</form>
The line below is not useful at it current position. That command will perform a database query and assign the result as a queryset, before you have saved the form data.
formInstance = IngredienceCategory.objects.filter(name=formInstance.name, user=formInstance.user)
This should work:
With cform as a normal Form:
if cform.is_valid():
formInstance = IngredienceCategory(user=request.user, cform.cleaned_data['name'])
formInstance.save()
If cform had been a ModelForm you could do:
if cform.is_valid():
formInstance = cform.save(commit=False)
formInstance.user = request.user
formInstance.save()
I do recommend you to check out ModelForms since it will build the cleaning functionality based on your model.
You should inherit from ModelForm
from django.forms import ModelForm
class CategoryForm(ModelForm):
class Meta:
model = IngredienceCategory
Refer to https://docs.djangoproject.com/en/dev/topics/forms/modelforms/ for how to render form and save it to database.