view "add product" - does not work - python

i created a model which contains name and price. I made a view that will help me with adding products on my site:
def new_expense(request):
if request.method == "EXPENSE":
form = ExpenseForm(request.EXPENSE)
if form.is_valid():
expense = form.save(commit=False)
expense.save()
return redirect('homebudget.views.expense_detail', pk=expense.pk)
else:
form = ExpenseForm()
return render(request, 'homebudget/edit_expense.html', {'form': form})
Now i have something like that: http://i.stack.imgur.com/3RbQr.png
but when i click save there's nothing happening! What must i change in view?
forms.py:
class ExpenseForm(forms.ModelForm):
class Meta:
model = Expense
fields = ('name', 'price',)
models.py:
class Expense(models.Model):
name = models.CharField(max_length=40)
price = models.FloatField("price")

request.method cannot be equal to EXPENSE, it may only be a HTTP method name. In the same way, request.EXPENSE
is not defined.
I don't know how the request is done but what you probably want to test is:
if request.method == 'POST':
form = ExpenseForm(request.POST)
Note:
expense = form.save(commit=False)
expense.save()
and
expense = form.save()
are equivalent.

Related

associate the user with the post Django and MySQL

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.

Django ModelForm: Defining a value not passed into the template

I have a ModelForm, and I want to only pass some of the fields into the template. I would like to save one particular field to define after the POST request has been sent. Here is the ModelForm:
class CreateListingForm(ModelForm):
class Meta:
model = models.ListingModel
fields = ['name', 'image', 'description', 'price', 'category']
widgets = {
'description': Textarea()
}
And here is the Model:
class ListingModel(models.Model):
name = models.CharField(max_length=30)
image = models.ImageField(upload_to='images')
description = models.CharField(max_length=1000)
price = models.PositiveIntegerField()
category = models.CharField(max_length=15)
objects = models.Manager()
owner = models.CharField(max_length=100)
In the next code block, I am attempting to define the owner field according to the current user logged in (request.user.username):
#login_required(redirect_field_name=login_view)
def create_listing(request):
if request.method == "GET":
return render(request, "auctions/createlisting.html", {
"CreateListingForm": forms.CreateListingForm()
})
elif request.method == "POST":
form = forms.CreateListingForm(request.POST, request.FILES)
if form.is_valid():
try:
form.owner = request.user.username
print(form.owner)
form.save(commit=True)
except Exception:
return HttpResponseRedirect(reverse("create_listing_error"))
return HttpResponseRedirect(reverse("index")) #TODO
Now, when I say print(form.owner), the result is correct. However when I save the ModelForm, the owner field is left blank. Am I not defining the value of the owner field correctly?
You should not confuse the ModelForm with the instance it is wrapping. The fact that it prints something for form.owner is not that strange, you first set an attribute named .owner, an attribute that did not exists before. You should set the .owner of the .instance of the form:
#login_required(redirect_field_name=login_view)
def create_listing(request):
if request.method == 'POST':
form = forms.CreateListingForm(request.POST, request.FILES)
if form.is_valid():
form.instance.owner = request.user.username
form.save()
return redirect('name-of-some-view')
else:
form = forms.CreateListingForm()
return render(request, 'auctions/createlisting.html', {
'CreateListingForm': form
})
Where 'name-of-some-view' should be replaced by the name of some view to which you redirect in case the form was valid.
You should however consider changing the CharField of owner to a ForeignKey [Django-doc]. Imagine that later the user changes their username, then your ListingModels do no longer refer to a real user.

Redirect to function based detail view after submitting form

I created a model named Student. I created a model form. I want to go to detail view not the list view, after submitting model form.
How do i do that ?
model.py
class Student(models.Model):
student_name = models.CharField(max_length=100)
father_name = models.CharField(max_length=100)
forms.py
class AdmissionForm(forms.ModelForm):
class Meta:
model = Student
fields = '__all__'
views.py
def admission_form(request):
form = AdmissionForm()
if request.method == 'POST':
form = AdmissionForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('student-list') # i want to redirect to detail view
context = {'form':form}
return render(request, 'student/admission_form.html', context)
In this admission form, i want to redirect to detail view of the student not the list view. How can i do that. In this code, i have redirected to list view.
def student_detail(request, id):
stud = Student.objects.get(id=id)
context = {'stud':stud}
return render(request, 'student/student_detail.html', context)
urls.py
urlpatterns = [
path('admission_form/', views.admission_form, name = 'admission-form'),
path('student/', views.student_list, name = 'student-list'),
path('student/<int:id>/', views.student_detail, name = 'student-detail'),
]
form.save() will return an instance of Student model. You can use it's id in redirect like this:
def admission_form(request):
form = AdmissionForm()
if request.method == 'POST':
form = AdmissionForm(request.POST, request.FILES)
if form.is_valid():
instance = form.save()
return redirect('student-detail', id=instance.pk)

Django model form, adding a user id when creating new note

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 + '/')

Django Form ForeignKey save

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...)

Categories