django UpdateView not saving form - django

All my CreateViews are working fine, but this one is not (although this is UpdateView). After checking, trying to identify differences, I find none. Must be something I'm still missing.
Template:
<form method="POST">{% csrf_token %}
{{ form.non_field_errors }}
{{ form.errors }}
{{ form.make }}
{{ form.make.errors }}
{{ form.model}}
{{ form.model.errors }}
{{ form.year}}
{{ form.year.errors }}
<button type="submit"> Save</button>
Close
</form>
Url paterns in URLS.py:
url(r'^update/(?P<pk>\w+)/$',UpdateView.as_view(
model=Vehicles,
form_class=VehiclesForm,
success_url="/main/",
template_name="vehicle_detail.html")),
Model:
from django.db import models
class Vehicles(models.Model):
stock = models.CharField(max_length=10, blank=False, db_index=True)
vin = models.CharField(max_length=17, blank=False, db_index=True)
vinlast8 = models.CharField(max_length=8, blank=False, db_index=True)
make = models.CharField(max_length=15, blank=False)
model = models.CharField(max_length=15, blank=False)
year = models.CharField(max_length=4, blank=False)
deal = models.IntegerField(blank=False, db_index=True, null=True)
sold = models.DateField(blank=True, null=True, db_index=True)
origin = models.ForeignKey('origins.Origins', db_column='origin')
#origin = models.CharField(max_length=10, blank=True)
bank = models.ForeignKey('banks.Banks', db_column='bank', null=True)
vehtype = models.ForeignKey('vehtypes.Vehtypes', db_column='vehtype', verbose_name='Veh Type')
status = models.ForeignKey('status.Status', db_column='status')
imported = models.DateField()
clerk = models.CharField(max_length=10, blank=False, db_index=True, verbose_name='Clerk')
completed = models.DateField(blank=True, null=True)
registry = models.IntegerField(blank=True, verbose_name='Reg #', null=True)
plate = models.CharField(blank=True, null=True, max_length=10)
tagno = models.IntegerField(blank=True, null=True, verbose_name='Tag #')
tag_exp = models.DateField(blank=True, null=True, verbose_name='Tag Exp')
unit_linked = models.IntegerField(blank=False, verbose_name='Link')
salesperson = models.CharField(max_length=20, blank=False, verbose_name='S/person', null=True)
agent = models.ForeignKey('agents.Agents', db_column='agent', blank=True, null=True)
tradein1 = models.CharField(max_length=10, blank=True, null=True, verbose_name='stock')
tr1vin = models.CharField(max_length=17, blank=True, db_index=True, null=True, verbose_name='vin')
tr1make = models.CharField(max_length=15, blank=True, null=True, verbose_name='make')
tr1model = models.CharField(max_length=15, blank=True, null=True, verbose_name='model')
tr1year = models.CharField(max_length=4, blank=True, null=True, verbose_name='year')
tradein2 = models.CharField(max_length=10, blank=True, null=True, verbose_name='stock')
tr2vin = models.CharField(max_length=17, blank=True, db_index=True, null=True,verbose_name='vin')
tr2make = models.CharField(max_length=15, blank=True, null=True,verbose_name='make')
tr2model = models.CharField(max_length=15, blank=True, null=True,verbose_name='model')
tr2year = models.CharField(max_length=4, blank=True, null=True,verbose_name='year')
lhtrade1 = models.CharField(max_length=15, blank=True, null=True, verbose_name='L/holder')
lh1docreq = models.DateField(blank=True, null=True, verbose_name='D/Requested')
lh1docrec = models.DateField(blank=True, null=True, verbose_name='D/Received')
lhtrade2 = models.CharField(max_length=15, blank=True, null=True, verbose_name='L/holder')
lh2docreq = models.DateField(blank=True, null=True, verbose_name='D/Requested')
lh2docrec = models.DateField(blank=True, null=True, verbose_name='D/Received')
cust1name = models.CharField(max_length=40, blank=True, db_index=True, null=True,
verbose_name='name')
cust1lic = models.CharField(max_length=20, blank=True, db_index=True, null=True,
verbose_name='license')
cust1addr = models.CharField(max_length=40, blank=True, null=True, verbose_name='address')
cust1city = models.CharField(max_length=15, blank=True, null=True, verbose_name='city')
cust1state = models.CharField(max_length=2, blank=True, null=True, verbose_name='state')
cust1zip = models.CharField(max_length=10, blank=True, null=True, verbose_name='zipcode')
cust1email = models.EmailField(blank=True, null=True, verbose_name='email')
cust1tel1 = models.CharField(max_length=15, blank=True, verbose_name='Tel. 1', null=True)
cust1tel2 = models.CharField(max_length=15, blank=True, verbose_name='Tel. 2', null=True)
cust1ssn = models.CharField(max_length=12, blank=True, db_index=True, null=True,verbose_name='SSN')
cust2name = models.CharField(max_length=30, blank=True, db_index=True, null=True,
verbose_name='name')
cust2lic = models.CharField(max_length=20, blank=True, db_index=True, null=True,
verbose_name='license')
cust2addr = models.CharField(max_length=25, blank=True, null=True, verbose_name='address')
cust2city = models.CharField(max_length=15, blank=True, null=True, verbose_name='city')
cust2state = models.CharField(max_length=2, blank=True, null=True, verbose_name='state')
cust2zip = models.CharField(max_length=10, blank=True, null=True, verbose_name='zipcode')
cust2email = models.EmailField(blank=True, null=True, verbose_name='email')
cust2tel1 = models.CharField(max_length=15, blank=True, verbose_name='Tel. 1', null=True)
cust2tel2 = models.CharField(max_length=15, blank=True, verbose_name='Tel. 2', null=True)
cust2ssn = models.CharField(max_length=12, blank=True, db_index=True, null=True,verbose_name='SSN')
class Meta:
db_table = 'vehicles'
def __unicode__(self):
return self.stock
def save(self, *args, **kwargs):
self.stock = self.stock.upper()
return super(Vehicles, self).save(*args, **kwargs)
Form:
from django import forms
from models import Vehicles
class VehiclesForm(forms.ModelForm):
class Meta:
model = Vehicles
It's a modelform. Firebug and console do report the POST is actually occuring, but record is not updated.
Appreciate anything you realize it's wrong.

