NOT NULL constraint failed: cars_car.owner_id - django

I was able to render the form onto the html, input data and submit it but i got a NOT NULL constraint failure. Isn't the owner assigned to its respective owners when as i have indicated in my views? i do not know what is wrong here please help!
Models
class Car(models.Model):
owner = models.ForeignKey('auth.User', on_delete=models.CASCADE)
name = models.CharField(max_length=100)
model = models.CharField(max_length=100)
description = models.TextField()
image = models.ImageField(upload_to=upload_image_path, null=True, blank=True)
created = models.DateField(auto_now_add=True)
updated = models.DateField(auto_now_add=False)
mileage = models.IntegerField()
open_market_value = models.DecimalField(max_digits=12, decimal_places=2)
depreciation = models.DecimalField(max_digits=10, decimal_places=2)
down_payment = models.DecimalField(max_digits=10, decimal_places=2)
road_tax = models.DecimalField(max_digits=8, decimal_places=2)
installment = models.DecimalField(max_digits=8, decimal_places=2)
objects = models.Manager()
def __str__(self):
return self.name
Views
class CarCreate(CreateView):
model = Car
fields = [
'name', 'model',
'description', 'image',
'updated', 'mileage',
'open_market_value', 'depreciation',
'down_payment', 'road_tax',
'installment']
template_name = 'cars/create_car.html'
def form_valid(self, form):
form.instance.created_by = self.request.user
return super().form_valid(form)
HTML
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<!-- Default form contact -->
<form action="{% url 'cars:create' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{form | crispy}}
<input type="submit" value="save">
</form>
<!-- Default form contact -->
{% endblock %}

Your model has a foreign key to the User model from 'django.auth'. While you are trying to save the object of 'Car' model as there was no object mentioned for the 'owner' field of the model, it is showing the error. So, you might want to explicitly mention it.
You can do something like this. Assuming that you have 'CarForm', a model form for you 'Car' model.
user = request.user
car_form = CarForm(request.POST)
if car_form.is_valid():
car = car_form.save(False)
car.owner = user
car.save()

This is most likely because owner is a required field in your model Car but you have not included it in the fields in your CreateView.

Related

Django Saving form with two foreign keys

