Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 2: how to force a foreignkey in admin interface
I'm new to Django and Python. Let's say I'm building an app to manage devices used by users in companies. I have multiple companies, with multiple users and rooms in each. Rooms and users are always linked to a company. A device can be linked to: An user ("Joe's iPhone", "Anna's Laptop") A room ("Conference Room's Computer") A device is always linked to a company. So, I can have a device, that is linked to a company only. So here's my code : #models.py class Company(models.Model): name=models.CharField(max_length=50) class User(models.Model): name=models.CharField(max_length=50) company=models.ForeignKey('Company', on_delete=models.CASCADE) class Room(models.Model): name=models.CharField(max_length=50) company=models.ForeignKey('Company', on_delete=models.CASCADE) class Device(models.Model): company=models.ForeignKey('Company', on_delete=models.CASCADE) user=models.ForeignKey('User', on_delete=models.CASCADE, blank=True, null=True) room=models.ForeignKey('Room', on_delete=models.CASCADE, blank=True, null=True) #admin.py class DevicesInline(admin.TabularInline): model = Device extra = 0 def formfield_for_foreignkey(self, db_field, request=None, **kwargs): if db_field == "Company": kwargs['queryset'] = ## Here I don't know ## return super().formfield_for_foreignkey(db_field, request, **kwargs) class UserAdmin(admin.ModelAdmin): inlines = [DeviceInline] What I want is pretty simple : when I'm editing a user (or a room), I want to be able to add a device for it. But the field "Company" has to be filled with the company for the user or room, and it can't be modified. That's all :) Thanks in advance ! PS: I … -
bootstrap 3.3.0:submenu of submenu is not shown using codepen example
I copied codes from this codepen example. Submenus are shown finely, while the submenus of submenus are not. I have removed some redundant ul/lis in order to let answerer see my question easily without destroying the HTML tree structure written by the original author--J.S. Negley. For example, Dropdown Submenu Link 4.1 is not shown. Bootstrap version: 3.3.0 Jquery version: 1.12.4 Django version : 2.1.5(djangorestframework 3.9.1) Python version: 3.5.0 in my index.js(and inside ready function) $('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) { event.preventDefault(); event.stopPropagation(); $(this).parent().siblings().removeClass('open'); $(this).parent().toggleClass('open'); }); inside my head tag: <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> {% load staticfiles %} <link rel="stylesheet" href='{% static "css/bootstrap/bootstrap.min.css" %}'> <script src='{% static "js/jquery-1.12.4.js" %}'></script> <script src='{% static "js/bootstrap.min-3.3.0.js" %}'></script> <link rel="stylesheet" href='{% static "css/bootstrap/bootstrap.css" %}'> <link rel="stylesheet" href='{% static "css/index.css" %}'> <script src='{% static "js/index.js" %}'></script> <title>MultiLingualNoteTaking</title> inside my body tag: <div class="container pen" style=""> <div class="row"> <div class="col-sm-12"> <nav class="navbar navbar-default navbar-fixed-top" role="navigation"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#" >MultiLingualNoteTaking</a> </div> <div class="collapse navbar-collapse" id="navbar-collapse-1"> <ul class="nav navbar-nav"> <li><a href="#">About</a></li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Create Books<b class="caret"></b></a> <ul class="dropdown-menu"> <li><a class="menu-item" id="menu1-createbook" href="#">Step 1. Create Books</a></li> <li><a class="menu-item" id="menu1-createchapter" href="#">Step 2. Create … -
How do I do date math in a Django ORM query?
I'm using Django with Python 3.7. I have teh below model ... class Article(models.Model): ... title = models.TextField(null=False) created_on = models.DateTimeField(default=datetime.now) I would like to write a Django ORM query where I find all articles that are older than 5 minutes. But I'm not sure how to write such a query. I tried Article.objects.filter((datetime.now(timezone.utc) - created_on)__gte==300) But this results in a SyntaxError: invalid syntax error. -
Running a script parallel to a Django Application at start up (manage.py runserver)
I'm looking to run another script as soon as my Django Application starts up. I wrote a python script to continuously update/create records in my database (SQLiteDB) that is connected to my Django Application. I tried to put the function call in my apps.py (def ready(self)) function, but that is never called. I also tried to add my function in both the urls.py and wsgi.py files, however, this function runs forever, and interacts with the database. Would it be possible to spawn a parallel process to the Django application within the application? (instead of running a separate script). -
Google SSO / Google Login in Django Admin
Need help adding google login in my django admin tried this https://pypi.org/project/django-admin-sso/ but can't make it work it seems to be outdated it currently goes to the google login page and when i click my google account it just goes back my current django admin page without doing anything. Any suggestions the login should only be in the django admin page? -
How to covert two ListAPIViews that are different into a single ModelViewSet
I have a django project I am working on that needs a users and account model. I am using and integrating Django Rest Framework. I was initially using individual API generic views from DRF. I am thinking of converting the individual generic views into a view set. I was able to do it for the user model. I wan to convert the Account model views to a view set. My issue is that I have two versions of the same ListAPIView for the profile model. The top View lists all of the accounts in the database and the second one list all the accounts for an idividual user based on the User__Username foreignkey in the Account model. class UserViewSet(viewsets.ModelViewSet): serializer_class = UserSerializer queryset = User.objects.all() lookup_field = 'username' class AccountListView(ListAPIView): queryset = Account.objects.all() serializer_class = AccountSerializer class AccountUserListView(ListAPIView): queryset = Account.objects.all() serializer_class = AccountSerializer filter_backends = (filters.DjangoFilterBackend,) filterset_fields = ('user', '_id', '_class') def get_queryset(self): return self.queryset.filter(user_username=self.kwargs.get('username')) It says that I can specifically define the properties of a view within the viewset but I want to define two versions of the ListAPIView for the single model. Is there a way to double define the same view in a single viewset. I … -
remove duplicate varible django view.py
Is there any ideas for the duplicate transaction variable? def destroy(self, request, pk=None): date_time = datetime.now() user = get_object_or_404(User, pk=request.user.id) transaction = TransactionVariant.objects.filter(transaction__pk=pk).update(deleted_at=date_time) transaction = Transaction.objects.filter(id=pk).update(deleted_at=date_time) serializer = TransactionSerializer(transaction, many=True) return Response(serializer.data, many=True) -
Django Autocomplete form media tag problem
in my html file i use {{ form.media }} tag but not see included js files in chrome browser {% extends 'base.html' %} {# Don't forget that one ! #} {% load static %} {% block content %} <div> <form action="" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" /> </form> </div> {% endblock %} {% block footer %} <script type="text/javascript" src="{% static 'admin/js/vendor/jquery/jquery.js' %}"></script> {{ form.media }} {% endblock %} Can someone help me ? -
Django 1.11 get_template with full path of template
I have the following search order of directories in settings.py 'DIRS': [os.path.join(DATA_ROOT, 'templates'), os.path.join(PROJECT_ROOT, 'src', 'py', 'my_project', 'app1', 'templates'), os.path.join(PROJECT_ROOT, 'src', 'py', 'my_project', 'app2', 'templates')), ], There is a template 'test_template.html' under app1 and app2. I want to programatically load app1/test_template1.html or 'app2\test_template2.html'by giving django.template.loader.get_template() the full path to the file (so that the correct template be loaded). But despite giving the full path it still loads the app/test_template1.htmlbecause it has higher priority in search order. Reversing the order will not help because then it will start loadingapp2/test_template.html`. I can keep the filenames unique but it should be something simpler. Any idea. Thanks. -
In a marketplace app, Is it safe to store how much each seller is owed in the database?
We are developing a marketplace for freelancers. Freelancers can complete work for payments and have the option to withdraw funds they earned to their bank accounts. Let's assume a freelancer has completed a service for $100. Our platform charged the customer $100 and now the freelancer is owed that amount. Is it safe to have an integer field connected to the ID of the freelancer with the value of '100' and allow freelancers to withdraw based on that value? Of course all withdrawals will go through manual reviews but it feels like bad practice to store something so sensitive in a simple integer field. Is there a better approach to storing such information? -
Group by then loop
So I have products that I want to loop through display on a Django detail view. The detail view is for a particular truck that will take all the products assigned to it to a city. So all the products on the view are assigned to this particular truck. The problem is, each product is also assigned to a particular customer. So I want the view to look something like Truck 1 detail view Customer 1 Product 1 Product 2 Product 5 Customer 2 Product 3, Product 4, Produt 6 As a basic example. The real life example may have 20-30 products and 5-6 customers. Of course I could just do some kind of order by but I want the looping of these to allow me to start new style of formatting whenever there is a new customer (similar to the above format), in order to make it easier to view for the employee who will be loading this truck. Is this possible? as it's confused me a little bit. -
Django Raw Query Output Inconsistent with pgAdmin Output
I'm using django with a postgres 10 db engine to build a web based search tool via forms. When executing the queries via raw SQL in django I only receive 3 records as opposed to 902 when running the same SQL in the Ouery Tool of pgAdmin. I've tried using the django ORM to build my queries but the examples are so simple I haven't been able to successfully utilize it for my needs. Guidance on querying multiple models in the manner below would be appreciated. Django Raw SQL statement ProstateUpper = 'Prostate' ProstateLower = 'prostate' GenderMale = 'Male' GenderAll = 'All' Master_Query = Eligibilities.objects.raw('''SELECT DISTINCT ON (Eligibilities.nct_id) Eligibilities.id, Studies.brief_title, Eligibilities.nct_id, Conditions.name, Eligibilities.gender, Eligibilities.minimum_age, Eligibilities.maximum_age, Eligibilities.criteria, Interventions.intervention_type, Interventions.name, Facilities.city, Facilities.state, Facilities.country, Brief_Summaries.description, Facility_Contacts.name, Facility_Contacts.email FROM Eligibilities INNER JOIN Studies on Studies.nct_id = Eligibilities.nct_id INNER JOIN Conditions on Conditions.nct_id = Eligibilities.nct_id INNER JOIN Interventions on Interventions.nct_id = Eligibilities.nct_id INNER JOIN Facilities on Facilities.nct_id = Eligibilities.nct_id INNER JOIN Brief_Summaries on Brief_Summaries.nct_id = Eligibilities.nct_id INNER JOIN Facility_Contacts on Facility_Contacts.nct_id = Eligibilities.nct_id WHERE ((Conditions.name LIKE %s OR Conditions.name LIKE %s)) AND (gender LIKE %s OR gender LIKE %s) ''', [ProstateUpper, ProstateLower, GenderMale, GenderAll])[:1000] pgAdmin SQL statement SELECT DISTINCT ON (eligibilities.nct_id) eligibilities.id, studies.brief_title, eligibilities.nct_id, conditions.name, … -
djnago form allow users query using combination foreignkey fields in a mdel
I am new to django and was trying to learn by developing small web app. but I am stuck now and I couldn't come up with a working solution no matter I tried. I have a quiz model with three foreignkey fields: level, subject and year. The three fields uniquely identify a quiz. When the users want to take a quiz, they have to select each fields and submit a request. How can I populate the Quiz form fields with contents from Quiz model. Any suggestions would be appreciated. class Quiz(models.Model): name = models.CharField() level= models.ForeignKey() type= models.ForeignKey() year= models.ForeignKey() class Level(models.Model): level= models.CharField() class Type(models.Model): type= models.CharField() class Year(models.Model): year= models.CharField() class QuizForm(ModelForm): class Meta: model = Quiz fields = ['level', 'type', 'year'] -
Django problem - cannot get the value from the front - query value is none
I've got a problem with an basic searcher app - its about to searching the database for the value that i will be taping in the search bar. I was trying to get the solution from the internet, but there is none or its hard to find something. I was looking for some tut, but none of them works in my app. Main problem is : ValueError: Cannot use None as a query value. I know that this query is none, but i dont get it why and how. So, this is my base.html form code: <form type="GET" action="" accept-charset="utf-8"> <input type="text" name="query" placeholder="Search..."/> <input type="submit" value='Search' /> </form> views.py: class FilmListView(ListView): model = Film template_name = 'searcher/home.html' context_object_name = 'films' ordering = ['-date_posted'] paginate_by = 3 query = request.GET.get('query') queryset_list = Film.objects.filter(title__icontains=query) urls.py: urlpatterns = [ path('', FilmListView.as_view(), name='search-home'), path('films/', SearchedFilmListView.as_view(), name='searched-films'), path('user/<str:username>', UserFilmListView.as_view(), name='user-films'), path('film/<int:pk>/', FilmDetailView.as_view(), name='film-detail'), path('film/new/', FilmCreateView.as_view(), name='film-create'), path('film/<int:pk>/update/', FilmUpdateView.as_view(), name='film-update'), path('film/<int:pk>/delete/', FilmDeleteView.as_view(), name='film-delete'), path('about/', views.about, name='search-about'), ] The other thing in this app is that i have to import request to make it work. If you got any solution or any tips just help. THX for answers. -
How to dynamically filter a view by ModelChoiceField selection
I have created a template that renders a dropdown list of students. I want to filter a query set on another view to show schedule info for just the student that was selected. perm_id in student_list is primary key and perm in StudentSchedule is foreign key. Here are snippets of my models.py, forms.py and views.py models.py class StudentList(models.Model): student_name = models.CharField(max_length=45, blank=True, null=True) perm_id = models.IntegerField(primary_key=True) class StudentSchedule(models.Model): perm = models.ForeignKey(StudentList, on_delete=models.CASCADE) begin_period = models.CharField(max_length=45, blank=True, null=True) section_id = models.CharField(max_length=45, blank=True, null=True) course_title = models.CharField(max_length=45, blank=True, null=True) last_name1 = models.CharField(max_length=45, blank=True, null=True) forms.py class StudentForm(forms.Form): Student = forms.ModelChoiceField(queryset=StudentList.objects.all() .order_by('student_name')) views.py class ScheduleView(View): form_class = ScheduleForm template_name = 'learning_logs/student_schedule.html' def get(self, request): form = self.form_class(initial={}) data = StudentSchedule.objects.filter() return render(request, self.template_name, {'form': form, 'data': data}) I can do this and get student with id # 123456 data = StudentSchedule.objects.filter(perm=123456) But, I want Django to use the perm_id from the student selected from StudentList -
Django, MySQL and Microsoft Visual C++
I will directly tell what's happening: I'm trying to create a Django project in PyCharm and I'm trying to use MySQL. In my project's virtual enviroment I have installed: -Django 2.1.5 -mysql-connector-python-rf 2.2.2 -pip 18.1 -pytz 2018.9 -setuptools 40.6.3 What I yet need to install is "mysqlconnector", either I try to install it with PyCharm or Windows Cmd Console I get the following error: "error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": https://visualstudio.microsoft.com/downloads/" In my Windows Apps I have: -Microsoft Visual C++ 2015 Redistributable(x64) - 14.0.23026.0 Extra data: - Python Version: 3.7.2 - Windows 10 x64bits - Pycharm IDE I will say again, I get this error either I try to install mysqlclient with PyCharm or Windows cmd console. Any solution? Many thanks! -
DRF Add some extra values to listview from external resource
I am overriding the def list(self, request) function of a ViewSet because i want to add some more fields to the returned Response by extracting some more info from an external API source. The merging is done through a common field of the two result sets called 'identity'. With some pseudocode below is what i want: class ExampleViewSet: def list(self, request): call_external_api = get_my_json_data_through_api() json_data = call_external_api.json() queryset = ExampleModel.objects.all() list_result = [entry.__dict__ for entry in queryset] result = {x['identity']: x for x in list_result + json_data}.values() serializer = MyCustomSerializer( data=result, many=True) serializer.is_valid() Is it a correct approach?. If yes how can i achieve my goal? -
Django model of a rent contract using Generic Foreign Key
I'm trying to model a rent contract in Django and use the admin form to insert and modify it. Both owner and tenant can be companies (VAT number) or individuals (no VAT number). Companies and individuals are stored in two different models (Company and Individual). I'm trying to solve this problem using Generic Foreign Key but I'm not able to show the tenant name in the admin page, only an integer field not friendly at all. gestimm is the name of the app and that's my oversimplified models: # my gestimm/models.py # from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models class Individual(models.Model): name = models.CharField(max_length=100, help_text='Name') def __str__(self): return self.name class Company(models.Model): name = models.CharField(max_length=100, help_text='Name') def __str__(self): return self.name class Contract(models.Model): description = models.CharField(max_length=30) start = models.DateField() stop = models.DateField() def __str__(self): return self.description class Tenant(models.Model): limit = models.Q(app_label='gestimm', model='individual') | models.Q(app_label='gestimm', model='company') contract = models.ForeignKey(Contract, on_delete=models.CASCADE, null=True, blank=True) content_type = models.ForeignKey(ContentType, on_delete=models.PROTECT, help_text='Tenant', null=True, limit_choices_to=limit) object_id = models.PositiveIntegerField(null=True) tenant = GenericForeignKey('content_type', 'object_id') How I tried to solve the problem: # my gestimm/admin.py # from django.contrib import admin from .models import Individual, Company, Contract, Tenant class TenantInline(admin.StackedInline): model = Tenant extra = 1 class ContractAdmin(admin.ModelAdmin): … -
Django iterate on template with 2 dicts from views.py
I have the following code : views.py file : twittdict = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6} twitlistdict = {'A' : 'a', 'B': 'b', 'C': 'c'} return render(request, 'homepageapp/home.html', {'twittdict' : twittdict, 'twitlistdict' : twitlistdict}) homepage.html file : {% for user in twitlistdict %} <a href="https:*/{{ twittdict.user.3 }}"> <div class="card border-white mb-3"> <p class="card-title"><div class="media"> <img class="mr-3 align-self-center" src="https://source.unsplash.com/random/90x94"> <div class="media-body"> <h5>{{ twittdict.user.0 }}</h5> <h6>@{{ twittdict.user.1 }}</h6> <p></p> </div> </div></p> <img class="card-img-top img-fluid" src="https://source.unsplash.com/random/301x200" alt=""> <div class="card-body"> <p class="card-text">{{ twittdict.user.4 }}</p> <p class="card-text"> <hr> <i class="fas fa-retweet">{{ twittdict.user.6 }} </i> <i class="far fa-heart">{{ twittdict.user.5 }}</i> <span class="pl-5"> {{ twittdict.user.2 }}</span> </p> </div> </div> </div>{% endfor %} When i preview the page with the browser, instead of loop items ( eg: twittdict.user.2 corresponding value ), nothing is showed. Blank. How can i made this work and display correct values in the page ? Really struggling with this. Any help is greatly appreciated Thank you in advance. -
How do I write a Django ORM query where the select table shares a common column with another table?
I'm using Django and Python 3.7. I have these two models. Note they both have a similar field class Article(models.Model): publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE,) class WebPageStat(models.Model): objects = WebPageStatManager() publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE, ) score = models.BigIntegerField(default=0) I would like to write a Django ORM query that selects one of the models but does a join on the shared column in order to do a comparison on the "score" field. I tried the below, but alas the error Article.objects.filter(publisher=webpagestat.publisher, webpagestat.score__gte==100) File "<input>", line 1 SyntaxError: positional argument follows keyword argument How do I include the "WebPageStat" table in my join? -
How to get a django template to pull information from two different models?
I am coding a basic django application that will show a table of current store sales, based off of information from a MariaDB database. The data is entered into the database through a seperate process, so it isn't created in Django, it is just using a simple python script to load a csv file and parse it into an Insert query. There are two models in my code, Stores and ShowroomData. Showroomdata holds all of the records from the python script, however it does not hold any store information. I would like for it to be able to show all of the showroom data as well as the store's location title which is not stored in the ShowroomData model. I know I need to seperate models but can not figure out how to get them to link together. class ShowroomData(models.Model): storeid = models.IntegerField(default=0) # Field name made lowercase. date = models.DateField() # Field name made lowercase. time = models.TimeField() # Field name made lowercase. sales = models.DecimalField(max_digits=10, decimal_places=2) # Field name made lowercase. tax = models.DecimalField(max_digits=10, decimal_places=2) # Field name made lowercase. class Meta: unique_together = (('storeid', 'date', 'time'),) db_table = 'showroomdata' class Stores(models.Model): storeid = models.IntegerField(primary_key=True) location = models.CharField() … -
How to modify django import export package on the admin page
I am using Django Import export to import list of books through the admin page. I was wondering if it is possible to customize Django Admin page so it has a model choice field for the field of month that user can chose Models.py: from django.db import models class Author(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Book(models.Model): JANUARY = '1' FEBRUARY = '2' MARCH = '3' APRIL = '4' MAY = '5' JUNE = '6' JULY = '7' AUGUST = '8' SEPTEMBER = '9' OCTOBER = '10' NOVEMBER = '11' DECEMBER = '12' MONTH_CHOICES = ( (JANUARY, 'January'), (FEBRUARY, 'February'), (MARCH, 'March'), (APRIL, 'April'), (MAY, 'May'), (JUNE, 'June'), (JULY, 'July'), (AUGUST, 'August'), (SEPTEMBER, 'September'), (OCTOBER, 'October'), (NOVEMBER, 'November'), (DECEMBER, 'December'), ) name = models.CharField('Book name', max_length=100) author = models.ForeignKey(Author, models.SET_NULL, blank=True, null=True) author_email = models.EmailField('Author email', max_length=75, blank=True) imported = models.BooleanField(default=False) published = models.DateField('Published', blank=True, null=True) price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) categories = models.ManyToManyField(Category, blank=True) month = models.CharField( max_length=2, choices= MONTH_CHOICES, default=JANUARY, ) def __str__(self): return self.name admin.py from django.contrib import admin from import_export import resources from .models import * from import_export.admin import ImportExportModelAdmin from import_export.fields import Field … -
How do I make this friend request class-based-view work?
I am trying to make a friend request class-based-view work on a django project, but keep getting errors. The error I am currently getting is: TypeError at /friend_request/joe int() argument must be a string, a bytes-like object or a number, not 'User' My Friend model is not looking for an int() though, so I am unsure of what is going on. class-based view: class AddFriend(APIView): def get(self, request, username): friend = User.objects.get(username=username) current_user = request.user.username f = Friend(current_user, friend, 1) f.save() url: url(r'^friend_request/(?P<username>[\w.@+-]+)', AddFriend.as_view(), name = 'add_friend'), model: class Friend(models.Model): #static variables for friend_status attribute FRIENDS = 1 A_REQUESTS_B = 2 B_REQUESTS_A = 3 friend_A = models.ForeignKey(User, related_name='friend_A') friend_B = models.ForeignKey(User, related_name='friend_B') friend_status = models.IntegerField() def __str__(self): return '%s and %s friendship' % (self.friend_A, self.friend_B) class Meta: unique_together = (('friend_A', 'friend_B'),) Ideally this CBV would figure out who the user sending the request is, figre out what friend is being "looked up" in the url, and create/save a new friend instantiation. Where is this int() error coming from, and how do I fix it? -
How to define APIView's url?
I'm trying to make an APIView with the Django Rest Framework. When I associate the view with the url, I got this error : AssertionError: basename argument not specified, and could not automatically determine the name from the viewset, as it does not have a .queryset attribute. Here is mys APIView : class ExampleView(APIView): authentication_classes = (SessionAuthentication, BasicAuthentication) permission_classes = (IsAuthenticated,) def get(self, request, format=None): content = { 'user': unicode(request.user), # `django.contrib.auth.User` instance. 'auth': unicode(request.auth), # None } return Response(content) And the router : router = routers.DefaultRouter() router.register('api/example', views.ExampleView.as_view()) So, what's wrong ? Thank you ! -
Auto increment field per user
I have a django app and I need to have two autoincrement fields. One is the pk and Django's default is good enough for that. But I need a second one that starts at 1 for each user. I have a User and they can create Tickets, and each one has a unique number relative to the user. So Ticket#1 for user1 and Ticket#1 for user2 would be two different entries and each user can see only their own tickets. This is necessary, and the ticket number is not arbitrary. Users need to see their ticket number and it must start at one always and increase according to each ticket created. I thought about storing the count on the user, but I'm not sure what would be the best approach for this. Ideally I would like to not have to modify my views and do everything on the models.