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
Related
Context: I'm forcing my self to learn django, I already wrote a small php based website, so I'm basically porting over the pages and functions to learn how django works.
I have 2 models
from django.db import models
class Site(models.Model):
name = models.CharField(max_length=50, unique=True)
def __str__(self):
return self.name
class Combo(models.Model):
username = models.CharField(max_length=50)
password = models.CharField(max_length=50)
dead = models.BooleanField(default=False)
timestamp = models.DateTimeField(auto_now_add=True)
siteID = models.ForeignKey(Site, on_delete=models.PROTECT)
class Meta:
unique_together = ('username','siteID')
def __str__(self):
return f"{self.username}:{self.password}#{self.siteID.name}"
When creating a view, I want to get the Combo objects, but I want to sort them first by site name, then username.
I tried to create the view, but get errors about what fields I can order by Cannot resolve keyword 'Site' into field. Choices are: dead, id, password, siteID, siteID_id, timestamp, username
def current(request):
current = Combo.objects.filter(dead=False).order_by('Site__name','username')
return render(request, 'passwords/current.html',{'current':current})
Since I'm not necissarily entering the sites into the database in alphabetical order, ordering by siteID wouldn't be useful. Looking for some help to figure out how to return back the list of Combo objects ordered by the Site name object then the username.
You can order this by siteID__name:
def current(request):
current = Combo.objects.filter(dead=False).order_by('siteID__name','username')
return render(request, 'passwords/current.html',{'current':current})
since that is the name of the ForeignKey. But that being said, normally ForeignKeys are not given names that end with an ID, since Django already adds an _id suffix at the end for the database field.
Normally one uses:
class Combo(models.Model):
# …
site = models.ForeignKey(Site, on_delete=models.PROTECT)
if you want to give the database column a different name, you can specify that with the db_column=… parameter [Django-doc]:
class Combo(models.Model):
# …
site = models.ForeignKey(
Site,
on_delete=models.PROTECT,
db_column='siteID'
)
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.
I want to add variable in Django model and I don't want to save it to database at the same time I want to return this variable to user when calling the endpoint.
this is what i found in the web, but the problem is the variable is not rerun to user
class User (models.Model):
f_name = models.CharField(max_length=255)
l_name = models.CharField(max_length=300)
full_name = ''
How to rerun the full_name to user when he call the api ?
If this is using Django Rest Framework, I don't know how your code is set up, but you'll need to extend your serializer:
add a new field to the serializer: full_name = serializers.SerializerMethodField()
add a method to the serializer:
def get_full_name(self, obj):
return "{} {}".format(obj.first_name, obj.last_name)
NOTE:
there are LOTS of different ways of joining those strings together, using #property in your model, fstrings, etc - up to you to choose the most appropriate for your needs (without seeing the rest of your code()
You can define model's property:
class User (models.Model):
f_name = models.CharField(max_length=255)
l_name = models.CharField(max_length=300)
#property
def full_name(self):
return self.f_name + self.l_name
now you use full_name same way as normal attribute user.full_name.
I'm trying to create a directory of sites, I'm new in Django. What I need is: one site can have many payment processors and one payment processors (Paypal, Payza, etc) can belong to many sites. I'm trying to create a table relationship to represents this. My models are like this:
# Models.py
class Sites(models.Model):
name = models.CharField(max_length=75)
link = models.CharField(max_length=150)
description = models.TextField(blank=True, null=True)
def __str__(self):
return self.name
class PaymentProcessors(models.Model):
name = models.CharField(max_length=75)
def __str__(self):
return self.name
class Sites_PaymentProcessors(models.Model):
site = models.ManyToMany(Sites)
payment_processor = models.ManyToMany(PaymentProcessors)
First, I'd like to know if my models are right. If not, how can I fix it?
Second, I'm using Django Admin site to create the sites and payment processors, how can I populate automatically my Sites_PaymentProcessors table with the relation between Sites and Payment_Processors when I add a new Site?
I would slightly change the models to accomodate ManyToManyFields like this:
class Sites(models.Model):
name = models.CharField(max_length=75)
link = models.CharField(max_length=150)
description = models.TextField(blank=True, null=True)
def __str__(self):
return self.name
class PaymentProcessors(models.Model):
name = models.CharField(max_length=75)
sites = models.ManyToManyField('Sites', related_name='payment_processors')
def __str__(self):
return self.name
Now, if you want custom fields or store more information along with the relationship, you can make use of the through table
For example, if you want to associate the amount limit or something more custom:
class Sites(models.Model):
name = models.CharField(max_length=75)
link = models.CharField(max_length=150)
description = models.TextField(blank=True, null=True)
def __str__(self):
return self.name
class PaymentProcessors(models.Model):
name = models.CharField(max_length=75)
sites = models.ManyToManyField('Sites', related_name='payment_processors', through='SitePaymentProcessor')
def __str__(self):
return self.name
from django.core.validators import MaxValueValidator
class SitePaymentProcessor(models.Model):
site = models.ForeignKey('Site')
payment_processors = models.ForeignKey('PaymentProcessors')
amount_limit = models.IntegerField(default=1000,
validators=[
MaxValueValidator(100)
])
Now, again this is just an example.
Now, registering the admin classes would enable you to populate data into the models via the admin interface.
To auto-populate a large dataset, I would consider using fixtures rather than populating elements individually.
I have the following code:
class Item(models.Model):
name = models.CharField(max_length=100)
keywords = models.CharField(max_length=255)
type = models.ForeignKey(Type)
class Meta:
abstract = True
class Variant(models.Model):
test_field = models.CharField(max_length=255)
class Product(Item):
price = models.DecimalField(decimal_places=2, max_digits=8,null=True, blank=True)
brand = models.ForeignKey(Brand)
variant = models.ForeignKey(Variant)
def get_fields(self):
return [(field.name, field.value_to_string(self)) for field in Product._meta.fields]
def __unicode__(self):
return self.name
Im using Grappelli.
I want my Product to have multiple Variations. Should I use a manytomanyfield?
I want to be able to add Variants to my Product directly in the Admin. Now I get an empty dropwdown with no variants(because they doesnt exists).
I thought Django did this automatically when u specified a Foreign Key?
How can I get the Variant fields to display directly on my Product page in edit?
I've read someting about inline fields in Admin?
Well, it's the other way around :)
1/ Place the foreign key field in your Variant, not in your Product (what you describe is actually a OneToMany relationship).
2/ Link the Variant to your Product in the relative ProductAdmin in admin.py as an inline (i.e VariantInline).
See the docs for further informations : https://docs.djangoproject.com/en/1.6/ref/contrib/admin/#inlinemodeladmin-objects
Hope this helps !
Regards,