I am attempting to save a form that submits data (project note comments) linked to another model (project notes) via foreign key (project notes). Project notes are linked via foreign key to another model (projects). I thought I would only need to consider the immediate relationship (project notes). However from the error I am getting, I also need to process the relationship from project notes to project.
The error:
IntegrityError at /projects/note/1/add_project_note_comment/
insert or update on table "company_project_projectnotes" violates foreign key constraint "company_project_proj_project_id_478f433c_fk_company_p"
DETAIL: Key (project_id)=(0) is not present in table "company_project_project".
The models:
class Project(models.Model):
title = models.CharField(max_length= 200)
description = tinymce_models.HTMLField()
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse ('project_detail', args=[str(self.id)])
class ProjectNotes(models.Model):
title = models.CharField(max_length=200)
body = tinymce_models.HTMLField()
date = models.DateField(auto_now_add=True)
project = models.ForeignKey(Project, default=0, blank=True, on_delete=models.CASCADE, related_name='notes')
def __str__(self):
return self.title
class ProjectNoteComments(models.Model):
body = tinymce_models.HTMLField()
date = models.DateField(auto_now_add=True)
projectnote = models.ForeignKey(ProjectNotes, default=0, blank=True, on_delete=models.CASCADE, related_name='notes')
The view:
class ProjectNotesCommentCreateView(CreateView):
model = ProjectNotes
template_name = 'company_accounts/add_project_note_comment.html'
fields = ['body']
def form_valid(self, form):
projectnote = get_object_or_404(ProjectNotes, id=self.kwargs.get('pk'))
comment = form.save(commit=False)
comment.projectnote = projectnote
comment.save()
return super().form_valid(form)
def get_success_url(self):
return reverse('project_detail', args=[self.kwargs.get('pk')])
The URL pattern:
path('note/<int:pk>/add_project_note_comment/', ProjectNotesCommentCreateView.as_view(), name='add_project_note_comment'),
The template:
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<h1>Add Comment</h1>
<form action="" method="post">
{% csrf_token %}
{{ form.media }}
{{ form|crispy }}
<input type="submit" value="save">
</form>
{% endblock content %}
Any ideas on how to get this to work?
You won't have a relationship with pk field of the ProjectNoteComments with the ProjectNote model and the related names are same for both models, you might want to fix that.
Moreover, you are delaying commiting the form only for ProjectNote, but you also have to handle it for Project model too through backward referencing projectnote__project (related names may cause problem at this place.

Django how to get model values inside another model?

I want the value of username from forms that I get as a string so that when I upload an image it is stored in a subdirectory with that username.
i.e. if 'bob' registers the image should be saved in 'static/auth_image/bob/image_name.extension'.
Also if I could it during the registration form filling that would be great.
models.py
class User_data(models.Model):
username = models.CharField(max_length=256, null=True, blank=True)
email = models.EmailField(max_length=254, null=True, blank=True)
four_digit_pass = models.CharField(max_length=256, null=True, blank=True)
private_key = models.CharField(max_length=256, null=True, blank=True)
profile_pic = models.ImageField(upload_to='static/profilepic', null=True)
def getUsername(self):
return self.username
def __str__(self):
return str(self.username)
class AuthImages(models.Model):
owner = models.ForeignKey('User_data', null=True, on_delete=models.CASCADE)
uname=owner.
def save_auth_image(self):
uname = self.username
self.auth_image_file = models.ImageField(
upload_to='static/auth_image/%s' % uname, null=True)
forms.py
class RegistrationForm(forms.ModelForm):
four_digit_pass = forms.CharField(widget=forms.PasswordInput())
class Meta:
model = User_data
fields = ['username', 'email', 'four_digit_pass',
'profile_pic', 'private_key']
register.html
{% extends "storage_app/base.html" %}
{% block body_block %}
<div class="jumbotron">
<h1>Register Page</h1>
</div>
<div>
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<p>Private Key should not be changed or shared with anyone</p>
<button type="submit">Upload</button>
</form>
</div>
{% endblock body_block %}
here in HTML, i want to take input for the second i.e. auth_image directly from webcam if possible
This is my first question also I am new to Django so please help me out if there is a cleaner way to write this and please excuse any mistakes.

form not saving data in db

i'm creating a form for product create and i have 5 image fields in product model ,user can upload 5 or 0 images as per requirement , but form is not saving data
python
models.py
class Category(models.Model):
cate_id = models.AutoField(primary_key=True)
category_name = models.CharField(max_length=45)
class Product(models.Model):
product_id = models.AutoField(primary_key=True)
product_name = models.CharField(max_length=45)
product_description = models.CharField(max_length=500, blank=True, null=True)
price = models.IntegerField()
quantity = models.IntegerField()
product_category_fk = models.ForeignKey('Category', on_delete=models.CASCADE,db_column='product_category_fk',related_name='pros')
image1 = models.ImageField(upload_to='chand_imgs',blank=True)
image2 = models.ImageField(upload_to='chand_imgs',blank=True)
image3 = models.ImageField(upload_to='chand_imgs',blank=True)
image4 = models.ImageField(upload_to='chand_imgs',blank=True)
image5 = models.ImageField(upload_to='chand_imgs',blank=True)
#forms.py
class CategoryForm(forms.ModelForm):
category_name = forms.CharField(max_length=50)
class Meta:
model = Category
fields = ('category_name', )
class ProductForm(forms.ModelForm):
class Meta():
model = Product
fields = ('product_category_fk','product_name','product_description','price','quantity','image1','image2','image3','image4','image5',)
#views.py
#login_required
def product_management(request):
form = ProductForm(data=request.POST)
if request.method =='POST':
if form.is_valid():
post=form.save(commit=True)
if 'picture' in request.FILES:
form.picture =request.FILES['picture']
return HttpResponseRedirect(reverse('index'))
else:
return render(request,'chandler/index.html',{'form':form})
else:
form = ProductForm()
return render(request,'chandler/product.html',{'form':form})
#product.html
{% if user.is_authenticated %}
<form method=”post” enctype=”multipart/form-data” action="" >
<h2>New post</h2>
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default">Save</button>
</form>
{% else %}
<h2>Please login first!!!!</h2>
{% endif %}
form not saving any data i know my view is incorrect ,already tried different methods
change
<form method=”post” enctype=”multipart/form-data” action="" >
to
<form method="post" enctype="multipart/form-data" action="" >

Django display related count

i currently try to display who many posts a category has.
Therefor i created the Post Model and the Category Model (See below):
models.py
# Categorys of Post Model
class Category(models.Model):
title = models.CharField(max_length=255, verbose_name="Title")
class Meta:
verbose_name = "Category"
verbose_name_plural = "Categories"
ordering = ['title']
def __str__(self):
return self.title
#Post Model
class Post(models.Model):
author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
title = models.CharField(max_length=200)
text = models.TextField(max_length=10000)
category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE, null=True)
tag = models.CharField(max_length=50, blank=True)
postattachment = fields.FileField(upload_to='postattachment/%Y/%m/%d/', blank=True, null=True)
postcover = fields.ImageField(upload_to='postcover/%Y/%m/%d/', blank=True, null=True, dependencies=[
FileDependency(processor=ImageProcessor(
format='JPEG', scale={'max_width': 300, 'max_height': 300}))
])
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
category_list.html
{% extends 'quickblog/base.html' %}
{% block content %}
{% for categories in categories %}
<div>
<h1><u>{{ categories.title }} {{ $NumCountGetHere }}</u></h1>
</div>
{% endfor %}
{% endblock %}
Now i have no idea how to get the related objects counted...?
You can use something like this:
{% for cat in categories %}
<div>
<h1><u>{{ cat.title }} {{ cat.post_set.count }}</u></h1>
</div>
{% endfor %}
The model Post has a Foreignkey field to the model Category. You can access the related Post instances from a given Category instance using the manager category_instance.post_set. Read about it in the docs.
Finally, we use the method .count() on this manager to get the number of related posts for that given category. This way the code ends up looking like {{ cat.post_set.count }}.

