Issue regarding form on Django 1.5 - django

This is the scenario: I have a form with many field filled with some his own data and the user can change them.
In this form I collect 3 kind of data:
the first type of data are user data,
the second type of data are user personal data and
the third type of data are user work data.
Work data and personal data are binding to user data using a foreign key.
When the user clicks submit, my view collect this data from the request and send them to a view.
This is the problem:
this 3 type of data already have a model and a modelform (I used it in another part of this website),
class User(models.Model):
username = models.CharField(max_length=30, unique=True)
password = models.CharField(max_length=30)
email = models.EmailField(unique=True)
confirmed = models.BooleanField(default=False)
class PersonalData(models.Model):
user = models.OneToOneField(AtgUser, primary_key=True)
name = models.CharField(max_length=100)
surname = models.CharField(max_length=100)
address = models.CharField(max_length=200, blank=True)
class WorkData(models.Model):
user = models.OneToOneField(AtgUser, primary_key=True)
companyname = models.CharField(max_length=100)
And their related modelforms:
class Form1(ModelForm):
class Meta:
model = user.User
class Form2(ModelForm):
class Meta:
model = user.PersonalData
exclude = 'user'
class Form3(ModelForm):
class Meta:
model = user.WorkData
exclude = 'user'
But now I must use a new form that includes all the data like this:
class Bigform(Forms.form):
username = models.CharField(max_length=30, unique=True)
password = models.CharField(max_length=30)
email = models.EmailField(unique=True)
name = models.CharField(max_length=100)
surname = models.CharField(max_length=100)
address = models.CharField(max_length=200, blank=True)
companyname = models.CharField(max_length=100)
so:
When I get my request in the view, How can I extract part of the collected data in Bigform and put this data in their own modelform or model in order to update this data in my Database?
I thought of extract some field from Bigform in order to fill an already exist model or model form.
Is this the correct way?
Suggestions?
Thanks in advance

Related

how to give custom validation in django and djangorestframework on creating an API?

Here is my question I am creating address model, in that city, district I am accepting null values, Because for some API View I will accept Null values, but another API I will call this same models that time I want to validate that field is required, How Its is possible Here is my below code example.
models.py
class Address(models.Model):
address_line1 = models.CharField(max_length=250)
address_line2 = models.CharField(max_length=250, blank=True, null=True)
city = models.ForeignKey('Cities', on_delete=models.DO_NOTHING, blank=True, null=True)
district = models.ForeignKey('Districts', on_delete=models.DO_NOTHING, blank=True, null=True)
class Assignaddress(models.Model):
address = models.ForeignKey(Address, on_delete=models.CASCADE)
owner_name = models.CharField(max_length=255)
class dont`Assignaddress(models.Model):
address = models.ForeignKey(Address, on_delete=models.CASCADE)
owner_name = models.CharField(max_length=255)
Now in serializer.py
class AddressSerializer(serializers.ModelSerializer):
class Meta:
model = Address
fields = ('address_line1','address_line2','city','district')
class AssignaddressSerializer(serializers.ModelSerializer):
class Meta:
model = Assignaddress
fields = ('address ','owner_name ')
class dont`AssignaddressSerializer(serializers.ModelSerializer):
class Meta:
model = dont`Assignaddress
fields = ('address ','owner_name ')
now How can I validate Assignaddress you have to pass city and district is required and don`tAssignaddress its not neccessary
Sorry for not writting views.py
So in one of your serializers you want to accept null values? You can do this with allow_null and / or required (for fields that should not be supplied during deserialization). Be sure to check out the corresponding Django Rest Framework documentation.
Example (out of my memory - check Django Rest Framework documentation for specific use case):
class AssignaddressSerializer(serializers.ModelSerializer):
address = serializers.PrimaryKeyRelatedField(many=False, allow_null=True)
class Meta:
model = Assignaddress
fields = ('address ','owner_name ')

Filtering Django query filtering

