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
Related
I'm trying create a python with django project to record the username (active session), quizid, questionid, studentanswer to mysql database but receives the integrity error > "Column 'username_id' cannot be null"
models.py
class Quiz(models.Model):
questionid = models.IntegerField(null=False)
quizid = models.AutoField(primary_key=True)
subjectname = models.CharField(max_length=50)
question = models.CharField(max_length=50)
correctanswer = models.CharField(max_length=50)
eqpoints = models.IntegerField()
student = models.ManyToManyField("self", through="StudentAnswer")
teacher = models.ManyToManyField(Teacher)
class StudentAnswer(models.Model):
username = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
questionid = models.ForeignKey(Quiz, on_delete=models.CASCADE, related_name='quiz_question')
quizid = models.ForeignKey(Quiz, on_delete=models.CASCADE, related_name='quiz_id')
studentanswer = models.CharField(max_length=50)
forms.py
class StudentAnswerForm(ModelForm):
questionid = forms.ModelChoiceField(widget=forms.Select(), queryset=Quiz.objects.only('questionid'))
studentanswer = forms.CharField(widget=forms.TextInput())
quizid = forms.ModelChoiceField(widget=forms.Select(), queryset=Quiz.objects.only('quizid'))
class Meta:
model = StudentAnswer
fields = ['quizid','questionid','studentanswer']
views.py
class AnswerQuiz(View):
template = 'ansQuiz.html'
def get(self, request):
form = StudentAnswerForm()
request.session['visits'] = int(request.session.get('visits', 0)) + 1
quiz = Quiz.objects.all() #get data from all objects on Quiz model
return render(request, self.template,{'quiz':quiz, 'form':form})
def post(self,request):
if request.method == 'POST':
form = StudentAnswerForm(request.POST)
if form.is_valid():
form.instance.user = request.user
form.save()
return render(request, self.template, {'form':form})
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)
This is my models.py file
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Book(models.Model):
category_choices =(
#("Undefined","Undefined"),
("Action", "Action"),
("Romance", "Romance"),
("Horror", "Horror"),
("Comedy", "Comedy"),
("Adventure", "Adventure"),
("Dramatic", "Dramatic"),
("Crime","Crime"),
("Fantasy","Fantasy"),
)
name = models.CharField(max_length=100)
author = models.CharField(max_length=100, null=True)
content = models.TextField()
price = models.DecimalField(max_digits=5, decimal_places=2)
image = models.ImageField(upload_to= 'photos/%y/%m/%d', blank = True)
category = models.CharField(
max_length = 20,
choices = category_choices,
#default = 'Undefined'
)
publication_year = models.CharField(max_length=4, null=True)
ISBN = models.CharField(max_length=13, null=True, unique=True)
active = models.BooleanField(default= True)
def __str__(self):
return self.name
class Borrow(models.Model):
name = models.ForeignKey(User, null=True, on_delete=models.SET_NULL)
book = models.OneToOneField(Book, null=True, on_delete= models.SET_NULL)
period = models.PositiveIntegerField(default=0)
id = models.IntegerField(primary_key=True)
def __str__(self):
return str(self.book)
and this is my forms.py file
from django import forms
from .models import Borrow
class BorrowForm(forms.ModelForm):
class Meta:
model = Borrow
fields = ('name', 'book', 'period')
and this is the function in my views.py file that renders the form
#login_required
def borrowing(request):
momo = BorrowForm()
if request.method == 'POST':
momo = BorrowForm(request.POST)
if momo.is_valid():
instacne = momo.save(commit=False)
instacne.user = request.user.username
instacne.save()
return redirect('profile')
return render(request, 'books/book.html', {'momo': momo})
The role of this function is to render that form and to save the data that user will enter and automatically assign the username of the current user to the field 'name' in form.
I tried alot of things to get the username of the current user and assign it to the field 'name' but nothing works and that field stays blank.
You're using a models.ForeignKey(User) so that table will store a user id, not a username. I'd call this field user and not name, personally.
Therefore you need to provide a user instance to it like this;
#login_required
def borrowing(request):
initial = {}
if request.user.is_authenticated:
initial.update({'name': request.user})
momo = BorrowForm(initial=initial)
if request.method == 'POST':
momo = BorrowForm(request.POST)
if momo.is_valid():
instance = momo.save(commit=False)
instance.user = request.user
instance.save()
If you wanted to easily get the username for a Borrow instance you could do this;
class Borrow(models.Model):
name = models.ForeignKey(User, null=True, on_delete=models.SET_NULL)
book = models.OneToOneField(Book, null=True, on_delete= models.SET_NULL)
period = models.PositiveIntegerField(default=0)
id = models.IntegerField(primary_key=True)
def __str__(self):
return str(self.book)
#property
def username(self):
return self.name.username
If you want the form to offer users by username, you can either have the str method of your user model return username, or create custom choices as a tuple of user ID & username in the form __init__
Python, Django.
I'm trying to create a form for inserting data into database. Getting error while trying to add a new customers site via form:
ValueError at /new_site/ Cannot assign "[]":
"Sites.customers_id" must be a "Customers" instance.
Model:
class Customers(models.Model):
id = models.AutoField(primary_key=True)
author = models.ForeignKey('auth.User', null=True)
name = models.CharField(max_length=100)
description = models.TextField()
def __str__(self):
return self.name
class Meta:
verbose_name_plural = "Customers"
class Sites(models.Model):
id = models.AutoField(primary_key=True)
customers_id = models.ForeignKey(Customers,null=True)
author = models.ForeignKey('auth.User',blank=True, null=True)
adress = models.CharField(max_length=100, help_text="Example: http://stackoverflow.com/")
s_login = models.CharField(max_length=100, blank=True, default='', help_text="Login and password if required." )
s_password = models.CharField(max_length=100, blank=True, default='')
certificate = models.CharField(max_length=100,blank=True, default='',help_text="File's name")
def __str__(self):
return self.adress
class Meta:
verbose_name_plural = "Sites"
Forms:
class SitesForm(forms.ModelForm):
customers_id = forms.ModelMultipleChoiceField(queryset=Customers.objects.filter(author_id=1))
adress = forms.CharField(max_length=100, help_text="Example: http://www.stackoverflow.com/")
s_login = forms.CharField(max_length=100, required=False, help_text="Login and password if required.")
s_password = forms.CharField(max_length=100, required=False)
certificate = forms.CharField(max_length=100, required=False, help_text="File's name if required")
class Meta:
model = Sites
fields = ( 'customers_id','adress','s_login', 's_password', 'certificate')
def __init__(self, user, *args, **kwargs):
self.user = user
super(SitesForm,self).__init__(*args, **kwargs)
cust = Customers.objects.filter(author_id=user.id)
self.fields['customers_id'].queryset = cust
View:
def new_site(request):
if request.method == 'POST':
form = SitesForm( request.user, request.POST)
if form.is_valid():
site = form.save(commit=False)
site.author = request.user
cusomer.customers_id = request.customers_id
site.save()
return redirect('/customers/')
else:
form = SitesForm( request.user)
return render(request, 'checker/new_site.html', {'form': form, 'username': auth.get_user(request).username })
In views.py
replace
cusomer.customers_id = request.customers_id
with
cusomer.customers_id = Customers.objects.filter(id=request.customers_id)[0]
it will save object of Customer instead of id.
Edit your view like this,
def new_site(request):
if request.method == 'POST':
form = SitesForm( request.user, request.POST)
if form.is_valid():
site = form.save(commit=False)
site.author = request.user
site.customers_id = Customers.objects.get(author=request.user)
site.save()
return redirect('/customers/')
else:
form = SitesForm( request.user)
return render(request, 'checker/new_site.html', {'form': form, 'username': auth.get_user(request).username })
Problem solved.
In views,problem was in this line:
cusomer.customers_id = request.customers_id
Changed to:
site.customers_id = Customers.objects.filter(id=request.POST.get('customers_id'))[0]
And changes in form:
class Meta:
model = Sites
fields = ( 'customers_id','adress','s_login', 's_password', 'certificate')
So you need to remove 'customers_id'. And it looks like:
class Meta:
model = Sites
fields = ('adress','s_login', 's_password', 'certificate')
Thanks everyone!
I have a form that takes information about an item and saves it into the database. Im trying to allow users to edit that form with new/different information and save it again. Im having some difficulty trying to get this to work. I think the problem is when Django validates the data it sees that the slug and unique id of the item already exist and doesnt allow it to validate the data but im not completely sure about this as well. Would really appreciate the help. Thanks.
#view
def edit_item(request, item_id):
if request.method == 'POST':
item = Item.objects.get(id=item_id)
form = AddItem(request.POST,instance=item)
if form.is_valid():
item = form.save(commit=False)
item.user = request.user
item.is_active = True
item.slug = slugify(item.name)
item.save()
return HttpResponseRedirect('thanks.html')
else:
form = AddItem(instance=item )
return render_to_response('forsale.html', locals(), context_instance=RequestContext(request))
#form
class AddItem(forms.ModelForm):
name = forms.CharField(label="Title")
class Meta:
model = Item
exclude = ('user','slug','is_active',)
#model
class Item(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length=30)
slug = models.SlugField(max_length=50, unique=True)
is_active = models.BooleanField(default=True, blank=True)
image1 = models.ImageField(upload_to='img')
image2 = models.ImageField(upload_to='img', blank=True)
image3 = models.ImageField(upload_to='img', blank=True)
image_caption1 = models.CharField(max_length=200, blank=True)
image_caption2 = models.CharField(max_length=200, blank=True)
image_caption3 = models.CharField(max_length=200, blank=True)
price = models.DecimalField(max_digits=8, decimal_places=2)
quantity = models.IntegerField(default=1)
description = models.TextField()
created = models.DateTimeField(auto_now_add=True)
shipping_price = models.DecimalField(decimal_places=2, max_digits=6)
categories = models.ManyToManyField(Category)
def save(self, *args, **kwargs):
super(Item, self).save(*args, **kwargs)
if not self.slug:
self.slug = slugify(self.product.title) + "-" + str(self.id)
self.save()
Update your view function like this to return form for get request as well:
def edit_item(request, item_id):
if request.method == 'POST':
item = Item.objects.get(id=item_id)
....
#your existing code
else: #if its GET request
item = Item.objects.get(id=item_id)
form = AddItem(instance=item )
return render_to_response('forsale.html', locals(),
context_instance=RequestContext(request))
Note: you need to handle case when item with item_id does not exists in the DB. In that case do not use instance parameter to instantiate the form.