Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Hierarchical relation between 3 models. Post references a Goal and Goal references a Category
So I'm trying to think of how to organize this weird relation I have. So posts are always associated with a goal, they can't not be associated with a goal. This of it like this so if your goal is to "lose weight" then your post can be an update like "ate a salad today!" So all posts must reference a goal in this way, then each goal type can have a category type. For example, 'weight loss' goal is of type 'health & fitness' category. I need to be able to query all posts related to a category quickly as well as all posts related to a goal. I have 2 ways of doing this Method 1: class GoalAndPostCategory(AbstractBaseModel): category = models.ForeignKey(Category, on_delete=models.CASCADE) goal_id = models.ForeignKey(Goal, on_delete=models.CASCADE) post_id = models.OneToOneField(Post, on_delete=models.CASCADE) Create a table where each row is just the category, goal and post, but this doesn't ensure that let's say goal 1 with post id 1 is the same category as goal 1 with post id 2. Since they're separate rows there's the possibility of inconsistency (Not sure how big of a deal this is). Method 2: class Goal(AbstractBaseModel): creator_id = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, related_name="goal_creator_id") end_date = … -
Django oauth2 using email instead of username
authorization: from rest_framework_simplejwt.serializers import TokenObtainPairSerializer from rest_framework_simplejwt.views import TokenObtainPairView class MyTokenObtainPairSerializer(TokenObtainPairSerializer): @classmethod def get_token(cls, user): token = super().get_token(user) token['email'] = user.email return token class MyTokenObtainPairView(TokenObtainPairView): serializer_class = MyTokenObtainPairSerializer urls: from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings from rest_framework_simplejwt.views import TokenRefreshView from api.authorization import MyTokenObtainPairView urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('api.urls')), path('api/token/', MyTokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), ] + static( settings.MEDIA_URL, document_root=settings.MEDIA_ROOT ) Im getting "username": ["This field is required"] when i try to post my info im using email and password. Ive seen someone use authorization so i tryed it but it didnt seem to work. Idk where i messed up in there. { "email": "aleksa@gmail.com", "password": "Admin!123" } -
DRF Django: How to modify a value before saving
class Pet(models.Model): date_of_birth = models.DateField() class PetSerializer(serializers.ModelSerializer): class Meta: model = Pet fields = "__all__" Now when i trying to do curl -X POST -H "Content-Type: application/json" \ -d '{ "date_of_birth":"2021-08-29T00:46:27.103Z" }' http://localhost:8025/api/dob/ I get {"date_of_birth":["Date has wrong format. Use one of these formats instead: YYYY-MM-DD."]} How to manage this because i will get input as 2021-08-29T00:46:27.103Z format only -
Django Adding Material
I am making a site to help me calculate the costs of my craft projects. class Supply(models.Model): name = CharField(max_length = 200, null = True, blank = True) type = ForeignKey(SupplyType, null = True, blank = True, on_delete = models.CASCADE) vendor = ForeignKey(Vendor, null = True, blank = True, on_delete = models.CASCADE) width = FloatField(null = True, blank = True) length = FloatField(null = True, blank = True) thickness = FloatField(null = True, blank = True) amount = FloatField(null = True, blank = True) cost = FloatField(null = True, blank = True) @property def square_inches(self): try: return round(self.width * self.length, 2) except: return "N/A" @property def cubic_inches(self): try: return round(self.width * self.length * self.thickness, 2) except: return "N/A" @property def cost_per_square_inch(self): try: return round(self.cost / self.square_inches, 2) except: return "N/A" @property def cost_per_cubic_inch(self): try: return round(self.cost / self.cubic_inches, 2) except: return "N/A" @property def cost_per_each(self): try: return round(self.cost / self.amount, 2) except: return "N/A" class Meta: verbose_name_plural = "Supplies" def __str__(self): return f"{self.vendor}-{self.name}" class ProductType(models.Model): name = CharField(max_length = 200, null = True, blank = True) def __str__(self): return self.name class Product(models.Model): name = CharField(max_length = 200, null = True, blank = True) product_type = ForeignKey(ProductType, null = True, blank … -
loading dump.json file to a new postgres database from django
I'm switching from the default sqlite3 database to the PostgreSQL database but I'm getting an DETAIL: Key (slug)=(superadmin) already exists. error the steps i did: py manage.py dumpdata --exclude contenttypes --exclude auth.permission --exclude sessions --indent 2 > dump.json python manage.py flush change database settings to postgres py manage.py migrate python manage.py load data dump.json now I have an empty sqlite3 database and i cant load the data to my Postgres database :( -
Recreate Django table without affecting the frontend experience
Every month, I need to delete all data in a table and refill that table with new data. Since the frontend fetches and display data from the said table through a serializer, users might experience a crash when the old data is deleted but the new data hasn't written in. So, to not disrupt users' experience, I'm thinking about the following procedure: Clone the existing table Write new data to the new table Rename the new table to match the Django model name Delete the old table I was wondering if there's any Django built-in method to achieve this? The cloned table must match everything defined in the model so that upon deleting the old table, the frontend would continue working smoothly. -
Django - UpdateView changes are not saved, success_url is not used
I think I have a pretty basic UpdateView but the object is not saved when I submit the form. The success_url is never called. When I click the Update button, the form refreshes and I stay on the same page. I am able to update the object via admin, so I believe the model is working fine. I am not getting any errors. urls path('classroomdetail/<uuid:classroom_id>/', views.classroomdetail, name='classroomdetail'), path('classedit/<uuid:pk>/', views.ClassroomUpdateView.as_view(), name='classupdate'), Model class Classroom(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) classroom_name = models.CharField(max_length=20) course = models.ForeignKey(Course, on_delete=models.CASCADE) students = models.ManyToManyField(Student) class Meta: constraints = [models.UniqueConstraint( fields=['user', 'classroom_name'], name="unique-user-classroom")] def __str__(self): return self.classroom_name views class ClassroomUpdateView(UpdateView): model = Classroom fields = ['classroom_name'] template_name_suffix = '_update' success_url = reverse_lazy('gradebook:classroom') template {% extends 'base.html' %} {% load static %} {% block content %} {% load crispy_forms_tags %} <div class="container"> <div class="row"> <div class="col"> <h3>This Classroom belongs to {{ classroom.course }}</h3> </div> </div> <div class="row"> <div class="col-md-3"> <form class="form-group"> {% csrf_token %}{{ form|crispy }} <input type="submit" class="btn btn-primary mt-2 mb-2" value="Update"> </form> </div> </div> <div class="row"> <div class="col-md-3"> <a href="{% url 'gradebook:classroomdetail' object.pk %}"><div class="ps-2">Cancel</a> </div> </div> </div> {% endblock content %} -
How to handle multiple ClientId s for single social auth provider
I am trying to implement social auth for my backend that will serve mobile apps on different platforms (IOS, Android). I am using django-allauth.socialaccounts to accomplish the task. The problem is that for ex Google requires to have an OAuth client ID per each platform. That said I cannot create multiple social apps with the same provider because I am starting to get MultipleInstancesReturned error. I am thinking about attaching different Site instances to the applications, but not sure if sites framework is good for distinguishing mobile platforms. The resulting question is pretty simple - how to implement social login having more than 1 client id for provider? -
How I can access a url path from root project to use in templates
I have two apps books, users, and main app(config) which contains settings of the project. I have configured my urls.py in config as follows: urlpatterns = [ path('', TemplateView.as_view(template_name='index.html'), name='home'), path('admin/', admin.site.urls), path('books/', include('books.urls')), path('account/', include('users.urls')), ] and I want to access home path in base.html templated like this: <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link" href="{% url 'home' %}">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'books:list' %}">My books</a> </li> </ul> but it throws this error: NoReverseMatch at / 'home' is not a registered namespace Request Method: GET Request URL: http://localhost:8000/ Django Version: 3.1.5 Exception Type: NoReverseMatch Exception Value: 'home' is not a registered namespace Exception Location: /home/shoukrey/.local/share/virtualenvs/pdfstack-J-DuXMon/lib/python3.9/site-packages/django/urls/base.py, line 83, in reverse Python Executable: /home/shoukrey/.local/share/virtualenvs/pdfstack-J-DuXMon/bin/python Python Version: 3.9.2 Python Path: ['/mnt/sda4/My-Projects/real-world/pdfstack', '/usr/lib/python39.zip', '/usr/lib/python3.9', '/usr/lib/python3.9/lib-dynload', '/home/shoukrey/.local/share/virtualenvs/pdfstack-J-DuXMon/lib/python3.9/site-packages'] Server time: Sun, 29 Aug 2021 01:28:02 +0000 -
Django Advanced Model
I have 2 models. In 1 of them, I want to withdraw general information, and in another - advanced information. I want the models to combine the service_id field. In model AdvancedService i have 2 objects with one service_id. In the Service model, when I click on the service_id, I want view 2 objects that such an service_id. However, I do not understand how it can be done. My code: #models.py class ServiceModel(models.Model): service_id = models.CharField(max_length=150) total_cars = models.PositiveIntegerField() # bmw + audi repaired = models.PositiveIntegerField() # broken_motor + broken_body advanced = models.ForeignKey( 'AdvancedServiceModel', on_delete=models.CASCADE) class AdvancedServiceModel(models.Model): service_id = models.CharField(max_length=150) bmw = models.PositiveIntegerField() audi = models.PositiveIntegerField() broken_motor = models.PositiveIntegerField() broken_body = models.PositiveIntegerField() def __str__(self) -> str: return f'{self.service_id}' #admin.py from django.contrib import admin from .models import ServiceModel, AdvancedServiceModel from django.urls import reverse from django.utils.html import escape, mark_safe @admin.register(ServiceModel) class ServiceModelAdmin(admin.ModelAdmin): list_display = ['advanced_link', 'total_cars', 'repaired'] def advanced_link(self, obj: AdvancedServiceModel): link = reverse("admin:tasks_advancedservicemodel_changelist") return mark_safe(f'<a href="{link}">{escape(obj.advanced.__str__())}</a>') advanced_link.short_description = 'Service id' advanced_link.admin_order_field = 'service_id' # Make row sortable @admin.register(AdvancedServiceModel) class AdvancedServiceModelAdmin(admin.ModelAdmin): list_display = ['service_id', 'bmw', 'audi', 'broken_motor', 'broken_body'] -
DRF MultiPartParser returns value as list
I am trying to create an API endpoint. Here I am using MultiPart/form-data content-type to cater multiple input types. But I am stuck in MultiPartParser. my view function declaration is something like this: @api_view(['GET','POST','PUT']) @parser_classes([MultiPartParser,JSONParser]) def item_view(request): The MultiPartParser is parsing this: <QueryDict: {'code': ['3'], 'gst_rate': ['5']}> <MultiValueDict: {}> What I want: <QueryDict: {'code':3, 'gst_rate':5}> <MultiValueDict: {}> How can I do that? -
How to save uploaded file and edited file in django?
I want to user to upload file, and then I want to save that file (that part is working), then I want to calculate data in this document and export it in results.html. Problem is this, I already used return function for user to download document (with done calculations). How to additionally save edited file, and forward to user to download and see data? def my_view(request): print(f"Great! You're using Python 3.6+. If you fail here, use the right version.") message = 'Upload as many files as you want!' if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Document(docfile=request.FILES['docfile']) newdoc.save() #This part is doing calculations for uploaded file dfs = pd.read_excel(newdoc, sheet_name=None) with pd.ExcelWriter('output_' + newdoc + 'xlsx') as writer: for name, df in dfs.items(): print(name) data = df.eval('d = column1 / column2') output = data.eval('e = column1 / d') output.to_excel(writer, sheet_name=name) return redirect('results') else: message = 'The form is not valid. Fix the following error:' else: form = DocumentForm() documents = Document.objects.all() context = {'documents': documents, 'form': form, 'message': message} return render(request, 'list.html', context) -
Django save an image to database
I have a site in Django that upload a photo and than it saves in a folther. After that the program make some processing in the image and save it to database. But it is giving an error: UnboundLocalError: local variable 'listing' referenced before assignment Part of Model: class Listing(models.Model): item = models.CharField(max_length=64) description = models.CharField(max_length=255, blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) category = models.CharField(max_length=1, choices=CATEGORIES, default=CATEGORIES[5][1]) time = models.DateTimeField(auto_now_add=True, blank=True) closed = models.BooleanField(default=False) owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="owners") bids = models.ManyToManyField(Bid, blank=True, related_name="bids") comments = models.ManyToManyField(Comment, blank=True, related_name="comments") image = models.ImageField(null=True, blank=True) restoredimage = models.BinaryField(blank=True) View: listing.restoredimage = None listing.restoredimage = cv2.imread(img_save_path) Sorry I new to Django I don´t know if I'm doing right. -
How to call a django function on click that doesn't involve changing page
I would like to have a simple task: When I click a button in the Template a function in the Views is called. I know I should make a url but I don't want the page to reload when the button is clicked I read something about AJAX/jQuery & I wonder if there is any alternatives that is limited to django and python? Thanks in advance, -
Im thinking of making a webapp with django, that's basically a wallpaper generator, but where to store and how to display an image on heroku?
Basically ill be using pillow to create random wallpapers, but ive never worked with images in django, so idk how am i supposed to display the generated image....because whilst hosting on heroku? i know that people store images on AWS and stuff, but how im supposed to do store an image generated from pillow to aws, automatically, or can u even do that? ps; im not demanding for any code, i just need to get an idea, a kind of a road map or maybe a tutorial if u may. -
How can I allow users to create their own posts in Django?
I am trying to build a discussion forum with Django. I first did a test post with Django admin, but now wanted to implement a form so that any user can post. The idea is that the home page of the forum has a list of all existing posts, and clicking on the "Create a Post" button would take them to the post form, and after submitting they can see their post on the list. I have the code for the form ready and thought I had hooked it up correctly to the URL, but I am getting a blank page when I click on "Create a Post". I am new to Django, and need some help solving this. Here are my files: Models.py: class Category(models.Model): name = models.CharField(max_length=20) class Post(models.Model): title = models.CharField(max_length=255) author = models.CharField(max_length=60, default= 'None') body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(auto_now=True) categories = models.ManyToManyField('Category', related_name='posts') class Comment(models.Model): author = models.CharField(max_length=60) body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) post = models.ForeignKey('Post', on_delete=models.CASCADE) Forms.py: class CommentForm(forms.Form): author = forms.CharField( max_length=60, widget=forms.TextInput(attrs={ "class": "form-control", "placeholder": "Your Name" }) ) body = forms.CharField(widget=forms.Textarea( attrs={ "class": "form-control", "placeholder": "Leave a comment!" }) ) class PostForm(forms.Form): title = forms.CharField( max_length=255, … -
Logging of hard errors (eg. 500) not working
I've got the following in my settings, yet, 500 errors aren't being written to my djangoerrors file. I've confirmed that the file exists in this directory (I created it myself and the permissions are set to 777). LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'ERROR', 'class': 'logging.FileHandler', 'filename': '/opt/python/log/djangoerrors.log' }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'ERROR', 'propagate': True, }, }, } Any thoughts on why errors are not being written to this file? thanks! -
Django - forloop in model.py to assign foreignkey
I have two models - User and Rank. During def save() I want the Users Rank automatically assigned to a Rank depending on the points the user has and the min_points from the Rank model. Models class User(AbstractUser): points = models.IntegerField(default=0) rank = models.ForeignKey(Rank, on_delete=models.SET_NULL, null=True, blank=True) class Rank(models.Model): rank = models.CharField(max_length=200) min_points = models.IntegerField() Now I added save() function to User model to check the user points and compare to the correct Rank # ...user model def save(self, *args, **kwargs): for i in Rank.objects.all(): if self.points >= i.min_points: self.rank == Rank.objects.get(id=i.id) super().save(*args, **kwargs) Unfortunally nothing happend after saving or creating a new user. My IDE throw warning: Unresolved attribute reference 'objects' for class 'Rank' Do I miss something? I cant figure out the issue... -
How can I create a URL-Shortener using Django based on the URL id?
I am working with Django and I am just a beginner. Now I am trying to make a URL shortener with Base 62 so I have created one class in models.py and its name is URLGenerator. Here is its code: class URLGenerator: BASE = 62 UPPERCASE_OFFSET = 55 LOWERCASE_OFFSET = 61 DIGIT_OFFSET = 48 def generate_unique_key(self, integer): """ Turn an integer [integer] into a base [BASE] number in string representation """ # we won't step into the while if integer is 0 # so we just solve for that case here if integer == 0: return '0' string = "" remainder: int = 0 while integer > 0: remainder = integer % self.BASE string = self._true_chr(remainder) + string integer = int(integer / self.BASE) return string def get_id(self, key): """ Turn the base [BASE] number [key] into an integer """ int_sum = 0 reversed_key = key[::-1] for idx, char in enumerate(reversed_key): int_sum += self._true_ord(char) * int(math.pow(self.BASE, idx)) return int_sum def _true_ord(self, char): """ Turns a digit [char] in character representation from the number system with base [BASE] into an integer. """ if char.isdigit(): return ord(char) - self.DIGIT_OFFSET elif 'A' <= char <= 'Z': return ord(char) - self.UPPERCASE_OFFSET elif 'a' <= char … -
Django sends empty PDF in attachment
I am kind of newbee and I am sitting with this issue for couple months now. I need to autogenerate PDF and attach it to email sent by django. All emails are sent comes with attached PDF, but the PDF is empty, no info in the file, but I see the file with info when it generates... Here is my views.py class SendPDFView(LoginRequiredMixin, View): def get(self, request, *args, **kwargs): pk = kwargs.get('pk') report = get_object_or_404(Report, pk=pk) template_path = 'pcreport/table_pdf.html' context = {'report': report} response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = f'filename="{report.flight}-{report.date}.pdf"' buffer = BytesIO() template = get_template(template_path) html = template.render(context) pisa_status = pisa.CreatePDF(html, dest=response) if pisa_status.err: return HttpResponse('Error creating <pre>' + html + '</pre>') pdf = buffer.getvalue() buffer.close() msg = EmailMessage("Subjest", "Body", "handlr.arn@gmail.com", ["handlr.arn@gmail.com"]) msg.attach(f'{report.flight}-{report.date}.pdf"', pdf, 'application/pdf') msg.send() return response -
error 'NoneType' object has no attribute 'is_absolute' while using mongodb
Exception Type: AttributeError Exception Value: 'NoneType' object has no attribute 'is_absolute' Exception Location: C:\Users\A\IPFinder\venv\lib\site-packages\dns\resolver.py, line 1006, in _get_qnames_to_try Python Executable: C:\Users\A\IPFinder\venv\Scripts\python.exe while uploading file the submit button should save file but it is showing while running action_page.py the code is showing error 'NoneType' object has no attribute 'is_absolute' action_page.py import cgi import os import cgitb; cgitb.enable() form = cgi.FieldStorage() fileitem = form['filename'] if fileitem.filename: fn = os.path.basename(fileitem.filename) open(fn, 'wb').write(fileitem.file.read()) this is my index.html {% extends 'base.html' %} {% block title %} IP Finder {% endblock %} {% block body %} <div class="container"> <br> <br> <center> <h1 style="font-family:'Courier New'">Django NSLookup</h1> <br> <br> <form action="{% url 'index' %}" method="post"> {% csrf_token %} <div class="form-group"> <label> <input type="text" class="form-control" name="search" placeholder="Enter website"> </label> </div> <input type="submit" class="btn btn-primary" value="Search"> <p></p> <p>Click on the "Choose File" button to upload a file:</p> <form enctype = "multipart/form-data" action="action_page.py" method="get"> <input type="file" id="myFile" name="filename"> <input type="submit" value="upload"> </form> </form> </center> <br> <br> <p>IP Address is : {{ip_address}}</p> </div> {% endblock %} views.py import dns.resolver def Index(request): search = request.POST.get('search') my_resolver = dns.resolver.Resolver() ip_address = my_resolver.resolve(search, "A") for i in ip_address: context = {"ip_address": i.to_text()} # print(ip_address) return render(request, 'index.html', context) -
Save Calculated Value from View to Model in Django
I have a Django application that gives the user an option to save a calculation or not within the form. If the user says they want to save the calculation, I would like to save the calculation result in the database too along with the input details. For the user input I am already able to save it. The challenge comes when saving the calculated results which are being handled by the views.py. My code is below: for my views.py def coordinate_transform(request): if request.method == 'POST': form = CoordinateForm(request.POST) if form.is_valid(): from_epsg = request.POST.get('from_epsg') y = request.POST.get('y') x = request.POST.get('x') to_epsg = request.POST.get('to_epsg') # Transform Coordinates transformer = Transformer.from_crs(int(from_epsg), int(to_epsg)) transformed = transformer.transform(y, x) # Save to Database? save_data = request.POST.get('saved') if save_data == 'on': form.save() messages.success(request, "Coordinate Transormation data stored") context = { 'form': form, 'y': transformed[0], 'x': transformed[1], } return render(request, 'utility/coordinate_transform.html', context) else: form = CoordinateForm() context = { 'form': form, } return render(request, 'utility/coordinate_transform.html', context) In the above code, form.save() is working fine but the calculation is not being saved. I tried using the Django Querysets to save the model and its not working. Here is my model.py class CoordinateTransform(models.Model): from_epsg = models.ForeignKey(CRS, on_delete=models.CASCADE, related_name='from_epsg') x … -
How Can I change this def into class in django views?
How Can I change this def into class in django views? app/views.py: def vote(request, slug): question = get_object_or_404(Question, slug=slug) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): return render(request, 'polls/detail.html', { 'question': question, 'error_message': "Nie wybrałeś żadnej opcji.", }) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('polls:results', args=(question.slug,))) -
Django doesn't clean() the formset
I have three models: class Order(models.Model): ... class Job(models.Model): ... class Item(models.Model): // Creates a record of a job for the order order = models.ForeignKey( Order, on_delete=models.CASCADE, blank=True, ) job = models.ForeignKey( Job, on_delete=models.CASCADE, ) I am using a modified UpdateView to update the Order: def get_job_forms(order, data=None): "" Takes order instance and creates a formset for it from Items"" JobModelFormset = modelformset_factory( Item, form=ItemForm, fields='__all__', formset=BaseModelFormSet, ) qs = order.item_set.all() return JobModelFormset(data, queryset=qs) class ObjectView(UpdateView): "" CreateView if called with is_create=True, else UpdateView"" is_create = False def get_object(self, queryset=None): try: return super().get_object(queryset) except AttributeError: return None class OrderUpdateView(WriteCheckMixin, ObjectView): model = Order form_class = OrderForm def form_valid(self, form): self.object = form.save() if not self.is_create: formset = get_job_forms(self.object, self.request.POST) if formset.is_valid(): for f in formset: inst = f.save(commit=False) inst.order = self.object inst.save() else: return self.render_to_response( self.get_context_data(form=form, formset=formset)) return redirect(self.object.get_absolute_url()) def get_context_data(self, *args, formset=None, **kwargs): context = super().get_context_data(*args, **kwargs) order = self.get_object() context['formset'] = formset if formset else get_job_forms(order) return context When I call UpdateView it renders the template with one empty formset, like you would expect it. But if I call POST on the formset, formset.is_valid() returns True even if all the fields are empty. If I allow null values … -
What is the diffrence between django apps and django contenttype?
What is the diffrence between django apps and django contenttype in getting models for example from django.apps import apps model = apps.get_model(app_label=app_label,model_name=model_name) and from django.contrib.contenttypes.models import ContentType model = ContentType.objects.get(app_label=app_label, model = model).model_class()