Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to use filter() queryset without use loop here
i want avoid using queryset inside loop cuz that hit database a lot i have to list Degreyid: [1, 3, 2, 3] companyid: [2, 2, 2, 1] i want use filtering in conjunction: -i want filter for object have Degreyid:1 and companyid:2 and seconde test should be Degreyid:3 and companyid:2.......... Degreyid:3 and companyid:1 . i dont want use loop like this : i=0 list=[] while i < len(listilam): ddegrycomp = DegreyCompany.objects.filter(withdegrey=Degreyid[i], company=companyid[i]) i+=1 there is any way to use filter with two list in parallel ?? note: using : .filter(withdegrey__in=Degreyid, company__in=companyid) dont help here -
django update form with materialize modal
I have this code in my django project and iam trying to edit records with a materialize modal but it always return url with id 1 "cpemodels/edit/1/" and so i can only edit record with id 1, I have a table with edit button in every row. (i dont have any issues when edit record with external page). urls.py path('cpemodel/edit/<int:pk>/', cpemodel_edit, name='cpemodel_edit') views.py def cpemodel_edit(request, pk=None): cmodel = get_object_or_404(CPEMODEL, pk=pk) if request.method == "POST": form = CPEMODELForm(request.POST, instance=cmodel) if form.is_valid(): form.save() return redirect('cpemodel') else: form = CPEMODELForm(instance=cmodel) return render(request,'provision/cpemodel/edit.html',{'form': form, 'cmodel': cmodel }) cpemodel.html <table class="responsive-table striped"> <thead> <tr> <th>Modelo</th> <th>Descripción</th> <th>Vendor</th> <th>Tipo</th> <th>ETHs</th> <th>POTs</th> <th>TV</th> <th>WIFI</th> <th></th> </tr> {% for cpemodel in object_list %} <tr> <td>{{cpemodel.model}}</td> <td>{{cpemodel.desc}}</td> <td>{{cpemodel.vendor}}</td> <td>{{cpemodel.type}}</td> <td>{{cpemodel.eth_ports}}</td> <td>{{cpemodel.pot_ports}}</td> <td>{{cpemodel.catv_port}}</td> <td>{{cpemodel.wifi}}</td> <td><a class="btn-floating waves-effect waves-light green light-3 hoverable" href="{% url 'cpemodel_edit' cpemodel.id %}"><i class="material-icons">edit</i></a></td> <td><a class="btn-floating waves-effect waves-light red light-3 hoverable" href="{% url 'cpemodel_delete' cpemodel.id %}"><i class="material-icons">delete</i></a></td> <td><button class="waves-effect waves-light btn modal-trigger" data-source="cpemodel/edit/{{cpemodel.id}}/" href="#modal1">Modal</button></td> <div id="modal1" class="modal"> <div class="modal-content"></div> </div> javascript code $(document).ready(function(){ $('.modal').modal(); $('.modal-trigger').click(function(){ var url = $('.modal-trigger').attr("data-source"); // use other ajax submission type for post, put ... $.get( url, function( data ) { // use this method you need to handle the response from the … -
Django : create chat with post author just with a submit button
I got a question I did not solved. I try to create a chat with the author of the post. But I got an issue when I tried to catch him directly with form instance: I've created a form with crispy form without field. All field are passed with form.instance. I really thank you in advance. #Post detail class PostDetail(generic.DetailView,FormMixin): model = Cuisine context_object_name = 'post' template_name = 'post_detail.html' form_class = CreateChannelForm def get_context_data(self, **kwargs): context = super(PostDetail, self).get_context_data(**kwargs) context['cuisine_user'] = Cuisine.objects.get(pk=user_id) context['form'] = self.get_form() return context def form_valid(self, form): if form.is_valid(): form.instance.post = self.object form.instance.usera = self.request.user form.instance.userb = cuisine_user #Here is the error form.save() return super(PostDetail, self).form_valid(form) else: return super(PostDetail, self).form_invalid(form) I got private space: class Channel(models.Model): usera = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="channel_usera") userb = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="channel_userb") post = models.ForeignKey(Cuisine,on_delete=models.CASCADE,related_name="channel_post") date_created = models.DateTimeField(auto_now_add=True, null=True) is_active = models.BooleanField('', default=False) slug = models.SlugField(editable=False,unique=True) Here is the model of the post: class Cuisine(models.Model): #Remplir manuellement title = models.CharField(max_length=90) user = models.ForeignKey(User,on_delete=models.CASCADE,related_name='cuisine_user') image = models.ImageField(upload_to='nutriscore/') description = models.TextField(max_length=1000, blank=True) -
Conditional pagination_by number in Django
I have a Django view with pagination: class MyListView(ListView): model = Model context_object_name = "Model" template_name = "template.html" paginate_by = 6 This template has a search bar that works fine: def get_queryset(self): if query: postresult = account_list.filter(name__contains=query) list = postresult return list The problem is, I want the pagination value for a page with a search query to be 20. How can I make the paginate_by value a conditional? -
Wagtail: Blog Pagination with Detailed Page Next and Previous Buttons
I have a pagination on my blog listing page. However, I would like it so that when you are in the Blog posts Details page there is still the option to loop through the posts with a next and previous post option. models.py Here is the repo I have been learning on Any help would be greatly appreciated. Original code from Kalob Taulien @CodingForEverybody -
Django custom auth Access Denied
I am writing a simple Django login page. Where I have an app that handles the authentication of the web page, which then redirect to a seperate app containing the home page. The login functionality is working, if i entered in a wrong password I will get the error Invalid username or password. Please try again.. When I log in and try to access the HomePageView however. I am getting a permission denied error. Am I missing something? Models.py class Users(AbstractUser): registration_id = models.CharField(max_length=100) last_active = models.DateTimeField(null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) REQUIRED_FIELDS = ['password'] USERNAME_FIELD = 'username' EXCLUDE_FIELDS = ["last_active"] forms.py class MyLoginForm(Form): username = forms.CharField(label='Username', max_length=100) password = forms.CharField( widget=forms.PasswordInput()) views.py (auth app) class LoginView(View): template_name = 'auth/login.html' def get(self, request, *args, **kwargs): if request.user.is_authenticated: return redirect(request, reverse('homePage')) return render(request, self.template_name, {'form': MyLoginForm} ) def post(self, request, *args, **kwargs): is_first_login = False try: form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user_info = auth.authenticate(username = username, password = password) if not user_info: messages.error(request,'Invalid username or password. Please try again.') return render(request, self.template_name, {'form': MyLoginForm} ) user_profile = Users.objects.get(username = user_info) login(request, user_profile) messages.info(request, "login successful") return redirect("homePage") else: messages.error(request, "Failed to log in") return … -
How do I display a link from view in a Django template?
Where to find info how to throw links {%url 'name'%} in the template from the view? When creating an article in the admin panel, a link to a page with an identical theme should be added to the "a" tag. I understand that you need to write a model, but what if there are a lot of pages(you need a choice)? Who the faced? view` class BlogArticles(ListView): # model = BlogNewArticles template_name = "blog/blog.html" def get_context_data(self, **kwargs): context = super(BlogArticles, self).get_context_data(**kwargs) context['blockheader'] = BlogPromoHeader.objects.all() # context['blockcenter'] = BlogPromoCentre.objects.all() # context['blockfooter'] = BlogPromoFooter.objects.all() # html {% for post in object_list %} <div class="blog vertical-blog col-lg-4 col-md-4 col-sm-6 col-xs-12"> <div class="blog-foto"><a href="{{ post.get_absolute_url }}"><img src="/media/{{ post.article_image_field }}"></a></div> <div class="blog-date">{{ post.article_datetime }}</div> div class="blog-subtitle"><a href="">{{ post.article_razdel }}</a></div> <div class="blog-title"><a href="{{ post.get_absolute_url }}">{{ post.article_title }}</a></div> </div> {% endfor %} -
I am using django crispy forms how can I change this text to start from the top and get to the below line when the line is full
So guys my site looks like this right now. Here's the site! You will definitely understand my problem if you didn't from the title HTML {% load crispy_forms_tags %} <div class="row"> <div class="col-md-6 offset-md-3" id="ada"> <h3>Makale Ekle</h3> <hr> <form method = "post"> {% csrf_token %} {{form|crispy}} <br> <button type = "submit" class = "btn btn-danger">Ekle</button> </form> </div> </div> CSS body { background: rebeccapurple; font-family: Arial, Helvetica, sans-serif; } #ada { margin: auto; margin-top: 100px; padding-top: 5rem; padding-bottom: 5rem; border: 5px solid rgb(49, 2, 68); background-color: purple; border-radius: 5%; } h3 { font-size: 2rem; color: white; } label { color: white; } input { width: 800px; margin-bottom: 1.2rem; size: 2rem; border: 3px solid purple; text-align: justify; } input[name="context"] { height: 10rem; padding: 20px 10px; line-height: 28px; } So guys I think I am missing something easy. I tried to solve it by adding some code in CSS but it definitely didn't work. -
group items with same value with that value as header
I'm practicing my python and django by making a recipe site. I can add ingredients (class RecipeIngredient) per recipe using inlines, searching for ingredients i already have in my database (class Ingredient) (with nutrional facts etc). This results in one big list of ingredients per recipe. To order them I added a step and a stepnum attribute. I return a list ordered by the stepnum, but how can I div them apart? For instance. If you make a cake you would have ingredients for the cake, and for the icing. all the ingredients for the icing would get a step value of "icing", and a stepnum of 0. all the ingredients for the cake would get a step value of "cake" and a stepnum of 1. I would like all the ingredients with stepnum 1 to appear under one that has the value associated with the items that have a stepnum value of 1, in this case "cake". How? I have this code on my recipedetail.html: <div><h1> INGREDIENTS: </h1></div> <div> {% for ingredients in recipe.get_text %} <ul> {% for item in ingredients %} <li><em> {{item.1|safe}} {% if item.2 is not None %} {{item.2|safe}} {% endif %} {{ item.0|safe}} </em></li> {% … -
Django migrations wrongly applaying
Basic problem I'm working on a django project where I'm using multiple databases with a custom router. Therefore, django should know which database to use for which app. Now I came across some in my opinion weird behaviour and wanted to ask if anyone knew if that is the correct behaviour or not, especially because the github page doesn't seem to have an issues tracker. To make the point clear, I'm using an extreme example, which I nonetheless tried. For testing purposes, I set the allow_migrate function to just return False. I did create a custom router which overrides the allow_migrate function and I also registered it under the DATABASE_ROUTERS settings. The allow_migrate function is also called, as I checked it with some print statements. How I understand the router usage The way I understand the documentation for using multiple databases with a custom router, the allow_migration method specifies if a migration is to be applied for the current db, app_label and model_name. If it returns True, the migration is applied, if False, it is 'silently skipped' and therefore not applied. What I expected As I set the allow_migrate function to return False all the time, I expected that none … -
Django: Need to check POST request mime type before uploading it to S3
So, here's my basic problem. I have form in my frontend that posts a file to my Django backend. Django will then pass that file off to AWS S3 for storage. I need to verify the file is a PDF or DOC before uploading to S3. I thought to check it's mime type with python-magic like so, form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): mime_type = magic.from_buffer(request.FILES['file'].read(), mime=True) if mime_type in ALLOWED_MIMETYPES: upload(request.FILES['file'], file_name) where upload just basically wraps boto3's upload_fileobj method. However, according to this Stack, the .read() I use in magic.from_buffer() empties the file buffer, so that when I pass the file into the upload method, it no longer exists. I've tried using copy and deepcopy to duplicate the file before checking it's mime type and then passing the duplicate into the upload function, but copy and deepcopy don't seem to work with fileobjects, as the duplicate is also empty after calling .read() on the original. How can I copy the file passed through the POST request so that I can check its mime type before passing it to S3 for storage? Is there another way to check it's mime type that doesn't involve emptying the file buffer? -
How to approve all installed apps permission programmatically in Django
settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', # Local apps 'users.apps.UsersConfig', # Third party apps 'allauth', 'allauth.account', 'allauth.socialaccount', ] views.py @user_passes_test(lambda u: u.is_superuser) def create_group(request): groups = Group.objects.all() if request.method == 'POST': group_name = request.POST.get('group_name') group = Group.objects.create(name=group_name) return HttpResponse(group.name) else: ctx = {'groups': groups} return render(request, 'users/admin/create_group.html', ctx) Here, I've created a view for creating user group programmatically. Now I want to allow users to approve permission just like django-admin dashboard. Like select few permissions and then press submit button to add these permissions to selected group. There must be some way doing so, because django admin itself doing it this way. I'd like to get some ideas how can I get this done. -
How do I setup multiple Django sites in Ubuntu 18
I bought a virtual server. Now I want to design two or more sites on it. The server company also provided me with an IP. How do I program my settings so that I can set up and access multiple sites through this server? In addition; I program using Python and the Django framework and on this server I can use Ubuntu 18.04, CentOS 7.06 and Debian 9. -
Django - Serialize an object with an object whitin
guys, I can't figure out how to do the following: I need to serialize a post object. If I do: return JsonResponse([post.serialize() for post in posts], safe=False, status=200) I get but I need to include additional data from the user: I can do it by doing a list like: post_list = [] for post in posts: post = { 'author': { 'user': post.author.user.username, 'name': post.author.user.first_name, 'avatar': post.author.avatar.url, }, 'message': post.message, "created": post.created, 'likes': post.likes.count(), } post_list.append(post) But I think this is not the best way to do it. Is it posibble to nest the user object in the post object using serialize()? Thanks in advance!!!! -
Poor Django architecture leading to "django.db.utils.OperationalError: no such table: main.invTypes"?
I hope I can get some help with an issue I've been beating my head against for a while now. I like to think I'm an intermediate Python developer, I'm working a on a pet project to improve my Django whilst focussing on getting the structure right and understanding how to write more pythonic code. I'm focussing on getting the model definitions correct to begin with and haven't started to look at forms or views yet. Perhaps I'll end up using it as a glorified database interface.... The following code creates a Market Order item which is stored in a database containing all the users data, which is downloaded from a 3rd party API. type_id is referenced in a separate database as it's taken from the static data download available from a 3rd party. I think it makes sense to separate them like this as it'll make database admin easier and cleaner in the future. I've checked and debugged the database router and fairly confident it's setup correctly. class MarketOrder(models.Model): date = models.DateTimeField(auto_now = True) duration = models.PositiveSmallIntegerField(default = 90) is_buy_order = models.BooleanField(default = False) issued = models.DateTimeField(blank=True, null=True) # tzinfo = tzlocal(), location_id = models.PositiveIntegerField(blank=True, null=True) min_volume = models.PositiveIntegerField(default … -
Cannot resolve keyword 'get_album_detail' into field
Am trying to create a search field that can get the artist name and the name of the song, but am getting an error saying "Cannot resolve keyword 'get_full_album_detail' into field." once i try to query from 'get_album_detail'. class Artist(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) username = models.CharField(max_length=50, null=True, unique=True) class Album(models.Model): artist = models.ForeignKey(Artist, on_delete=models.CASCADE) name = models.CharField(max_length=120) @property def get_album_detail(self): return str(self.artist.username) + " - " + str(self.name) ### CUSTOM MODEL MANAGER class SongQuerySet(models.QuerySet): def search(self, query = None): qs = self if query is not None: or_lookup = (Q(get_album_detail__icontains=query)| Q(slug__icontains=query) #Q(artist__user__icontains=query) ) qs = qs.filter(or_lookup).distinct() return qs ## SEARCH VIEW class AlbumSearch(ListView): template_name = 'search/song_search.html' paginate_by = 15 def get_queryset(self): request = self.request query = request.GET.get('q', None) if query is not None: song_result = Song.objects.search(query=query) return song_result -
duplicate when use filter() with values()
i have this 3 models : class Degrey(models.Model): name = models.CharField(max_length=200) class DegreyCompany(models.Model): withdegrey = models.ForeignKey(Degrey, on_delete=models.CASCADE, null=True, blank=True) company = models.ForeignKey(Secondary, on_delete=models.CASCADE, null=True, blank=True) spesial = models.ForeignKey('Spesial', on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=200, default=withdegrey.name, null=True, blank=True) nomberetud = models.PositiveSmallIntegerField(null=True, blank=True) nomberexist = models.PositiveSmallIntegerField(null=True, blank=True) class Meta: unique_together = ('withdegrey', 'company', 'spesial'), def __str__(self): return self.name class Secondary(models.Model): withprimary = models.OneToOneField(CustomUser, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=200) codeonec = models.PositiveSmallIntegerField() codelocal = models.PositiveSmallIntegerField() address = models.CharField(max_length=200) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.name) and the model: class MediaSecParnt(models.Model): withdegrey = models.ForeignKey(Degrey, on_delete=models.CASCADE) withsecondray = models.ForeignKey(Secondary, on_delete=models.CASCADE) nomberesteda = models.PositiveIntegerField(null=1, blank=1) nomberhodor = models.PositiveIntegerField(null=1, blank=1) when use querset to accses the value of through model -MediaSecParnt- : listilam = MediaSecParnt.objects.filter(date__range=[primary1, primary2]).values( 'withsecondray__name','withdegrey__name','withsecondray_id','withdegrey_id').annotate(nomberhodor=Sum('nomberhodor'), nomberesteda=Sum('nomberesteda')) i get good result but when i want to add -nomberetud- like this queryset : listilam = MediaSecParnt.objects.filter(date__range=[primary1, primary2]).values( 'withsecondray__name', 'withdegrey__name', 'withsecondray_id', 'withdegrey_id','withsecondray__degreycompany__withdegrey_id').annotate( nomberhodor=Sum('nomberhodor'), nomberesteda=Sum('nomberesteda'),nberetud=Sum('withsecondray__degreycompany__nomberetud')) its give me duplucat value : <QuerySet [ {'withsecondray_id': 2, 'withdegrey_id': 1, 'withsecondray__degreycompany__withdegrey_id': 1, 'nomberhodor': 600, 'nomberesteda': 800, 'nberetud': 510}, {'withsecondray_id': 2, 'withdegrey_id': 1, 'withsecondray__degreycompany__withdegrey_id': 2, 'nomberhodor': 600, 'nomberesteda': 800, 'nberetud': 1220}, {'withsecondray_id': 2, 'withdegrey_id': 2, 'withsecondray__degreycompany__withdegrey_id': 1, 'nomberhodor': 500, 'nomberesteda': 1000,'nberetud': 510}, {'withsecondray_id': 2, 'withdegrey_id': 2, 'withsecondray__degreycompany__withdegrey_id': 2, 'nomberhodor': … -
HTMLCalendar displaying as a String instead of using the HTML properly (Django)
I'm trying to display an HTMLCalendar in my django project but it's only displaying the html code instead of the actual Calendar. views.py def CalendarView(request): cal = HTMLCalendar().formatmonth(2020, 10, withyear=True).replace('<td ', '<td width="150" height="150"') return render(request, 'calendar.html', {'cal': cal}) calendar.html {% extends 'base.html' %} {% block tilte %} Home {% endblock %} {% block body %} <div id="content-main"> <ul class="object-tools"> <li> <a href={{ previous_month }}> Previous month </a> </li> <li> <a href={{ next_month }}> Next month </a> </li> </ul> {{ cal }} {% endblock %} This is what gets displayed instead of the actual calendar -
Checkmark in Django, getting which one is checked
I'm new in django and trying to set a form like this: my form So far I did this: result.html: .... <form id="form" name="form" method="GET"> <p> <label class="container">Yes <input type="checkbox" name="1"> <span class="checkmark"></span> </label> <br> <label class="container">No <input type="checkbox" name="0"> <span class="checkmark"></span> </label> <br> <label class="container">No proper image <input type="checkbox" name="2"> <span class="checkmark"></span> </label> <br> </p> .... in views.py: def result(request): .... if request.method == 'GET': context = {} context['form'] = FormYesOrNo() .... return render(request, template_name, response1) in forms.py: choices = [(1, 'Yes'), (0, 'No'), (2, 'none')] class FormYesOrNo(forms.Form): def PrdJudgeRe(self): PrdJudge = forms.TypedChoiceField( choices=choices, coerce=str) return (PrdJudge) Now in views.py I do not know how to get the checked box index or value. when running server and for example I check yes in the log I see this: "GET /result/?1=on HTTP/1.1" 200 1389 which means that it can see 1 is on but how can I get that? -
How to import 2 or more js files into jinja2
I know that to import a js file, I can simply do: <script src="/static/js/example.js"> But i need to import two or more files js into my jinja file. And when i do this: <script src="/static/js/example.js"> <script src="/static/js/example2.js"> Jinja only loads the first file. I searched a lot on the web, but all the examples are using HTML and not Jinja. -
Choosing the right datetimepicker
I am having a tough time finding a datetimepicker that does exactly what I need and works with Bootstrap 4, Django, and Django Crispy Forms. The critical thing I need is the ability for the user to type what they want in the date input field without the calendar popping up with an icon next to the input field upon which they can click if they would like to choose a date visually. I have had problems with a few datetimepickers with no responses on this platform as to how I might resolve those issues. I first tried the Django wrapper for Tempus Dominus (django tempus dominus) which seemed the most logical choice, but it does not play well if you are using Django Crispy Forms layouts to render the forms. When the input is converted to a datetimepicker widget with a clickable calendar icon, the layout is thrown off as the input field's container gains extra height without any detectable CSS margins, padding, etc. It also forces the field to be required when it should not. Also, if the server side validation returns an error, the error text is disabled (changes css of the text element to display:none) although … -
I can't save changes to entry after clicking 'edit entry' button in Django
I have a problem with editing entry in Django. After changing the text it can't be saved and get redirected to Entries page. Picture down below:[Image of editing entry][1] [1]: https://i.stack.imgur.com/kZ9Gv.png Here's the code for edit_entry: from django.shortcuts import render, redirect from .models import Topic, Entry from .forms import TopicForm, EntryForm def edit_entry(request, entry_id): entry = Entry.objects.get(id=entry_id) topic = entry.topic_id if request != 'POST': form = EntryForm(instance=entry) else: form = EntryForm(instance=entry, data=request.POST) if form.is_valid(): form.save() return redirect('learning_logs:topic', topic_id=topic.id) context = { 'entry':entry, 'topic':topic, 'form':form } return render(request, 'learning_logs/edit_entry.html', context) -
Can I add tags inside articles in Django?
Can I add tags inside articles in Django? for example i want add article about pubg so i want add tag called pubg and when user click on this tag it will show all articles with same tag i mean pubg tag is there way to do that -
'Slide' object has no attribute 'topicdetail_set'
I created a model for Slide on django. below is model.py class Slide(models.Model): user = models.ForeignKey(User, on_delete=models.DO_NOTHING, blank=True) text = models.CharField(max_length=300) is_deleted = models.BooleanField(default=False) topic_id = models.ForeignKey(Article, on_delete=models.DO_NOTHING) created_at = models.DateTimeField("created at", auto_now_add=True) objects = models.Manager() def __str__(self): return self.text serializer.py class SlideSerializer(serializers.ModelSerializer): topicdetail_set = ArticleDetailSerial(many=True) user_detail = FindOwnerSerializer(source='user', read_only=True) author = AuthorSerializer(many=True) class Meta: model = Slide fields = ('id','text', 'created_at', 'topicdetail_set', 'user_detail','author') When I run the url for slide http://127.0.0.1:8000/article/slide/ then I got below error AttributeError: Got AttributeError when attempting to get a value for field `topicdetail_set` on serializer `SlideSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Slide` instance. Original exception text was: 'Slide' object has no attribute 'topicdetail_set'. Now I am confused, Is the code that I have created is wrong? And if it is wrong then how should I fix it? -
How to share Python method between two Django classes?
I have two classes in my Django models.py file: class ProfileManager(models.Manager): def create_profile(self, user, member): # Set default age to 100 years old when profile is created. years_ago100 = datetime.datetime.now() - datetime.timedelta(days=101 * 365) age = calculate_age(years_ago100) # <- Used here profile = self.create(user=user, person_dob=years_ago100, person_age=age) return class Profile(models.Model): person_dob = models.DateField() person_age = models.IntegerField() objects = ProfileManager() def save(self, *args, **kwargs): # Update to real age when user edits profile for the first time. self.person_age = calculate_age(self.person_dob) # <- Used here too super(Profile, self).save(*args, **kwargs) Each class uses this calculate_age method: def calculate_age(born): today = datetime.date.today() return (today.year - born.year - ((today.month, today.day) < (born.month, born.day))) How can I make this method accessible to both classes? One easy way would be to make the method global like this but that seems like a kludgy way to do it: def calculate_age(born): ... class ProfileManager(models.Manager): ... class Profile(models.Model): ... Also, this wouldn't work if I wanted to access that method outside of this particular models module. Is there a standard way to do this when using Django?