can not update data in Django Form - python

I am not able to upload data in Profile.
How to Solve the problem?
models.py:
class Profile(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE, blank=True, null=True)
name = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200, null=True)
created_at = models.DateField(auto_now_add=True)
alamat = models.CharField(max_length=200, null=True)
no_tlp = models.IntegerField(default=0)
wilayah = models.CharField(max_length=200, null=True)
j_kel = models.CharField(max_length=200, null=True)
pic_Profile = models.ImageField(upload_to='profil/',default="person-circle.svg",null=True, blank=True)
def __str__(self):
return str(self.id)
forms.py:
class Uplaoddata(ModelForm):
no_tlp = forms.CharField(label='No Telpon', max_length=100)
wilayah = forms.ChoiceField(label =("Wilayah"),widget=forms.Select, choices=wilayah ,help_text="<style>.errorlist{display:None} </style>")
j_kel = forms.ChoiceField(label = ("Jenis Kelamin"),widget=forms.Select, choices=Jenis ,help_text="<style>.errorlist{display:None} </style>")
pic_Profile = forms.ImageField(label='Foto Profil', max_length=100)
class Meta:
model=Profile
fields=["email", "name", "alamat", "no_tlp", "wilayah", "j_kel", "pic_Profile"]
views.py:
def home(request):
data = cartData(request)
cartItems = data['cartItems']
id_profil = request.user.profile
profiles = Profile.objects.get(id__contains=id_profil)
if request.method == "POST":
form = Uplaoddata(request.POST ,request.FILES, instance=profiles)
if form.is_valid():
form.save()
else:
form=Uplaoddata(instance=profiles)
print("Data Tidak terupdate")
context = {'profiles':profiles,'form':form, 'cartItems':cartItems}
return render(request, 'home.html',context)

Ok, probably you should remove instance=profiles inside the if statement.
def home(request):
data = cartData(request)
cartItems = data['cartItems']
id_profil = request.user.profile
profiles = Profile.objects.get(id__contains=id_profil)
if request.method == "POST":
form = Uplaoddata(request.POST ,request.FILES)
if form.is_valid():
form.save()
else:
form=Uplaoddata(instance=profiles)
print("Data Tidak terupdate")
context = {'profiles':profiles,'form':form, 'cartItems':cartItems}
return render(request, 'home.html',context)

Related

Getting error during adding a comment as notnull

I don't understand why I am getting this one I tried making null=True, blank=True but still, it does not solve my error, at last, I thought of sending it here ...!! please tell me where I am going wrong
Models.py
class Certification(models.Model):
id = models.UUIDField(default=uuid.uuid4,
unique=True, primary_key=True, editable=False)
course_name = models.CharField(max_length=255)
course_image = models.ImageField()
course_taken = models.CharField(max_length=255)
mentor_name = models.CharField(max_length=20, blank=True, null=True)
slug = models.SlugField(unique=True, null=True)
#body = RichTextField()
body = RichTextUploadingField()
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.course_name
class Comment(models.Model):
certificate = models.ForeignKey(Certification, on_delete=models.CASCADE)
name = models.CharField(max_length=200)
body = models.TextField(null=True, blank=True)
forms.py
class CommentForm(ModelForm):
class Meta:
model = Comment
fields = '__all__'
exclude = ['certificate']
def __init__(self, *args, **kwargs):
super(CommentForm, self).__init__(*args, **kwargs)
self.fields['name'].widget.attrs.update(
{'class': 'form-control form-control-sm',})
self.fields['body'].widget.attrs.update(
{'class': 'form-control form-control-sm',})
Views.py
def certificatePage(request,pk):
certi = Certification.objects.get(id=pk)
count = certi.comment_set.count()
comments = certi.comment_set.all()
form = CommentForm()
if request.method == "POST":
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.certi = certi
comment.save()
context = {
"certi": certi,
'count':count,
'comments':comments,
'form':form
}
return render (request, 'base/certificate.html',context)
Click On The Image To See The Error

