I am building a Blog App and i am stuck on a problem.
The Problem
Validation Error is not raising.
What i am trying to do
I made a feature that if user select past time in DateTimeField in Browser Page then a Validation error will be shown. BUT the error is showing.
forms.py
from django.core.exceptions import ValidationError
class PostForm(forms.ModelForm):
date_added = forms.DateTimeField(initial=timezone.now)
def clean_date(self):
date_added = self.cleaned_data['date_added']
if date_added.date() < datetime.date_added.today():
raise forms.ValidationError("The date cannot be in the past!")
return date_added
views.py
def new__blog_post(request,user_id):
if request.method != 'POST':
form = PostForm()
else:
form = PostForm(request.POST,request.FILES)
new_post = form.save()
new_post.post_owner = request.user
new_post.save()
return redirect('mains:posts',user_id=user_id)
context = {'form':form,'posts':posts}
return render(request, 'new_blog_post.html', context)
My other question related to this , Question
I don't know what i am doing wrong in this.
Any help would be Appreciated.
Thank You in Advance.
To validate data you need to call Form.is_valid(). See Using forms to validate data.
So call first is_valid():
def new__blog_post(request,user_id):
if request.method == 'POST':
form = PostForm(request.POST,request.FILES)
if form.is_valid():
new_post = form.save()
new_post.post_owner = request.user
new_post.save()
return redirect('mains:posts',user_id=user_id)
else:
form = PostForm()
posts = Post.objects.all()
context = {'form':form,'posts':posts}
return render(request, 'new_blog_post.html', context)
forms.py:
from django.core.exceptions import ValidationError
import datetime
class PostForm(forms.ModelForm):
date_added = forms.DateTimeField(initial=timezone.now)
class Meta:
model = YourModel
fields = ["date_added", ...]
def clean_date_added(self):
date_added = self.cleaned_data['date_added']
if date_added.date() < datetime.added.today():
raise forms.ValidationError("The date cannot be in the past!")
return date_added
Related
Whenever I try to create a "Tour" for a "User" I get this error:
"DoesNotExist at /add-tour/FAjK5CryF8/ - User matching query does not exist."
Specifically the problems seems to come from this line of code:
user = User.objects.get(pk=pk)
models.py
class Tour(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
tour_date = models.DateField(default=date.today)
tour_fans = models.ForeignKey(FanAccount, on_delete=models.PROTECT)
def __str__(self):
return f"{self.user} del {self.tour_date}"
views.py
def tour_new(request, pk):
user = User.objects.get(pk=pk)
if request.method == "POST":
form = TourForm(request.POST)
if form.is_valid():
instance = form.save(commit=False)
instance.tour_fans = request.user
form.instance.user = user
instance.save()
form.save()
return render(request, "tour.html", {"form": TourForm(), "success": True})
else:
form = TourForm()
return render(request, "tour.html", {"form": form})
For "User" I'm using a custom Primary Key (ShortUUID).
I'm new to Python and Django so it may be something easily solvable, but after hours of attempts I seem unable to solve it.
You need to make sure your user instance does exist, so you should instead of user = User.objects.get(pk=pk)call user = get_object_or_404(User, pk=pk), then you need to pass user as an instance:
if request.method == "POST":
form = TourForm(request.POST, instance=user)
I am trying to associate the user with the post. I have two models students is for user and sublists is for user posts with a foreign key(author). I am using MySQL database and using forms to store data into them. when my form.author execute in my HTML file it gives me a list of ids for all users in the databse but I am already logged in and i want to post as the logged in user without choosing. If remove it says my form is not valid which make sense since im not inputing for form.author.Since I'm using MySQL, I'm not using the built-in User authentication method, but instead comparing both email and password with the login form input. Spend too much time on this but hard to get around with this one. Any help would be appreciated
my views.py look like this
def addnew(request):
if request.method == 'POST':
form = Sublist(request.POST)
if form.is_valid():
try:
form.save()
messages.success(request, ' Subscirption Saved')
name = sublist.objects.get(name=name)
return render (request, 'subscrap/main.html', {'sublist': name})
except:
pass
else:
messages.success(request, 'Error')
pass
else:
form = Sublist()
return render(request, 'subscrap/addnew.html', {'form': form})
#login_required(login_url='login')
#cache_control(no_cache=True, must_revalidate=True, no_store=True)
def main(request):
return render(request, 'subscrap/main.html')
def mod(request):
student = students.objects.all()
return render(request, 'subscrap/mod.html' , {'students': student})
My Models.py
class students(models.Model):
fname = models.CharField(max_length=50)
lname = models.CharField(max_length=50)
password = models.CharField(max_length = 50 , null = True)
passwordrepeat = models.CharField(max_length = 50, null = True)
email = models.EmailField(max_length=150)
class Meta:
db_table = "students"
class sublist(models.Model):
author = models.ForeignKey(students, related_name='sublist' ,on_delete=models.CASCADE)
name = models.CharField(max_length=150)
cost = models.IntegerField(default = 0)
renewalcycle = models.IntegerField(default = 0)
class Meta:
db_table = "sublist"
Since I'm using forms here's my forms.py
lass StudentForm(forms.ModelForm):
class Meta:
model = students
fields = "__all__"
class Studentlogin(forms.Form):
email = forms.EmailField(max_length=150)
password = forms.CharField(max_length = 50, widget=forms.PasswordInput)
class Sublist(forms.ModelForm):
class Meta:
model = sublist
fields = "__all__"
Exclude the Author from the Sublist form:
class Sublist(forms.ModelForm):
class Meta:
model = sublist
exclude = ['author']
In the addnew method, you associate the .instance.author with the request.user:
#login_required(login_url='login')
def addnew(request):
if request.method == 'POST':
form = Sublist(request.POST)
if form.is_valid():
form.instance.author = request.user
form.save()
messages.success(request, ' Subscirption Saved')
return redirect('some_view')
else:
messages.error(request, 'Error')
else:
form = Sublist()
return render(request, 'subscrap/addnew.html', {'form': form})
Note: Models in Django are written in PascalCase, not snake_case,
so you might want to rename the model from sublist to Sublist.
Note: Usually a Form or a ModelForm ends with a …Form suffix,
to avoid collisions with the name of the model, and to make it clear that we are
working with a form. Therefore it might be better to use SublistForm instead of
Sublist.
Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the students directly. For more information you can see the referencing the User model section of the documentation.
I have a problem with defining form in Django (python 3.7, django 3.0.8)
I create a model. This model has two very important fields: date and user_id.
Requirement: date and user_id are unique.
I create a form model to associated with the model. The logged in user completes the form and it is important that the defined date cannot be from the past and cannot appear in the database.
My problems:
One problem:
My validation associated with date from the past WORKS CORRECT[!], but but if a past date is given, no error message is displayed.
Second problem: The second thing is that I have no idea how to prevent definition data, what it exist in database.
Code: models.py
class MyModel(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
date = models.DateField()
...(other fields)
class Meta:
unique_together = [['user', 'date']]
Code: forms.py
class AddMyModel(forms.Form):
date = forms.DateField(widget=DateInput(attrs={'type': 'date'}),
)
def clean_date(self):
date = self.cleaned_data['date']
if date < timezone.now().date():
raise ValidationError("Date cannot be in the past")
return date
Do you have any idea how to design the form to display in the template the error "date cannot be from the past" and error "the given date is already defined"?
views.py
def add(request):
if request.user.is_authenticated:
user = request.user.id
if request.method == 'POST':
form = AddMyModel(request.POST)
if form.is_valid():
date = form['date'].value()
mymodel= MyModel(user=User(pk=user), date=date)
mymodel.save()
return render(request, 'mysite/successfuladd.html', {"login": True})
form = AddMyModel()
return render(request, 'mysite/add.html', {'form': form, 'login': True})
else:
return render(request, 'mysite/homepage.html', {'login': False})
Try this one with datetime:
def clean_date(self):
date = self.cleaned_data['date']
if date < datetime.date.today():
raise ValidationError(self.error_messages['Date cannot be in the past'], code='Date cannot be in the past')
return date
I managed to fix the problem by myself.
MyModels is the same.
forms.py
class AddMyModel(forms.ModelForm):
def clean_date(self):
date = self.cleaned_data['date']
if date < timezone.now().date():
raise forms.ValidationError(message='Date cannot be in the past')
return date
class Meta:
model = MyModel
fields = ('date')
widgets = {
'date': forms.DateInput(attrs={'type': 'date'})
}
views.py
def add(request):
if request.user.is_authenticated:
user = request.user.id
if request.method == 'POST':
form = AddMyModel(request.POST)
if form.is_valid():
date = form['date'].value()
if MyModel(user=User(pk=user), date=date):
unique_error = "User and date is already exist."
return render(request, 'mysite/add.html',
{'form': form, 'login': True, 'unique_error': unique_error})
else:
mymodel= MyModel(user=User(pk=user), date=date)
mymodel.save()
return render(request, 'mysite/successfuladd.html', {"login": True})
return render(request, 'mysite/add.html',
{'form': form, 'login': True})
form = AddMyModel()
return render(request, 'mysite/add.html', {'form': form, 'login': True})
else:
return render(request, 'mysite/homepage.html', {'login': False})
I'm pretty new to Django, I've been stuck on this view for a little while. My goal with this form is to be able to create a small note on a "Property" about maintenance or other information. The note would log the time, date, note and the user that recorded the note. Any help would be appreciated.
View:
#login_required(login_url="login")
def createNote(request, pk):
PropertyNoteFormSet = inlineformset_factory(
Property, PropertyNote, fields=('note', 'user',))
property_note = Property.objects.get(id=pk)
form = PropertyNoteFormSet(instance=property_note)
# form = OrderForm(initial={'customer': customer})
if request.method == "POST":
print(request.POST)
form = PropertyNoteFormSet(
request.POST, instance=property_note)
if form.is_valid():
form.save()
return redirect("/")
context = {"form": form}
return render(request, "dashboard/create_note.html", context)
Here is the ModelForm:
class PropertyNoteForm(ModelForm):
class Meta:
model = PropertyNote
fields = ['note']
exclude = ['user']
Here is the Model:
class PropertyNote(models.Model):
airbnb_name = models.ForeignKey(Property, blank=True,
null=True,on_delete=models.CASCADE)
note = models.TextField(blank=True, null=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
created_on = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.note
The form comes out with around 4 boxes to fill in. Currently it works, but you have to actually select the user that is posting the note, I would like this part to be handled automatically and use the current logged in user. I think I still have a whole lot of holes in my knowledge around this stuff, I just can't seem to work it out.
Thanks in advance.
Edit:
I've tried this:
def createNote(request, pk):
PropertyNoteFormSet = inlineformset_factory(
Property, PropertyNote, fields=('note',), extra=1)
property_note = Property.objects.get(id=pk)
form = PropertyNoteFormSet(
queryset=PropertyNote.objects.none(), instance=property_note)
# form = OrderForm(initial={'customer': customer})
if request.method == "POST":
print(request.POST)
form = PropertyNoteFormSet(
request.POST, instance=property_note)
if form.is_valid():
instance = form.save(commit=False)
instance.user = request.user
print(instance.user)
instance.save()
return redirect("/")
context = {
"form": form,
'pk': pk,
}
return render(request, "dashboard/create_note.html", context)
But I get this:
AttributeError at /create_note/75/
'list' object has no attribute 'user'
Request Method: POST
Request URL: http://127.0.0.1:8000/create_note/75/
Django Version: 3.0.4
Exception Type: AttributeError
Exception Value:
'list' object has no attribute 'user'
you can use request.user.id to get the logged user id in your view.
See Documentation in Django
#login_required(login_url="login")
def createNote(request, pk, **kwargs):
note_form = PropertyNoteForm()
if request.method == "POST":
note_form = PropertyNoteForm(request.POST)
if note_form.is_valid():
add_note = note_form.save(commit=False)
add_note.user = request.user
add_note.airbnb_name =
Property.objects.get(id=pk)
add_note.save()
return redirect('/property/' + pk + '/')
context = {
"form": note_form,
'pk': pk,
}
return render(request, "dashboard/create_note.html", context)
I solved it with the above code. Using instance was the incorrect thing to do here. I didn't need to create an instance and I didn't need the inline form. I simply needed a new form:
note_form = PropertyNoteForm()
The user input information, I need to send that information to check if it's valid:
if request.method == "POST":
note_form = PropertyNoteForm(request.POST)
if note_form.is_valid():
Then I needed to populate the form with information that was not already in the form from the user:
add_note = note_form.save(commit=False)
add_note.user = request.user
add_note.airbnb_name = Property.objects.get(id=pk)
add_note.save()
return redirect('/property/' + pk + '/')
Sry for stupid question, but I don't understand. I'm trying to use Django Forms, I have 2 models
class Post(models.Model):
unit = models.ForeignKey('Unit',on_delete=models.CASCADE, primary_key=False)
and
class Unit(models.Model):
name = models.CharField(max_length=120, unique = True)
I've created a form
from django import forms
from .models import Post, Unit, StatusOfPost
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = [
'unit',
]
than I've written a view.py
def ideaNewForm(request):
unit = Unit.objects.get(name=request.POST['unit'])
user = request.user
if request.method == 'POST':
form = PostForm(request.POST)
if form.is_valid():
idea = form.save(commit=False)
idea.unit = unit
idea = Post.objects.create(
author = user,
)
return redirect('postsList')
else:
form = PostForm()
return render(request, 'post_new.html', {'form':form})
Unit matching query does not exist.- and i have that such issue.
I have a dropdown list it is a Unit model. How save it right?
Before I did it without Django Form
unit = Unit.objects.get(name=request.POST['unit'])
and it worked well, but I want use Django Forms
I'm not quite sure why you are trying to get the unit separately. It's what is selected in the form, there is no need to get it; just saving the form will create the post with the selected unit. The only thing you need to do is to add the user.
def ideaNewForm(request):
if request.method == 'POST':
form = PostForm(request.POST)
if form.is_valid():
idea = form.save(commit=False)
idea.author = request.user
idea.save()
return redirect('postsList')
else:
form = PostForm()
return render(request, 'post_new.html', {'form':form})
You just missing a ['unit'] after request.POST:
def ideaNewForm(request):
unit = Unit.objects.get(name=request.POST['unit'])
(...remaining codes...)