This is my first Question ever on StackOverflow, so bear with me for my mistakes.
Now, to the question!
I am currently making website in django and It has multiple models which are linked to one parent model. Now I want to create a multiple page form to include all this models. How to do that???
here's problem in detail:
models.py
class Profile(models.Model):
user = models.OneToOneField(User)
first_name = odels.CharField(
max_length=255, validators=ONLY_LETTERS_VALIDATOR)
last_name = odels.CharField(
max_length=255, validators=ONLY_LETTERS_VALIDATOR)
# And some other fields
class YMHTMobile(models.Model):
profile = models.ForeignKey(Profile)
mobile = models.CharField(max_length=10, validators=ONLY_DIGITS_VALIDATOR)
is_active = models.BooleanField(default=True)
def __unicode__(self):
return '%s' % self.mobile
class Meta:
verbose_name_plural = 'Mobile Details'
# some more models with foreign key as profile
Now I want to create a Multiple page form with all these models(like one model form in one page and click next for another form)
How do I do that??
Use the Form Wizard contrib app.
UPDATE: Form Wizard was moved from django 1.8 to separate project - Django Form Tools.
Related
I have two models one is user model and another one is cars model.
class User(models.Model):
id = models.BigAutoField(primary_key=True)
username = models.CharField(max_length=50, verbose_name="User Name")
class Cars(models.Model):
id = models.BigAutoField(primary_key=True)
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='cars')
Now on /admin/app/cars/1/change/ page i want to see the username as a normal text in that form below the dropdown of users.
I tried with inline stack but that didn't worked, and throwing error, User has to foreign key to Cars.
The text shown in the admin panel is determined by the __str__ function, so adding something like
def __str__(self):
return self.username
to your user model should be enough
I am building a website where users can upload files and can attach uploads to projects that they created beforehand. The upload is done with a django form where the user can specify the title, comments, etc... There is also a dropdown list where the user can choose from the existing projects that he created (list of projects is dependent on user)
As of now the dropdown only shows the (autogenerated) project id which is the pk of the model Project.
I want the dropdown to show the names of the projects and not the project ID which is not very meaningful for the user.
I have already tried
to_field_name='name'
but that didn't work
I have also tried
Project.objects.filter(user=user).values_list('name')
or
Project.objects.filter(user=user).values('name')
the last two options show the project name in {'projectname} but when I select them and submit the form the error "Select a valid choice. That choice is not one of the available choices."
This is my code:
models.py
class Upload(models.Model):
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
upload_date = models.DateTimeField(default=timezone.now)
comments = models.CharField(max_length=10000, null=True)
title = models.CharField(max_length=10000, null=True)
project = models.CharField(max_length=99, default='--None--')
forms.py
class UploadForm(ModelForm):
project = ModelChoiceField(label='Select Project', queryset=Project.objects.all(), to_field_name='name',
empty_label='--Select Project--')
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
super(UploadForm, self).__init__(*args, **kwargs)
if user is not None:
self.fields['project'].queryset = Project.objects.filter(user=user)
class Meta:
model = Upload
fields = ['title', 'project', 'upload_date', 'comments']
According to docs
The str() method of the model will be called to generate string representations of the objects for use in the field’s choices. To provide customized representations, subclass ModelChoiceField and override label_from_instance. This method will receive a model object and should return a string suitable for representing it.
https://docs.djangoproject.com/en/2.2/ref/forms/fields/#modelchoicefield
so you should define __str__() method for Project model e.g.
def __str__(self):
return self.name
Here's my models.py
from multiselectfield import MultiSelectField
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
users = User.objects.values_list('id','username')
authorized = MultiSelectField(choices=users, null=True)
def __str__(self):
return self.question_text
My problem is that while server is running after user register my choices field are not updating till rerun my server.
I did some research and i found solution for that:
https://mschmitt.org/blog/dynamic-django-form-choice-labels/
http://www.ilian.io/django-forms-choicefield-with-dynamic-values/
I have no idea how to override model in forms + i need to override model in django admin forms. any pointers would be great!
thanks in advance
You should not do this at all. If you want to store related objects, you should use a proper database relationship.
In this case, a ManyToManyField to User would be appropriate, since a question can have multiple authorized users and presumably a user can be authorized for multiple questions.
I am new to Django and trying to create an App with two User Types (Freelancers and Customers). I understand how to create a User profile Class and it works well for me:
class UserProfile(models.Model):
user = models.OneToOneField(User)
description = models.CharField(max_length=100, default='')
country = models.CharField(max_length=100, default='')
website = models.URLField(default='')
phone = models.IntegerField(default=0)
def create_profile(sender, **kwargs):
if kwargs['created']:
user_profile = UserProfile.objects.create(user=kwargs['instance'])
post_save.connect(create_profile, sender=User)
This works well for me on a one user type user. But now I am building an app with 2 types of users (freelancers and customers), what is the best approach to get this done. Both users will have different view and info. Should I:
Create 2 different apps, and repeat the normal registeration and login for each.
If I do the above, hope the freelancers when logged in won't access customers view.
How do I add user type to the user profile if I decide to use one app and model for it.
Please I need a step by step beginner approach, or a link to relevant source.
Thanks.
You could try this:
class UserProfile(models.Model):
user = models.ForeignKey(User)
#define general fields
class Freelancer(models.Model):
profile = models.ForeignKey(UserProfile)
#freelancer specific fields
class Meta:
db_table = 'freelancer'
class Customers(models.Model):
profile = models.ForeignKey(UserProfile)
#customer specific fields
class Meta:
db_table = 'customer'
You can then have as many Users as you want from the UserProfile.
You should need just use Groups Django mechanism - you need to create two groups freelancer and let say common and check whether user is in first or second group - then show him appropriate view
To check whether user is in group you can use
User.objects.filter(pk=userId, groups__name='freelancer').exists()
You Could Try extending the Default Django Auth User like this
Create an App with Account or Whatever name you like , then in models.py write like below
class User(AbstractUser):
is_head = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
is_public = models.BooleanField(default=False)
Add Auth Extended Model in Settings.py
AUTH_USER_MODEL = 'accounts.User'
Migrate your Account app and you are all set with Your User Extended Model.
I have scenario in which a user can have multiple books. I can create two different models for user and books and relate them using foreign keys (or one-to-many will be right way ?).
I have created a django forms for User model but when i do like this {{form.as_p}} in templates only user model fields is shown not books field.
I want that with user fields my books model filed also displayed (like book names field more then once because he can have multiple books) , Please let me know if it is possible using django forms/models or I have to user simple html forms with jquery and then save data in models.
Thanks
EDIT:
my models :
class Product(models.Model):
categories = models.CharField(max_length=5, choices = settings.CATEGORIES)
name = models.CharField(max_length=100)
description = models.TextField()
currency = models.CharField(max_length=5, choices = settings.CURRENCY)
status = models.BooleanField(default=True)
def __unicode__(self):
return self.name
class Prices(models.Model):
products = models.ForeignKey(Product)
prices = models.IntegerField()
def __unicode__(self):
return self.id
if you are creating a form for Prices, try putting this in your model form:
products = forms.ModelMultipleChoiceField(queryset=Product.objects.all())
I think you should add required fields in meta class such as
class ThreadForm(ModelForm):
class Meta:
model = Thread
fields = ('Books', 'User')
Please understand the work flow to use foreign keys in model form here.