Django AttributeError at /company-registration/

I have a User model, an ApplicantProfile model, and a CompanyProfielModel. A user can be of two types, an applicant or a company.
models.py
class User(AbstractBaseUser):
email = models.EmailField(max_length=255, unique=True)
name = models.CharField(max_length=255)
date_joined = models.DateTimeField(auto_now_add=True)
is_applicant = models.BooleanField(default=False)
is_company = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_admin = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['name']
objects = MyUserManager()
def __str__(self):
return self.email
def has_perm(self, perm, obj=None):
return True
def has_module_perms(self, app_label):
return True
class ApplicantProfile(models.Model):
GENDER_MALE = 0
GENDER_FEMALE = 1
GENDER_CHOICES = [(GENDER_MALE, 'Male'), (GENDER_FEMALE, 'Female')]
user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
image = models.ImageField(upload_to=image_directory_path, storage=image_storage, null=True, blank=True)
bio = models.TextField(max_length=500, null=True, blank=True)
address = models.TextField(max_length=200, null=True, blank=True)
birth_date = models.DateField(null=True, blank=True)
phone = PhoneNumberField(null=True, blank=True)
website = models.URLField(max_length=255, null=True, blank=True)
gender = models.IntegerField(choices=GENDER_CHOICES, null=True, blank=True)
interest = models.TextField(max_length=255, null=True, blank=True)
linkedin = models.CharField(max_length=255, null=True, blank=True)
github = models.CharField(max_length=255, null=True, blank=True)
twitter = models.CharField(max_length=255, null=True, blank=True)
facebook = models.CharField(max_length=255, null=True, blank=True)
def __str__(self):
return self.user.name
class CompanyProfile(models.Model):
user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
image = models.ImageField(upload_to=image_directory_path, storage=image_storage, null=True, blank=True)
about = models.TextField(max_length=500, null=True, blank=True)
location = models.CharField(max_length=100, null=True, blank=True)
start_date = models.DateField(null=True, blank=True)
website = models.URLField(max_length=255, null=True, blank=True)
logo = models.ImageField(upload_to=image_directory_path, storage=image_storage, null=True, blank=True)
def __str__(self):
return self.user.name
I have two URLs to create two different types of users. I can create applicants automatically right after a user registers from the applicant registration url, but I can't create companies from the company registration url.
views.py
def applicant_register(request):
if request.method == 'POST':
form = ApplicantRegistrationForm(request.POST)
if form.is_valid():
form.save()
email = form.cleaned_data.get('email')
raw_password = form.cleaned_data.get('password1')
user = authenticate(email=email, password=raw_password)
ApplicantProfile.objects.create(user=user)
messages.success(request, "Account created successfully.")
return redirect('applicant-feed')
form = ApplicantRegistrationForm()
context = {
"form": form
}
return render(request, 'user/applicant/applicant-register.html', context)
def company_register(request):
if request.method == 'POST':
form = CompanyRegistrationForm(request.POST)
if form.is_valid():
form.save()
email = form.cleaned_data.get('email')
raw_password = form.cleaned_data.get('password1')
user = authenticate(email=email, password=raw_password)
CompanyProfile.objects.create(user=user) # This line gives the error
messages.success(request, "Account created successfully.")
return redirect('company-feed')
form = CompanyRegistrationForm()
context = {
"form": form
}
return render(request, 'user/company/company-register.html', context)
Any help is appreciated.
Getting this error in the browser
According to error, looks like CompanyProfile is not a model class but something else. Is there a chance that you redefine it in views.py? Probably you also define a view with this name?
you don't need to use the form because you can create an account directly to any model like this function
def company_register(request):
if request.method == 'POST':
user = request.POST['user']
image = request.FILES['image']
about = request.POST['about']
location = request.POST['location']
start_date = request.POST['start_date']
website = request.POST['website']
logo = request.FILES['logo']
profile = CompanyProfile.objects.create(user=user, image=image, about=about, location=location, start_date=start_date, website=website, logo=logo)
profile.save()
return Response('Done')
else:
return Response('POST method only accepted')