I'm doing some querying currently and I was wondering if I would be able to query something from these 3 models where the return would give me all the projects the users are working on. I know about the basic filtering however thats not really enough in this case, how would one go about querying through 2 foreign keys.
class User(models.Model):
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
email = models.EmailField()
class ProjectUser(models.Model):
project = models.ForeignKey("Project", on_delete=models.CASCADE)
user = models.ForeignKey("User", on_delete=models.CASCADE)
is_lead = models.BooleanField(default=False)
class Meta:
unique_together = (("project", "user"),)
class Project(models.Model):
name = models.CharField(max_length=255)
client = models.CharField(max_length=255)
complete = models.BooleanField(default=False)
You can obtain the Projects a user is working on with:
Project.objects.filter(
projectuser__user=user
)
The double underscores are used to look "through" relations. Furthermore the default related_query_name=… parameter [Django-doc] is, if not specified, the name of the model in lowercase.

Django ModelForm: Huge ForeignKey queryset leads to crash when loading form

Basically, I have two models: User and Event. An event is always associated with one user.
class User(models.Model):
user_id = models.AutoField(primary_key=True)
username = models.CharField(max_length=255, unique=True)
hashed_password = models.CharField(max_length=255)
class Event(models.Model):
event_id = models.AutoField(primary_key=True)
title = models.CharField(max_length=255)
description = models.TextField(max_length=255, blank=True, default='')
user = models.ForeignKey(User)
And then I have the following form for Event.
class EventForm(forms.ModelForm):
class Meta:
model = Event
fields = ['title', 'description', 'user']
I can succesfully show this form in my template to create an event. I can also associate a user to a form successfully with Select field when the users number are still few.
Now the problem is, when I have 1M users in database, my browser crashes when loading the template. Any idea how to solve this one? I was thinking about using AJAX and then search user that matches the username, but I'd like to hear other better approaches. Thanks!

How do I filter Choice FK in Forms?

I want filter a choice in a form according user_logged. Here is my models.
#models.py
class Store(models.Model):
name = models.CharField(max_length=64, unique=True)
description = models.TextField(null=True, blank=True)
class StoreManager(models.Model):
store = models.ForeignKey(Store, related_name='store', on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
class StoreLogo(models.Model):
store = models.ForeignKey(Store, related_name='store', on_delete=models.CASCADE, verbose_name='Store')
image = photo = models.FileField()
First I created a Store, after that I Associate a StoreManager to a Store, and then I want in a forms add a ImageLogo, so in that forms, in field Store, I want list only a Store what user has associated.
Store = (SuperMarket Store), (ClothesStore)
StoreManager = John(SuperMarket Store), Julian(ClothesStore)
StoreLogo = John (can only view SuperMarket Sotre)
StoreLogo = Julian(can only view ClothesStore)
I'm using CBV(generic.CreateView).
There is my views.
#views.py
class AddPhotoOnEstablishment(LoginRequiredMixin, generic.CreateView):
model = StoreLogo
fields = ['store', 'image']
success_url = reverse_lazy('register:establishment_list')
context_object_name = 'object_name'
I want, if John has associated to Store and logged in the system, when he add a Image logo, the field Store only appear the Store he has associated.
maybe this link will help. it explained methods and attributes of CreateView class. in the render_to_response method you can get the current user using this code:
self.request.user
and check if it's associated with the store logo you're sending as response.

Delete all data from model if user do not have data in another model

If user has data in the Data model and Bank model everything is ok but if user do not have data in Bank model and only in Data model - all data from Data model must be removed.
How to do?
class Data(models.Model):
user = models.ForeignKey(User, unique=True)
something = models.CharField(max_length=255)
class Bank(models.Model):
user = models.ForeignKey(User, unique=True)
number = models.IntegerField()
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
name = models.CharField(max_length=255)
in one of your views function (or in a cron job... your question is vague actually):
bank = Bank.objects.get(user=user)
if not bank:
data = Data.objects.filter(user=user).delete()
warnings:
user must have a valid value (ie: must be defined)
this code doesn't check for anything, it just performs what you asked
adding a foreign_key from Bank to Data (or viceversa, it depends on the strength of the relation) could be a valid change to your classes. Like this we don't know how Data and Bank are related to each other