How update models modelforms and django - python

i have a problem when i try update the data for model usuario
this is my model
class Usuario(models.Model):
user = models.ForeignKey(User)
nombres = models.CharField(max_length = 50)
correo = models.EmailField()
class Meta:
db_table = u'utp_users'
def __str__(self):
return str(self.nombres.encode('utf-8') )
this is mi form. py
class UsuarioForm(forms.ModelForm):
class Meta:
model = Usuario
fields = ['nombres','correo']
my url
url(r'^menu/update/(?P<usuario_id>\d+)$', 'utpapp.views.update'),
this my view update
#login_required(login_url='/')
def update(request,usuario_id):
form = UsuarioForm(request.POST)
if form.is_valid():
user = Usuario.objects.get(pk=usuario_id)
form = UsuarioForm(request.POST, instance = user)
form.save()
return redirect('/menu/')
else:
user = Usuario.objects.get(pk = usuario_id)
form = UsuarioForm(instance=user)
return render_to_response('form.html',{ 'form':form }, context_instance=RequestContext(request))
and the template i am do this
<a title="Editar informacion" href="/menu/update/{{usuario.id}}"><img src="/media/imagenes/usuario.png" class=" col-xs-3 col-md-7 quitar-float" alt="Editar informacion" ></a>
the problem is when i select the option update i get the this msj "Page not found (404)"
but i change in template href {{usuario.id}} for {{user.id}} is work but with user different what is the problem ??