Since, there is no answer...
At first, since you don't modify in any way your form you don't to specify it - ModelForm is implicitly meant in UpdateView by default. So, you don't need this:
form_class=VehiclesForm
Then, in your model (which is huge) you don't need blank=False - it's also defaults.
Your problem, I think, is in field validation procedure. Your template html-form renders only some of fields, but your model has much more (and what is important - they aren't optional and they have no default values).
Because of this, you simply don't see validation errors.
if you render whole form like this:
<form method="POST">{% csrf_token %}
{{ form.as_p }}
<button type="submit"> Save</button>
Close
</form>
...you'll see validation errors!
PS: If you wanted to render only those fields you must:
1) specify fields attribute with list of those fields:
# django doc example
class AuthorUpdate(UpdateView):
model = Author
fields = ['name']
template_name_suffix = '_update_form'
2) ensure that you provide all needful data (default or explicitly through form fields) for model instance saving.
3) read the Django docs - it is very detailed and meticulous, good luck!

For me I have to change
<form action="." .....>
to
<form action="" ..... >

Related

Annotate querying, pk

How should I query when I use pk with annotate?
I need to redirect to user profile when a guest click in link.
Models
class Posty(models.Model):
title = models.CharField(max_length=250, blank=False, null=False, unique=True)
sub_title = models.SlugField(max_length=250, blank=False, null=False, unique=True)
content = models.TextField(max_length=250, blank=False, null=False)
image = models.ImageField(default="avatar.png",upload_to="images", validators=[FileExtensionValidator(['png','jpg','jpeg'])])
author = models.ForeignKey(Profil, on_delete=models.CASCADE)
updated = models.DateTimeField(auto_now=True)
published = models.DateTimeField(auto_now_add=True)
T_or_F = models.BooleanField(default=False)
likes = models.ManyToManyField(Profil, related_name='liked')
unlikes = models.ManyToManyField(Profil, related_name='unlikes')
created_tags = models.ForeignKey('Tags', blank=True, null=True, related_name='tagi', on_delete=models.CASCADE)
class CommentPost(models.Model):
user = models.ForeignKey(Profil, on_delete=models.CASCADE)
post = models.ForeignKey(Posty, on_delete=models.CASCADE, related_name="comments")
content1 = models.TextField(max_length=250, blank=False, null=False)
date_posted = models.DateTimeField(default=timezone.now)
date_updated = models.DateTimeField(auto_now=True)
def __str__(self):
return str(self.content1)
class Profil(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
age = models.PositiveIntegerField(blank=True, null=True)
country = models.CharField(max_length=50)
user = models.OneToOneField(Account, on_delete=models.CASCADE)
avatar = models.ImageField(default="avatar.png", upload_to="images",validators=[FileExtensionValidator(['png', 'jpg', 'jpeg'])])
slug = models.SlugField(blank=True)
gender = models.CharField(max_length=6, choices=GENDER)
friends = models.ManyToManyField(Account, blank=True, related_name="Friends")
social_facebook = models.CharField(max_length=250, null=True, blank=True)
social_instagram = models.CharField(max_length=250, null=True, blank=True)
social_twitter = models.CharField(max_length=250, null=True, blank=True)
social_youtube = models.CharField(max_length=250, null=True, blank=True)
social_linkedin = models.CharField(max_length=250, null=True, blank=True)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
Views
if tag == None:
my_tag = Posty.objects.annotate(
latest_comment = Subquery(CommentPost.objects.filter(post=OuterRef('id')).values('content1').order_by('-date_posted')[:1]),
my_author=Subquery(CommentPost.objects.filter(post=OuterRef('id')).values('user__user__username').order_by('-date_posted')[:1]),
)
I got a correct username, but I can't get a correct redirect:
Unfortunately, you need to annotate the CommentPost's id information as well with the queryset just like you added the username information. That will end up being a lot of subquery added to the original queryset. Rather I would suggest to use prefetch related to preload the CommentPost information with the original queryset (for reducing DB hits) and directly access that information from template. For example:
# view
my_tag = Posty.objects.prefetch_related('commentpost_set')
# template
{% for post in my_tag %}
<span> {{post.commentpost_set.last.content1}}<span>
<span> {{post.commentpost_set.last.user.username}}<span>
{% endfor %}
Also, last is a queryset function which returns the last object of a given queryset. I can access the CommentPost queryset from a Posty object by reverse querying.

How to get user object in template?

model.py
class User(AbstractUser):
is_agree = models.CharField(max_length=1, blank=True)
is_verify = models.CharField(max_length=1, blank=True)
type = models.CharField(max_length=1, blank=True)
name = models.CharField(max_length=255, blank=True)
address1 = models.CharField(max_length=255, blank=True)
address2 = models.CharField(max_length=255, blank=True)
bank_account = models.CharField(max_length=255, blank=True)
phone_number = models.CharField(max_length=255, blank=True)
I want to get users type in template.
I tried {{ user.type }}. but was not worked

Column core_event.hometask does not exist

When I run my Django project on production server, I have this error:
ProgrammingError at /admin/core/event/
column core_event.hometask does not exist
LINE 1: ..._event"."is_approved", "core_event"."event_type", "core_even...
What I should do to fix it? Now I haven't "hometask" field in my model:
class Event(models.Model):
name = models.CharField(max_length=100, null=True)
author = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
description = models.TextField(max_length=1000, blank=True, null=True)
date_start = models.DateTimeField(null=True, blank=True)
date_finish = models.DateTimeField(null=True, blank=True)
image = models.ImageField(
upload_to="event_images/", default='event_images/default.png', blank=True, null=True)
is_approved = models.BooleanField(null=True)
TYPE_CHOICES = (
('Event', "Мероприятие"),
('Lesson', "Урок"),
)
event_type = models.CharField(choices=TYPE_CHOICES, max_length=200, default="Мероприятие")
topics = ArrayField(models.CharField(max_length=200), blank=True, null=True)
materials = ArrayField(models.URLField(), blank=True, null=True)
possible_users = models.ManyToManyField("core.User", blank=True, related_name='possible_users')
actual_users = models.ManyToManyField("core.User", blank=True, related_name='actual_users')
classes = models.ManyToManyField("core.Class", blank=True, related_name='classes')
From what you posted, looks like the field existed in the model before but not anymore. However, your admin.py still has reference to the old field of hometask.
So, go to admin.py, search for hometask, and remove it.

What am I missing in this Django model relationship

I have a CustomUser model, and a Blog model.
CustomUser model:
class CustomUser(AbstractUser):
email = models.EmailField(unique=True)
first_name = models.CharField(max_length=20, default="", blank=True)
last_name = models.CharField(max_length=20, default="", blank=True)
address = models.CharField(max_length=150, default="", blank=True)
city = models.CharField(max_length=20, default="", blank=True)
zip_code = models.CharField(max_length=20, default="", blank=True)
country = models.CharField( max_length=50, default="", blank=True, choices=settings.COUNTRIES_LIST)
about_me = models.TextField(max_length=225, default="", blank=True)
photo_url = models.TextField(null=True)
is_active = models.BooleanField(default=True) # can login
Blog model:
class Blog(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, null=True, verbose_name=_('user'), related_name="%(class)s_blogs", on_delete=models.SET_NULL)
blog_id = models.CharField(max_length=150, null=False, default=get_id, unique=True, editable=False)
blog_title = models.CharField(max_length=150, null=False)
blog_description = models.TextField(max_length=300, null=True, blank=True)
created_at = models.DateTimeField(auto_now=False, auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True, auto_now_add=False)
blog = FroalaField()
dynamic_link = models.CharField(max_length=225, null=False, default="")
blog_type = models.CharField( max_length=50, null=False, choices=BLOGSTYPE_LIST)
blog_status = models.CharField(max_length=150, null=False, default="unapproved")
is_active = models.BooleanField(default=False)
is_featured = models.BooleanField(default=False)
My understanding is that I could use the related_name to get all blogs by a user.
>>> from users.models import CustomerUser
>>> user = CustomUser.objects.get(pk=1)
>>> user.blog_blogs.all()
<BlogQuerySet []>
As you must have seen, this turns to always return but an empty queryset, even though there are blog entries by that user.
So is it am not understanding here?
Thank you.

function in models is unrecognizable

I trying extend existed models so I added 'thumbnails' in to it. Unfortunately function related to this is not recognized and django console gives me:
thumbnail = models.ImageField(upload_to=_get_upload_image, blank=True, null=True)
NameError: name '_get_upload_image' is not defined
Could someone help me with this issue?
Django 1.6.5 models.py (short version)
class Feed(models.Model):
link = models.CharField(blank=True, max_length=450)
url = models.CharField(blank=True, max_length=450)
title = models.CharField(blank=True, null=True, max_length=250)
category = models.ForeignKey(Category, blank=True, null=True)
user = models.ForeignKey(User, blank=True, null=True)
last_update = models.DateField(blank=True, null=True, editable=False)
country = models.ForeignKey(Country, blank=True, null=True)
thumbnail = models.ImageField(upload_to=_get_upload_image, blank=True, null=True)
class Meta:
unique_together = (
("url", "user"),
)
def _get_upload_image(instance, filename):
return "images/%s_%S" % (str(time()).replace('.','_'), filename)
I solved this through placing function on top of class
class Feed(models.Model):
def _get_upload_image(instance, filename):
return "images/%s_%S" % (str(time()).replace('.','_'), filename)
link = models.CharField(blank=True, max_length=450)
url = models.CharField(blank=True, max_length=450)
title = models.CharField(blank=True, null=True, max_length=250)
category = models.ForeignKey(Category, blank=True, null=True)
user = models.ForeignKey(User, blank=True, null=True)
last_update = models.DateField(blank=True, null=True, editable=False)
country = models.ForeignKey(Country, blank=True, null=True)
thumbnail = models.ImageField(upload_to=_get_upload_image, blank=True, null=True)