Django - form field does not pass validation

models.py
class Location(models.Model):
name = models.CharField(max_length=100, verbose_name=u"Локация", default=u'')
country = models.ForeignKey("Country")
class Country(models.Model):
name = models.CharField(max_length=50, verbose_name=u"Страна")
class Photo(models.Model):
location = models.ForeignKey(Location, null=True, verbose_name=u'Фото')
photo = models.ImageField(upload_to='photos', null=True)
forms.py
class LocationForm(forms.ModelForm):
class Meta:
model = Location
fields = ['name', 'country']
photos = MultiFileField(min_num=1, max_num=10)
def save(self, commit=True):
instance = super(LocationForm, self).save(commit)
for each in self.cleaned_data['photos']:
Photo.objects.create(photo=each, location=instance)
return instance
views.py
class AddLocationPageView(CreateView):
model = Location
form_class = LocationForm
template_name = 'add_location.html'
class BrowseLocationsPageView(ListView):
model = Country
context_object_name = 'countries'
template_name = "browse_locations.html"
add_location.html
<form action="" method="POST">{% csrf_token %}
{{ form|crispy }}
<button class="btn btn-default" type="submit">Add</button>
</form>
browse_locations.html
{% for country in countries %}
{{ country }}
{% endfor %}
While creating Location object the form field says: "Select a valid choice. That choice is not one of the available choices."
Of course, I do not have any choices, because the design is - if Country is absent in DB, it has to be created during Location creating, and in opposite case (Country is in DB, because someone created it before when he was creating Location) it has to be joined to Location.