Try this, you need to pass usuario as context to the template, and you can much simplify the code (especially the form for GET/POST, they are basically the same form, so don't repeat it) as like:
from django.shortcuts import get_object_or_404
#login_required(login_url='/')
def update(request,usuario_id):
user = get_object_or_404(Usuario, pk=usuario_id)
form = UsuarioForm(request.POST or None, instance=user)
if request.method == 'POST' and form.is_valid():
form.save()
return redirect('/menu/')
# you need to pass `usuario` as part of the context to template
# so you can access usuario.id in template
return render_to_response('form.html',{ 'form':form, 'usuario': user }, context_instance=RequestContext(request))
Also make sure you have a url route for /menu/, or else redirect will get you 404.

You forget to pass the usuario variable to the template.

Related

How to get the current logged in user? Django models

I want to get the current logged in user to this CreateForm form. Below Im giving my current code, here request.user is not giving me error
ValueError at /create-post/
Cannot assign "<SimpleLazyObject: <User: testuser>>": "Post.author" must be a "Author" instance.
models.py
class Author(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
rate = models.IntegerField(default=0)
class Post(models.Model):
title = models.CharField(max_length= 50)
overview = models.TextField()
body_text = RichTextUploadingField(null = True)
time_upload = models.DateTimeField(auto_now_add=True)
author = models.ForeignKey(Author, related_name='author', on_delete=models.CASCADE)
thumbnail = models.ImageField(upload_to = 'thumbnails')
publish = models.BooleanField()
categories = models.ManyToManyField(Categories)
read = models.IntegerField(default=0)
slug = models.SlugField(null= True, blank= True)
Forms.py
class CreateForm(ModelForm):
class Meta:
model = Post
fields = [
'title',
'overview',
'body_text',
'thumbnail',
'categories',
'publish',
]
Views.py
def create_post(request):
if request.method == 'POST':
form = CreateForm(request.POST, request.FILES)
if form.is_valid:
post = form.save(commit=False)
post.author= request.user
post.save()
return render(request, 'index.html')
else:
form = CreateForm()
return render(request, 'create_post.html', {'form': form})
As the error says, post.author expects an Author object, not the user. You thus retrieve this with:
from django.contrib.auth.decorators import login_required
#login_required
def create_post(request):
if request.method == 'POST':
form = CreateForm(request.POST, request.FILES)
if form.is_valid():
form.instance.author= request.user.author
form.save()
return render(request, 'index.html')
else:
form = CreateForm()
return render(request, 'create_post.html', {'form': form})
You should also call the is_valid() method [Django-doc], so form.is_valid().
Note: You can limit views to a view to authenticated users with the
#login_required decorator [Django-doc].
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 User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.
The author field on your Post model is a foreign key to Author model, and not user. You could replace post.author = request.user with:
if request.user.author:
post.author = request.user.author
else:
post.author = Author.objects.create(user=request.user)
The answer from Willem works if an Author instance was already created for the User, but will throw an exception if there's no Author object associated with that user.

Form is not being saved in Django admin page

I have faced a problem in my Django project where my form is not being saved as a new listing in my model(listing) and is not even showing on Django's admin page.
my models.py :
class listing(models.Model):
title = models.CharField(max_length=64)
describtion = models.CharField(max_length=300)
bid = models.FloatField()
category = models.ForeignKey(categories, default=1, verbose_name="Category",
on_delete=models.SET_DEFAULT)
user = models.ForeignKey(User,default='', verbose_name="User", on_delete=models.SET_DEFAULT)
image = models.CharField(max_length=400)
def __str__(self):
return f"{self.title} "
create a new listing form :
class create(ModelForm):
class Meta:
model = listing
fields = [ 'title', 'describtion','bid','category','image']
views.py :
def CreateListing(request):
user = request.user
if request.method == "POST":
form = create(request.POST, instance=user)
if form.is_valid():
new_listing = form.save()
new_listing.user = request.user
new_listing.save()
return render(request, "auctions/listing.html")
else:
return render(request, "auctions/Create.html",{
"form": create
})
Ps: I have no problem with my urls.py
You need to set the user before you can save this to the database:
def CreateListing(request):
user = request.user
if request.method == "POST":
form = create(request.POST, instance=user)
if form.is_valid():
form.instance.user = user
form.save()
return redirect('%name-of-some-view')
else:
form = create(instance=user)
return render(request, "auctions/Create.html",{
'form': form
})
Note: You can limit views to a view to authenticated users with the
#login_required decorator [Django-doc].
Note: In case of a successful POST request, you should make a redirect
[Django-doc]
to implement the Post/Redirect/Get pattern [wiki].
This avoids that you make the same POST request when the user refreshes the
browser.

rendered form isnt saving any input into database, why isnt it working?

I tryed to add validation to ContactModel, by doing Forms.py but I went too far away with it and now dont know to fix it. Can someone help ?
def addContact(request):
form = ContactForm()
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
# form = Contact(
# full_name = request.POST ('fullname'),
# relationship = request.POST ('relationship'),
# email = request.POST ('email'),
# phone_number = request.POST ('phone-number'),
# address = request.POST ('address'),
# )
form.save()
return redirect('/contact')
context = {'form': form}
return render(request, 'contact/new.html', context)
def contactProfile(request,pk):
contact = Contact.objects.get(id=pk)
return render(request, 'contact/contact-profile.html', {'contact': contact})
In my opinion in Views I have big mess.. When I fill up all fields data isn't sending to database.
forms.py:
from django.forms import ModelForm
from .models import Contact
class ContactForm(ModelForm):
class Meta:
model = Contact
fields = '__all__'
models.py:
from django.db import models
# Create your models here.
class Contact(models.Model):
full_name = models.CharField(max_length=500)
relationship = models.CharField(max_length=50)
email = models.EmailField(max_length=254)
phone_number =models.CharField(max_length=20)
address = models.CharField(max_length=100)
def __str__(self):
return self.full_name
It seems that your form is not valid and it redirects always to contact.
You should to use redirect only if the form is valid. Otherwise you will never see which errors your form contains.
Try the following code:
def addContact(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
form.save()
return redirect('/contact')
else:
form = ContactForm()
context = {'form': form}
return render(request, 'contact/new.html', context)

Django python setting initial values dynamically to form

I'm building a small web service for inventory control. As part of this, I want to populate a detail view for any of the inventory items. This is what I have so far for that:
class Product_Update(forms.Form):
Product_Code = forms.CharField(
max_length=10,
attrs={"placeholder = <ID here> Readonly = True"
)
Name = forms.CharField(max_length=100)
Description = forms.Textarea(attrs={"Rows": 3})
price = forms.DecimalField()
mini = forms.IntegerField()
Max = forms.IntegerField()
How do I pass the form the parameters?
You should use a ModelForm instead:
class ProductUpdate(forms.Form):
class Meta:
model = Product
fields = ('product_code', 'name', 'description', 'price', 'mini', 'max')
Now you can easily pass a model instance to your form:
def some_view(request):
instance = Product.objects.first()
form = ProductUpdate(request.POST or None, instance=instance)
context = {'form':form}
return render(request, 'some_template.html', context)
If you want to show multiple products in the same form, you will need to use modelformset_factory:
from django import forms
ProductFormSet = forms.modelformset_factory(Product, form=ProductUpdate, extra=0)
Now in your views.py, you can pass a QuerySet to your form:
def some_view(request):
queryset = Product.objects.all()
form = ProductFormSet(request.POST or None, queryset=queryset)
if request.method == 'POST' and form.is_valid():
form.save()
context = {'form':form}
return render(request, 'some_template.html', context)
You can access the form's data in the view by accessing request.POST
def actionView(request, product_id):
product = Product.objects.get(id=product_id)
form = ProductUpdate(request.POST, instance=product_id)
form.save(commit=False) #Do this if you want to make changes to some value
form.price = 112233
updated_form = form.save()

How do I save m2m field session from a form to another?

I'm doing a multi step form where everything is saved at the end. In my models I have a m2m checkbox field and I'm using django Sessions to grab the forms datas to show it on the final step.
The issue is that the m2m field (checkboxes) is not saved when I submit the final form.
Here is my views file :
views.py
def step1(request):
initial={'name': request.session.get('name', None), 'checkbox': request.session.get('checkbox', (False,))} #cookies
form = FormOneForm(request.POST or None, initial=initial)
if request.method == 'POST':
if form.is_valid():
request.session['name'] = form.cleaned_data['name']
request.session['checkbox'] = form.cleaned_data.get('checkbox')
return HttpResponseRedirect(reverse('step2'))
return render(request, 'step1.html', {'form': form})
def step2(request):
form = FormTwoForm(request.POST or None)
if request.method == 'POST':
if form.is_valid():
formtwo = form.save(commit=False)
formone2 = FormOne.objects.create(checkbox=request.session.get('checkbox')) #error is here
formone = FormOne.objects.create(name=request.session['name'])
formtwo.owner = formone
formtwo.save()
formone2.save_m2m()
return HttpResponseRedirect(reverse('step3'))
return render(request, 'step2.html', {'form': form})
models.py
class Font(models.Model):
font_name = models.CharField(max_length=100)
font_family = models.CharField(max_length=100)
font_link = models.CharField(max_length=100)
...
class FormOne(models.Model):
name = models.CharField(max_length=40)
checkbox = models.ManyToManyField(Font, blank=True)
...
class FormTwo(models.Model):
owner = models.ForeignKey(FormOne)
name = models.CharField(max_length=40)
...
this code gives me this error :
'checkbox' is an invalid keyword argument for this function
How can I achieve what I am trying to realise ?
Try to save object first:
formone2 = FormOne.objects.create(name=request.session['name'])
formone2.checkbox.add(request.session.get('checkbox')
The problem is that you need to save object before use Many-to-many relations. See docs:
You can’t associate it with a Publication until it’s been saved

Categories

Resources