I have a problem, I am doing project in Django for my University, and I don't know how can I change value of cell in Database using views.py. My application is an application to do exams online and problem is that many users need to use it at the same time, so I need to do relations in database, like every question has an answer and that answer is provided by one user. And there is problem, I don't know how can I change this dynamically in Views.py.
This is my code from Views.py:
if form.is_valid():
if username == Users.objects.latest('name'):
Choice.objects.username = Users.objects.get('name')
And my models.py:
class Answers(models.Model):
question = models.ForeignKey(Questions, on_delete=models.CASCADE)
text = models.TextField()
def __str__(self):
return self.text
class Users(models.Model):
name = models.CharField(max_length=30)
pass = models.CharField(max_length=30)
def __str__(self):
return self.name
class Choice(models.Model):
username = models.ForeignKey(Users, null=True, on_delete=models.CASCADE)
question = models.ForeignKey(Questions, null=True, on_delete=models.CASCADE)
answer = models.CharField(null=True,max_length=50)
class Questions(models.Model):
text = models.CharField(max_length=150)
madeBy = models.ForeignKey(User, null=True, blank=False, default='kacper', on_delete=models.CASCADE)
def __str__(self):
return self.text
Also if you have any other idea how could I improve this would be great, it's first time that I'm doing something in DJango.
If I understand your question correctly you want to update("how can I change value of cell ...") an specific object. To do this you can use following command :
YourModel.objects.filter(pk=yourobject_pk).update(username=Users.objects.get('name'))
Have this in mind, first you have to filter the object you want to update(I suggest doing this by id) and then update the field(cell) you want.
Related
Say there is a poll app and I want a user to vote only once for a poll question.
Assume models.py to be as follows,
class PollUser(models.Model):
username = models.CharField(max_length=120, unique=True)
class PollQuestion(models.Model):
question = models.CharField(max_length=250)
issuing_user = models.ForeignKey(PollUser, on_delete=models.CASCADE)
class PollChoice(models.Model):
text = models.CharField(max_length=250)
votes = models.PositiveIntegerField(default=0)
Is there a way to implement this functionality, without making this check in the views?
I'm trying to easily present data from two different tables (classes). I have an Environment class with all the environments details and a Changes class which contain history changes on all my environments.
My view is currently showing all my Environment details. I want to add to this view the last change been made on each environment (e.g last modified by: User).
My models.py look like this:
class System(models.Model):
system_name = models.CharField(max_length=40, blank=True)
system_id = models.CharField(max_length=100, blank=True)
system_clusters = models.ManyToManyField(Cluster, blank=True)
system_owner = models.CharField(max_length=20, blank=True)
def __str__(self):
return self.system_name
class Changes(models.Model):
date = models.DateTimeField(auto_now_add=True)
cluster = models.ForeignKey(System, on_delete=models.CASCADE)
user = models.CharField(max_length=20, blank=True)
change_reason = models.CharField(max_length=50, blank=True)
def __str__(self):
return self.date
At first, i though to pass a dictionary to my template with the system as a key and a change as a value:
last_changes = {}
change = Changes.objects.filter(cluster__in=s.system_clusters.all()).order_by('-id')[0]
last_changes[s.system_id] = change.change_reason
Even though it partially works (I still trying to parse the dict in my template), I feel like this is not the right approach for the task.
I'm hoping to reach a result where I can just call system.last_change in my template. Can I add another field for System class that will point to his last_change in the Changes table?
You can write a method on System to return the last change for an item:
def last_change(self):
return self.changes_set.order_by('-date').first()
Now you can indeed call system.last_change in the template.
I have this model in Django, where a person has the same information from the user provided by Django plus a little bit more information. When I create a new person it requires to create a new user also, that's fine. But when I delete a person the user still remains on my database. What am I missing here ? I would like to delete the user too.
class Person(models.Model):
user = OneToOneField(User)
gender = CharField(max_length=1, choices=GenderChoices, blank=True, null=True)
birth_date = DateField(blank=True, null=True)
def __unicode__(self):
return self.user.username
Try to override the delete method on the model (code not tested):
class Person(models.Model):
user = OneToOneField(User)
gender = CharField(max_length=1, choices=GenderChoices, blank=True, null=True)
birth_date = DateField(blank=True, null=True)
def __unicode__(self):
return self.user.username
def delete():
theuser = User.objects.get(id=user)
theuser.delete()
I have found some relevant documentation about CASCADE usage in Django here.
i read a lot of forms.
i want to edit userinformation, but the userinformation is existed of two models.
One model this:
class Tc(LoginUser):
link = models.CharField(max_length=100)
name = models.CharField(max_length=50, unique=True)
contact = models.OneToOneField(Contact, blank=True, null=True)
def __str__(self):
return self.name
And the second one:
class Contact(models.Model):
contact_id = models.AutoField(primary_key=True)
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
def __str__(self):
return self.email
Now i want to edit "contact" field.
It should be controled, if a contact is existing, if not, so create a new. If there is an existing one, then update this.
My problem is that, that i must use two forms and i dont know how exactly.
You need to make queries : for handle contact and know about a contact existing you need Making queries
. as a hint for check about existing if you have one unique object of contact like check_name you can do it with following :
from models import Contact
contats=contact.objects.all()
for n in contacts:
if n.first_name == check_name()
#do something
else:
#do something
In Django I'm trying to write a ModelForm for a ContactForm and when I try to load the page containing the form it says that it doesn't exist. Then when I try to render the other form I had previously written it says that
Caught AttributeError while rendering: 'CashtextsForm' object has no attribute 'subject'
'Subject' is a field in the form that I was trying to render in ContactForm. So is there some certain order I have to list them in models.py? Here's that code:
# Create your models here.
from django.db import models
from django.forms import ModelForm
class Cashtexts(models.Model):
cashTexts = models.CharField(max_length=100, blank=True) #change me to a website filter
superPoints = models.CharField(max_length=100, blank=True)#chance to "superPoints _Username"
varolo = models.CharField(max_length=100, blank=True)
swagbucks = models.CharField(max_length=100, blank=True)
neobux = models.CharField(max_length=100, blank=True)
topline = models.CharField(max_length=100, blank=True)
Paidviewpoint = models.CharField(max_length=100, blank=True)
cashcrate = models.CharField(max_length=100, blank=True)
def __unicode__(self):
return self.cashcode
class Contact(models.Model):
sender = models.EmailField()
subject = models.CharField(max_length=25)
message = models.TextField()
class CashtextsForm(ModelForm):
class Meta:
model = Cashtexts
def __unicode__(self):
return self.subject
class ContactForm(ModelForm):
class Meta:
model = Contact
I previously had them arranged as Model-Modelform, Model-Modelform but hereit shows them as the way I now currently have them.
Also Is there any advantages to write just forms? Right now I'm more comfortable writing model forms over forms(I dont imagine they are much differnt) but if I only wrote model forms would I be missing out on features? So is there anything I missed on how t write multiple forms in models.py or did I have them written worng? or can i not create them via the command syncdb?
The __unicode__(self) method should be part of your Contact class
class Contact(models.Model):
sender = models.EmailField()
subject = models.CharField(max_length=25)
message = models.TextField()
def __unicode__(self):
return self.subject
It doens't make sense inside CashtextsForm as that does not "know" a subject attribute.
Yes, your form really does not have subject, just remove __unicode__ definition and everything will be ok.
This is because of declarative style of django code. If you want to inspect your objects use pdb module and dir builtin.
You will use ModelForm subclasses almost every time, but sometimes you will need a form which can not be built from model. In this case django will help you to describe such form and to use form clean and field validation.
the subject field is defined in the model and not in the modelform, since a modelform can be initialized without a model instance it is not safe to do something like this:
def __unicode__(self):
return self.instance.subject
What you can do (but I do not really see the point of doing this):
def __unicode__(self):
if getattr(self, 'instance') is not None:
return self.instance.subject
return super(CashtextsForm, self).__unicode__()