How to get fields of foreign key

In models.py:
class Comment(models.Model):
item = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='comments')
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
body = models.TextField()
rating = models.FloatField(null=True)
aggregate = models.FloatField(null=True)
date = models.DateTimeField(auto_now_add=True)
class Item(models.Model):
id_item = models.AutoField(primary_key='true')
item_name = models.CharField(max_length=100, null=False)
slug = models.SlugField(max_length=250, blank=True, null=True)
item_description = models.TextField()
item_img = models.ImageField(blank=True, null=True, upload_to="static/item/cover/")
tags = TaggableManager()
In views.py:
def detail(request, slug_text):
details = Item.objects.filter(slug=slug_text)
if details.exists():
reviews = Comment.objects.filter(item=slug_text)
details = details.first()
average = reviews.aggregate(Avg("rating"))["rating_avg"]
average = round(average, 2)
form = CommentForm()
if request.method == "POST":
form = CommentForm(request.POST, author=request.user, item=details)
if form.is_valid():
form.save()
return HttpResponseRedirect(slug_text)
else:
return HttpResponse('<h1>Trang không tồn tại</h1>')
return render(request, 'homepage/detail.html', {'detail': details, 'form': form, 'average': average})
What if I want to get the item.slug = slug_text field in here?
reviews = Comment.objects.filter(item=slug_text)
You not far from it, to get data from a foreignkey you use double under score __ i.e: to get item slug use item__slug see below
reviews = Comment.objects.filter(item__slug=slug_text)
All the best.

How to link guest and user checkout together?

I'm very new to Django and I'm confused with the checkout. I have the "accounts" app for the user to enter their profile and I want to link it with the checkout but also include guest checkout. Right now I'm good to the guest-checkout but I cant link the user info from "accounts" app to the checkout.
The is the error I am getting:
IntegrityError at /usercheckout/
NOT NULL constraint failed: accounts_profile.user_id "
accounts/models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
first_name = models.CharField(max_length=255, default='')
last_name = models.CharField(max_length=255, default='')
email = models.EmailField(default='none#email.com')
birth_date = models.DateField(default='1999-12-31')
address = models.TextField(default='')
mobile = models.CharField(max_length=255, default='')
def __str__(self):
return self.user.username
def __str__(self):
return 'Order {}'.format(self.id)
def create_profile(sender, **kwargs):
if kwargs['created']:
profile = Profile.objects.create(user=kwargs['instance'])
post_save.connect(create_profile, sender=User)
orders/models.py
class Order(models.Model):
first_name = models.CharField(max_length=60)
last_name = models.CharField(max_length=60)
email = models.EmailField()
address = models.CharField(max_length=150)
postal_code = models.CharField(max_length=30)
city = models.CharField(max_length=100)
mobile = models.IntegerField(default=0)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
paid = models.BooleanField(default=False)
class Meta:
ordering = ('-created', )
def __str__(self):
return 'Order {}'.format(self.id)
def get_total_cost(self):
return sum(item.get_cost() for item in self.items.all())
class OrderItem(models.Model):
order = models.ForeignKey(Order, related_name='items', on_delete=models.CASCADE)
orderu = models.OneToOneField(Profile, on_delete=models.CASCADE)
product = models.ForeignKey(Product_info, related_name='order_items', on_delete=models.CASCADE)
price = models.DecimalField(max_digits=10, decimal_places=2)
quantity = models.PositiveIntegerField(default=1)
def __str__(self):
return '{}'.format(self.id)
def get_cost(self):
return self.price * self.quantity
orders/views.py
def guestcheckout(request):
cart = Cart(request)
if request.method == 'POST':
form = OrderCreateForm(request.POST)
if form.is_valid():
order = form.save()
for item in cart:
OrderItem.objects.create(
order=order,
product=item['product'],
price=item['price'],
quantity=item['quantity']
)
cart.clear()
return render(request, 'order/created.html', {'order': order})
else:
form = OrderCreateForm()
return render(request, 'order/create.html', {'form': form,"cart":cart})
def choose_checkout(request):
return render(request,'order/chooserequest.html',)
#login_required
def usercheckout(request):
cart = Cart(request)
if request.method == 'POST':
form = ProfileForm(request.POST)
if form.is_valid():
order = form.save()
for item in cart:
OrderItem.objects.create(
orderu=order,
product=item['product'],
price=item['price'],
quantity=item['quantity']
)
cart.clear()
return render(request, 'order/created.html',{'order': order})
else:
user = request.user
profile = get_object_or_404(Profile, user=user)
form = ProfileForm(instance=profile)
return render(request, 'order/usercheckoutnormal.html', {'form': form,"cart":cart})
Its because your OneToOneField of user is null. Set a user before saving the form, let say -
#login_required
def usercheckout(request):
cart = Cart(request)
user = request.user
profile = get_object_or_404(Profile, user=user)
if request.method == 'POST':
form = ProfileForm(request.POST,instance=profile)
if form.is_valid():
order = form.save()
for item in cart:
OrderItem.objects.create(
orderu=order,
product=item['product'],
price=item['price'],
quantity=item['quantity']
)
cart.clear()
return render(request, 'order/created.html',{'order': order})
else:
form = ProfileForm(instance=profile)
return render(request, 'order/usercheckoutnormal.html', {'form': form,"cart":cart})

