I am working on a small project containing two models User and Post.And a user can have multiple posts.
I have created a custom form PostForm.
When ever i am submitting the form it showing me the following error:-
'PostForm' object has no attribute 'user'
views.py:-
def add_post(request):
print("addpost runn")
if request.method == 'POST':
post_form = PostForm(request.POST)
print(request.POST)
print("if part")
if post_form.is_valid():
print(post_form)
post_form.save(commit=False)
post_form.user = request.user
post_form.save()
else:
print("else part")
post_form = PostForm()
return render(request, "addpost.html", {"form": post_form})
forms.py:-
class PostForm(forms.ModelForm):
text = forms.CharField(label="Write Your Text Here", max_length=200, widget=forms.Textarea(attrs={'rows': 3}))
created_at = forms.DateTimeField(input_formats=['%d/%m/%Y %H:%M:%S'],
widget=forms.DateTimeInput(format='%d/%m/%Y %H:%M:%S'))
updated_at = forms.DateTimeField(input_formats=['%d/%m/%Y %H:%M:%S'],
widget=forms.DateTimeInput(format='%d/%m/%Y %H:%M:%S'))
class Meta:
model = Post
fields = ['text']
def save(self, commit=True):
print(self.cleaned_data)
post = Post.objects.create_post(
self.cleaned_data['text'],
datetime.datetime.now(),
datetime.datetime.now(),
self.user,
)
return post
manager.py:-
class PostManager(BaseUserManager):
def create_post(self, text, created_at, updated_at, user, **otherfields):
print(created_at)
print(updated_at)
print(text)
post = self.model(text=text, created_at=created_at, updated_at=updated_at, user=user)
post.save(using=self._db)
return post
Here's your answer:
instance=post_form.save(commit=False)
instance.user = request.user
instance.save()
Related
I'm working on this project but I got the following error
comm = doctor_detail.comments.filter(active=True)
AttributeError: 'Doctor' object has no attribute 'comments' however I think that everything is alright
this is my models.py
class Comments(models.Model):
co_name = models.CharField(max_length=50, verbose_name="الاسم ")
co_email = models.EmailField(
max_length=50, verbose_name="البريد الالكتروني")
co_body = models.TextField(max_length=400, verbose_name='التعليق')
created_dt = models.DateTimeField(auto_now_add=True)
active = models.BooleanField(default=True)
post = models.ForeignKey(
User, on_delete=models.CASCADE, related_name='comments')
def __str__(self):
return 'علق {} على {}'.format(self.co_name, self.post)
this is my views.py
def doctor_detail(request, slug):
# استدعاء جميع البينات اللي في البروفايل
doctor_detail = get_object_or_404(Doctor, slug=slug)
comm = doctor_detail.comments.filter(active=True)
form = Commentair()
if request.method == 'POST':
form = Commentair(data=request.POST)
if form.is_valid():
new_comment = form.save(commit=False)
new_comment.post = doctor_detail
new_comment.save()
form = Commentair()
else:
form = Commentair()
return render(request, 'user/doctor_detail.html', {'doctor_detail': doctor_detail,
'comm': comm,'form': form
})
I really don't know why I'm facing this error because the related name is available and I think everything is okay .please if there is an answer to this write it and explain it to me. thank you
### You done mistake in here comments -> Comments c will be capital in filter
def doctor_detail(request, slug):
# استدعاء جميع البينات اللي في البروفايل
doctor_detail = get_object_or_404(Doctor, slug=slug)
comm = doctor_detail.Comments.filter(active=True)
form = Commentair()
if request.method == 'POST':
form = Commentair(data=request.POST)
if form.is_valid():
new_comment = form.save(commit=False)
new_comment.post = doctor_detail
new_comment.save()
form = Commentair()
else:
form = Commentair()
return render(request, 'user/doctor_detail.html', {'doctor_detail': doctor_detail,
'comm': comm,'form': form
})
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
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 + '/')
I am trying to replicate
if form.is_valid():
With the django form wizard. (this question shouldn't have anything to do with the wizard)
I have this code:
class ContactWizard(SessionWizardView):
def get_template_names(self):
return [TEMPLATES[self.steps.current]]
def done(self, form_list, **kwargs):
if self.request.method == 'POST':
print(form_list)
process_form_data(form_list)
return HttpResponseRedirect('../home')
def process_form_data(form_list):
if form.is_valid():
form_data = [form.cleaned_data for form in form_list]
first_name = form_data[0]['first_name']
last_name = form_data[0]['last_name']
email = form_data[0]['email']
fav_food = form_data[0]['fav_food']
fav_drink = form_data[0]['fav_drink']
user = User.objects.create_user(email)
user.first_name = first_name
user.last_name = last_name
user.email = email
user.save()
user_addon = UserAddon.objects.create(user=user,fav_food=fav_food,fav_drink=fav_drink)
user_addon.save()
return form_data
If i print out form_list i get this
odict_values([<UserAddonForm bound=True, valid=True, fields=(fav_food;fav_drink;first_name,last_name;email)>,ContactForm3 bound=True, valid=True, fields=(info1;info2;message)>])
and if i try running it with just
form.is_valid()
i get
Exception Value: name 'form' is not defined
how can i get an equivalent of the form.is_valid() working?
Thanks
You're passing a form_list to the function process_form_data, but checking against name form (by form.is_valid()) which does not exist at that point.
Assuming form_list is an iterable, you can iterate over it and deal with the forms sequentially:
def process_form_data(form_list):
for form in form_list:
if form.is_valid():
form_data = form.cleaned_data
first_name = form_data[0]['first_name']
last_name = form_data[0]['last_name']
I have a from created which is generated by a model. I can save the form, but the form data is not inserted into the table. The insert occurs, but with blank data. Any help would be greatly appreciated.
models.py
class HelpDefinition(models.Model):
org = models.IntegerField(default=0)
help_type = models.CharField(max_length=255)
help_content = models.TextField(blank=True)
def __unicode__(self):
return self.name
views.py
def index(request, org_id=None):
help_def = HelpDefinition()
if org_id:
help_def = HelpDefinition.objects.get(org=org_id)
if request.method == 'POST':
form = FormHelp(request.POST)
if form.is_valid():
help_def.save()
messages.success(request, 'Saved!')
else:
messages.error(request, 'Ugh')
else:
form = FormHelp(request=request, initial=initial_data)
return {
'form': form,
}
forms.py
class FormHelp(forms.Form):
org = forms.CharField(widget=forms.HiddenInput, required=True)
help_type = forms.ChoiceField(abel='Text', required=True)
help_content = forms.CharField(label='Description', required=True, widget=forms.Textarea)
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
super(FormHelp, self).__init__(*args, **kwargs)
Due that you dont use ModelForm, you need to set your attributes one by one.
if request.method == 'POST':
form = FormHelp(request.POST)
if form.is_valid():
help_def.org = form.cleaned_data.get("org")
help_def.help_type = form.cleaned_data.get("help_type")
help_def.help_type = form.cleaned_data.get("help_content")
help_def.save()