Django form with one too many fields - python

I am trying to work out how to create a form for my Invoice model. It will include filling in the fields for my InvoiceLine model. This is possible via the admin interface, registering an inline object to the InvoiceAdmin model.
Any pointers on how to proceed for the same behavior on the front end?
The following are the models simplified only to include the model relationship and an arbitrary number
from django.db import models
class Invoice(models.Model):
number = models.IntegerField()
class InvoiceLine(models.Model):
invoice = models.ForeignKey(Invoice)

Do the lines and header of invoice via javascritp and send a json to server with the data, we work this way

You can use an inlineformset_factory. This wasn't my idea I found it on this blog post Django's Inlineformset_factory and You. Thanks Charles.

Related

Django Like mechanism. Database performance question

I have CustomUser model and Post model. I consider adding a lightweight like mechanism to the posts.
What comes to my mind is defining a Like model in such fashion to connect the models to each other:
class LikeFeedback(models.Model):
likingUser = models.ForeignKey(CustomUser)
post_liked = models.ManyToManyField(Post)
But this design produces a new row in the database with each like.
Another option is to define CustomUser and Post models in a way that:
class Post(models.Model):
...
users_liked = models.ManyToManyField(CustomUser)
class CustomUser(models.Model):
...
posts_liked = models.ManyToManyField(Post)
I am not sure if this approach creates a new row or uses a different indexing mechanism, but it looks tidier.
In terms of DB performance what approach is the fastest? Do I need to define the ManyToMany connection in both models to speed up DB processes? Because 15 posts are to be displayed on the webpage at once and and with every post it is necessary to check if the visitor already liked the note. Also, with each like and takeback a write operation is to be performed on the DB.
I am not sure if this approach creates a new row or uses a different indexing mechanism, but it looks tidier.
A ManyToManyField will create an extra table called a junction table [wiki] with ForeignKeys to the model where you define the ManyToManyField, and the model that you target with the ManyToManyField.
You furthermore only need one ManyToManyField, otherwise you make two relations that act indepdently. You thus model this as:
from django.conf import settings
class Post(models.Model):
# ...
likes = models.ManyToManyField(
settings.AUTH_USER_MODEL,
related_name='liked_posts'
)
class CustomUser(models.Model):
# ...
# no ManyToManyField to Post
Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

Stock code request application in Django & SQL

I have a material excelfile and it has different type of material.
Each category has start specific prefix like AB001 or BC001
I am planning to write a webservice for the request of this material stock codes.
But I need to import the my old database and i have stucked how can i implement this?
I have created a model in DJANGO like Materials, But i could not solve that if i import the my old excel file, the software how can understand the numbers will be correct.
It must be consecutively. Like ( AB001 , AB002, AC001,AC002,AZ001)
Thanks in advance!
Django ORM has an order_by() method. do you need something other than this?
The models meta class can allow for default order
models.py
class Material(models.Model):
material_stock_code = models.CharField(max_length=255)
class Meta:
ordering = ['material_stock_code']
The order_by() method can be used on any query
views.py
Material.objects.all().order_by('material_stock_code')
I would also recommend looking at django-rest-framework to make the API

Is it possible to create new fields using django admin page interface?

Is it possible to create and delete new charfields or textareas through the Django admin page without harcoding them?
For example, I have a simple model, registered in Django admin page
class DocumentList(models.Model):
title = models.CharField(max_length=200)
def __str__(self):
return self.title
Obviously, it has only one charfield on admin page, something like:
DocumentList: [___________]
How can I add another one and delete her later if needed from Django admin page without actually hardcoding another charfield/textarea in models.py, to make it look like:
DocumentList: [___________]
*****************[___________]
Django models are not meant to be dynamically altered. You have to explicitly add the fields on your model, run migrations to have the fields created in your database backend, and reload your server process (./manage.py runserver does this automatically).
If you want to create a model that can hold an arbitrary amount of text strings instead of just one or a fixed amount, you need to use a many-to-many relation to another model.
You can use a custom form in the admin, either by using the form option of the get_form method. This is the documentation example for how you'd pass a custom form:
from django import forms
from django.contrib import admin
from myapp.models import Person
class PersonForm(forms.ModelForm):
class Meta:
model = Person
exclude = ['name']
class PersonAdmin(admin.ModelAdmin):
exclude = ['age']
form = PersonForm
You can add extra fields, as in any form.
I was wondering why you wanted this. Since you said in a comment it is to submit information to an API, you can also use an action, taking input from the user in an intermediate page.
EDIT: As became apparent in comments, the form needs to be dynamic for the user, and not when it is created. Therefore, the solution is using inlines, which once created and linked to the current model, allow the user to add any number of related forms to the current form.

Django custom user models in 1.8

I'd like to create a project for finding mentor.
In planning i thought, that it would be nice to separate two models on registration users: for students (those, who wants to find mentor) and mentors.
Built-in django user model isn't like that. I plan to add more fields, also several fields can be the same: in students and in mentors.
Can you give me live example of customing model? Would be nice, if you have smth in git or other code sharing.
Shoudl I inherit mentor model from students, because it can have same fields: email, name, surname, etc?
What additional code should i write for working custom model? I read docs and found unknown for me - managers. Should i also customize managers?
If i get success in custom model what problems can i meet in future for auth,registration, changing passwords for this custom model?
Creating 2 separate models is not recommended here. You will need to have separate login process and be careful to avoid problems with sharing pk between users in separate tables. Also I'm pretty sure that django won't allow that.
Better choice is to make 2 profile models, as described in Extending the existing User model. In one of profiles you will store specific data for student and in other specific data for mentors.
Your website has two intended users, so there is no problem with creating two user models. Just make sure to inherit them from user model
from django.contrib.auth.models import User
class Student(User):
...
class Mentor(User):
...
You shouldn't re-invent the wheel, except you really want to learn and practice core features of Django. Just add some add-on library like userena, which "supplies you with signup, signin, account editing, privacy settings and private messaging". In general userena gives an additional UserenaBaseProfile model which is connected to built-in User model. So you can just inherit this model for the Student and for the Mentor:
from django.contrib.auth.models import User
from userena.models import UserenaBaseProfile
class CustomProfile(UserenaBaseProfile):
user = models.OneToOneField(User, unique=True)
common_field_for_all_children = models.IntegerField()
class Meta:
abstract = True
class Student(CustomProfile):
something_student_related = models.IntegerField()
class Mentor(CustomProfile):
something_mentor_related = models.CharField(max_length=255)

Django: how to properly use UserProfile? (Django auth extra information)

i finally can make my Django+Auth app works. I add the extra information to the user as the docs say. Now, i've a simple question. When i'm building a model that is related to the user, which user should i relate to? To auth.models.User or to my accounts.UserProfile?
An example: I've a model for Product, and the Product belongs to a user. Which would be the best option:
class Product(models.Model):
user = models.ForeignKey(auth.models.User)
or
class Product(models.Model):
user = models.ForeignKey(accounts.UserProfile)
I'm currently using auth.models.User, becouse i can issue a get_profile, but some friend told me that i was wrong.
Thank you!
You're doing the right thing.
UserProfile is just an extension of the User model.
And logically you're making a relation of a object with an object, not a relation of a object with some extra information.
Also, as you mentioned, you can always issue the 'get_profile' to get the extra data.

Categories

Resources