Update already existing data in database

I am trying to use the "update ()" to update existing data in the data base of the "ModelC".
Models:
from django.db import models
class ModelA(models.Model):
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
def __str__(self):
return '%s' %(self.id)
class ModelB(models.Model):
observation = models.CharField(max_length=30)
status = models.BooleanField()
relation = OneToOneField(ModelA)
def __str__(self):
return '%s' %(self.relation)
class ModelC(models.Model):
relationA = models.ForeignKey('ModelA', null=True, blank=True)
date_relationA = models.CharField(max_length=10, null=True, blank=True)
user_relationA = models.CharField(max_length=15, null=True, blank=True)
relationB = models.ForeignKey('ModelB', null=True, blank=True)
date_relationB = models.CharField(max_length=10, null=True, blank=True)
user_relationB = models.CharField(max_length=15, null=True, blank=True)
def __str__(self):
return str(self.id)
Views of the ModelA:
def RegModelA(request):
form = ""
user = None
if request.method == "POST":
form = ModelAForm(request.POST)
if form.is_valid():
save = form.save()
date = time.strftime("%d - %m - %Y")
user = request.user.username
create = ModelC.objects.create(relationA=save, date_relationA=date, user_relationA=user, relationB=None, date_relationB=None, user_relationB=None)
return redirect('/')
else:
form = ModelAForm
return render(request, "ModelA.html", {"form":form})
**Result when registering ModelA:**
In ModelA:
Image of the result
In ModelC:
Image of the result
Views of the ModelB:
def RegModelB(request):
form = ""
user = None
if request.method == "POST":
form = ModelBForm(request.POST)
if form.is_valid():
save = form.save()
date = time.strftime("%d - %m - %Y")
user = request.user.username
update = ModelC.objects.filter().update(relationB=save, date_relationB=date, user_relationB=user)
return redirect('/')
else:
form = ModelBForm
return render(request, "ModelB.html", {"form":form})
What I am looking for is that when registering the data of the ModelB, the fields of the relationB in the ModelC are updated.
But I can not find how to obtain the ID of the ModelC, if the relation of the ModelB is equal to the field relationA in the ModelC.
I'm using:
Python 3.5
Django 1.11

Categories