Django CharField add to choices from front-end - python

Problem Description
Suppose I have a model with a CharField that has choices as follows:
class MyModelWithChoice(models.Model):
FIELD1_CHOICES = (('1', 'One'),)
field1 = models.CharField(max_lenth=32, choices=FIELD1_CHOICES)
Is there a way to add to these choices from the front end?
Preventing the problem
I know that the problem can be prevented by creating another model and using a ForeignKey for field1, which works just fine.
Reason I'm trying to find another way
The reason I'm trying to avoid creating a new model is because it doesn't really carry any more information. If it contained further information about the choice, I wouldn't have a problem, but it seems like too much overhead to create a table in the db just for the choices

I think you must use django forms then you can use django forms in your fron-end
See this documentation from django offical website

Related

Is it possible to use a table in the database when it is NOT a Django model?

Is it possible get a queryset from a table in the app database that is NOT a model in the app?
If I have a table that is not a model named "cartable", conceptually, I want to do this:
myqueryset = cartable.objects.all()
Is there a relatively easy way to do this? Thanks!
If you want to access an existing table in your database that is not managed by your application, you can still create a class for it, and tell django to ignore it for migrations.
Just create a model and add the fields you need to access and then add a meta class to tell django to leave it alone.
class MyModel(model.Model):
class Meta:
managed = False
you can read about that at https://docs.djangoproject.com/en/1.9/ref/models/options/#managed
To do so you would need to create a class (not a model), with methods that use raw SQL. You should see more details here on how to do so: https://docs.djangoproject.com/en/1.9/topics/db/sql/#executing-custom-sql-directly
Please note that you will have to manually create the object with the right properties afterwards.
If you wanted to use Django ORM without the models, I don't think it is possible. You could however create a model that matches your db in a separate app and never create migrations for it to ensure you don't accidentally modify the DB.
Short answer is, "not really". Django QuerySet deals with model instances, so everything in QuerySet API is tied into models. Everything expects to return model instances, uses model fields etc.
That said, you should be able to create a model for an existing table. You will need to add db_table to the Meta, so Django knows where the table lives. If you have some indexing, you will need to make sure Django's idea of indexes is the same as the one in the database. indexed=True on fields and unique_together in Meta should help a lot with that.

how to add dynamic fields at run time in django

I have to add dynamic fields at run time in my django application,but I don't know the proper way how to add new fields at run time.
I want to add the code which will generate the dynamic field and will update database too. I am using postgresql database. please help if anyone can.
My "model.py" is simply like this:
class Student(models.Model):
name=models.CharField(max_length=100)
school=models.CharField(max_length=100)
created_at=models.DateField(auto_now_add=True)
is_active=models.BooleanField(default=False)
def __str__(self):
return self.name
Django is not made for dynamic models, as relational databases are not. A model change at runtime will create a ton of problems.
You have to simulate it, by...
clever use of related models
storing values in a large field, e.g. JSON as text
having a generic model that stores the data as key, value; e.g. a table with PK, a FK, key, value as columns.
You should try the first option and only if that does not work out try the other two.

Django searchable drop down for ForeignKey widget

in my Django model I have a m2m relation with an intermediate model that contain the two foreign keys of the respective two models.
My problems is that, the first model may have many entries and when I associate it with other model I have a too large drop down widget in the admin.
The default ManyToManyField widget (with filter_horizontal set) may be ok, but it is compatible only with m2m relations....
Is there a solution (even 3rd parts) for the ForeignKeyFields?
Any suggestions?
Edit:
For the other users, I've solved my problem using django-selectable
http://django-selectable.readthedocs.org/en/v0.8.X/index.html
The 3rd party component Django Ajax Selects does exactly what you are looking for.
I played around with django-selectable as well, but found django-autocomplete-light (https://github.com/yourlabs/django-autocomplete-light‎) easier to use and more flexible for what I wanted to achieve.
Perhaps it can be useful to you as well.

Django 1.5 + User model relationship

Django 1.5+ allows us to add custom fields to a User. I want to use this fact, but I don't necessarily know what is good practice. Here is a situation I am confused on how to handle the models.
Given the option to add fields to User, if a project only has one type of User, lets say a Student model, can I simply add student-specific fields to User? I am new to Django, but I believe the alternative would be to set up general User settings, and create a Student model, and a one-to-one unique field in it call user.
Should you ever expand a Django User's fields to mimic that of a model, even if the project is guaranteed only to have one type of user?
If you only have one type of user and are using Django 1.5+, I would recommend taking advantage of the new AbstractUser. Extending Django's default user
As an example where you want to add date of birth and favorite color:
#myusers/models.py
from django.contrib.auth.models import AbstractUser
from django.db import models
class MyUser(AbstractUser):
dob = models.DateField()
favorite_color = models.CharField(max_length=32, default='Blue')
If you need more flexibility you can extend the AbstractBaseUser instead of AbstractUser, but for most basic cases you should only need AbstractUser.
Also note that in either case, you'll need to reference your user model by using settings.AUTH_USER_MODEL.
Using out example above and assuming the app it was defined in is called myusers:
#settings.py
AUTH_USER_MODEL = 'myusers.MyUser'
The method you mention of creating a Student model with a one-to-one field to the User model still works, but is not as clean (there are still cases where it makes sense if you have multiple kinds of users).
I don't normally like to reference books in answers, but I found that Two Scoops of Django's, Chapter 16 on the User model gave a much clearer explanation of where the different options are appropriate than the current version of the online Django docs. The book is overall a very useful intro to Django and was written based on 1.5. You'd have to buy the book or find someone who has it, though... (FYI: I don't get any money recommending this).
You could also take a look at this SO question/answer: https://stackoverflow.com/a/14104748/307293
You shouldn't touch the django contributed User model (from the authentication framework). This will break upgrades and you do not know what other consequences it might have.
There are two basic ways to do this:
If you just need to store additional information about a user, but don't need to change how the authentication/authorization mechanism works, create a model and add a OneToOneField to the User model. In this model, store any other miscellaneous information.
If you want to change how authentication works you can create your own User model and have django use that (1.5+ only).

Improving Performance of Django ForeignKey Fields in Admin

By default, Django's admin renders ForeignKey fields in admin as a select field, listing every record in the foreign table as an option. In one admin-accessible model, I'm referencing the User model as a ForeignKey, and since I have thousands of users Django is populating the select with thousands of options. This is causing the admin page to load incredibly slowly, and the select is not very useful since it can take a while to scroll through thousands of options to find the one you want.
What's the best way to change the rendering of this field in order to improve page load and usability? I'd like the select field to be replaced with some sort of button to launch a search form popup, or a text field that searches keywords via Ajax to find the Id for the specific User they want to associate. Does admin have anything like this builtin, or would I have to write this from scratch?
Add raw_id_fields to your model to only show the ID instead of a dropdown.
You're right, Cerin, the cause of the slowdown is because Django is populating the <select> element with too many options. You might want to use an autocomplete element instead.
Interestingly, Django 2.0 has introduced a new feature on the admin site, called autocomplete_fields, which I think you will find useful in this case. It uses AJAX.
class ExampleAdmin(models.ModelAdmin):
autocomplete_fields = ['example_field_user']
You can use one of the few autocomplete apps for Django. Check them at Django Packages.
There's also django-extensions that have ForeignKeyAutocompleteAdmin that fit your needs pretty well.
Another option is to add readonly_fields instead of raw_id_fields

Categories

Resources