Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to correct set generic relation?
class A(models.Model): relation = GenericRelation('B') another_relation = GenericRelation('B') class B(models.Model): content_type = models.ForeignKey(ContentType, blank=True, null=True) object_id = models.PositiveIntegerField(blank=True, null=True) content = GenericForeignKey('content_type', 'object_id') a = A() b = B() How to set connection so that I get b as result of a.another_relation.all()? -
Django Channels Chat Application with Angular Frontend
What is the best way integrated Django channel with latest angular frontend? I need to build a private chat app where user able to send a message and attached image to another user. Messages will contain in inbox and user inbox will show with user image thumbnail text area and last timestamp. Will I send each data with routing.py or I will use URLs.py also? Thanks. -
InterfaceError: Error binding Parameter 5...Django JWT token (django request token tool)
I am trying to set up a "one time use" link creating system with this tool: https://github.com/yunojuno/django-request-token I have followed the instructions on the installation and implementation. Now the implementation says that I should create a Requesttoken in the admin interface or with some other method. When I go to the admin interface and when I go to add the token, I fill out the scope field which is the only one required and click save. This is where I get the InterfaceError:r: Error binding Parameter 5 - probably unsupported type And the error seems to happen at this line of code: super(RequestToken, self).save(*args, **kwargs) Now I will include the models.py file: https://github.com/yunojuno/django-request-token/blob/master/request_token/models.py This is the file which contains the line of code which is causing the error. I am really stuck on this and I hope someone will know how to fix it. If you dont know how to fix the problem maybe you know some tool which does a simillar thing as this one. Thanks in advance -
Django RF docs displaying input fields for POST/PUT requests
I am using DRF Docs (http://drfdocs.com/) to test my API built with Django RF. I have a following URL: url(r'^libraries/$', library_list), And corresponding view: # Get all libraries and create a library @api_view(['GET', 'POST']) def library_list(request): """ List all libraries, or create a new library for a specific user """ if request.method == 'GET': libraries = Library.objects.filter() serializer = LibrarySerializer(libraries, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = LibrarianSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response( serializer.errors, status=status.HTTP_400_BAD_REQUEST) Model: class Library(models.Model): library_id = models.AutoField(primary_key=True) name = models.CharField(max_length=30) city = models.CharField(max_length=30) address = models.CharField(max_length=80) phone = models.CharField(max_length=30, blank=True, null=True) website = models.CharField(max_length=60, blank=True, null=True) #This helps to print in admin interface def __str__(self): return u"%s" % (self.name) Serializer: class LibrarySerializer(serializers.ModelSerializer): class Meta: model = Library fields = '__all__' See following image: What exactly am I missing to add (to the view/models/serializer) that the form to POST data is missing? -
error: 'projectname' appears as both a file and as a directory
I have a Django project that I am trying to push (from git repo to server) name of the project is: projectname the account name is gitlab.com/projectname/django I am getting this error when I try to push: error: 'projectname' appears as both a file and as a directory enter code here`error: projectname: cannot drop to stage #0 enter code here`error: Pull is not possible because you have unmerged files. hint: Fix them up in the work tree, and then use 'git add/rm <file>' hint: as appropriate to mark resolution and make a commit. fatal: Exiting because of an unresolved conflict. -
Unable to import view from different app
I'm trying to import a view from one app into another app but it's giving me this error: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/trie/Desktop/django/venv/lib/python3.5/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/trie/Desktop/django/venv/lib/python3.5/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/trie/Desktop/django/venv/lib/python3.5/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/home/trie/Desktop/django/venv/lib/python3.5/site-packages/django/core/management/base.py", line 332, in execute self.check() File "/home/trie/Desktop/django/venv/lib/python3.5/site-packages/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/home/trie/Desktop/django/venv/lib/python3.5/site-packages/django/core/management/base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "/home/trie/Desktop/django/venv/lib/python3.5/site-packages/django/core/checks/registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "/home/trie/Desktop/django/venv/lib/python3.5/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/home/trie/Desktop/django/venv/lib/python3.5/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/home/trie/Desktop/django/venv/lib/python3.5/site-packages/django/urls/resolvers.py", line 397, in check for pattern in self.url_patterns: File "/home/trie/Desktop/django/venv/lib/python3.5/site-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/trie/Desktop/django/venv/lib/python3.5/site-packages/django/urls/resolvers.py", line 536, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/trie/Desktop/django/venv/lib/python3.5/site-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/trie/Desktop/django/venv/lib/python3.5/site-packages/django/urls/resolvers.py", line 529, in urlconf_module return import_module(self.urlconf_name) File "/home/trie/Desktop/django/venv/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 673, in exec_module File "<frozen importlib._bootstrap>", line 222, … -
Getting this error in django "login() missing 1 required positional argument: 'user' "
I am a new Django user and I just created a registration and login system for my website in Django 1.11. I am struck when I go to login section of my website. I get the error as mentioned "login() missing 1 required positional argument: 'user'" and I can't figure out what's wrong with the login function and the variable 'user'. Kindly help me. Thanks in advance. Here is my code: urls.py: from django.conf.urls import url from . import views from django.contrib.auth import login app_name='one' urlpatterns = [ url(r'^games$',views.games,name='games'), url(r'^others$',views.others,name='others'), url(r'^about$',views.about,name='about'), url(r'^upload$',views.UploadFile.as_view(),name='upload'), url(r'^register$',views.UserFormView.as_view(),name='register'), url(r'^login/$', login, name='login'), ] views.py: from django.shortcuts import render,redirect from django.contrib.auth import authenticate, login from django.views.generic.edit import CreateView from .models import file from django.views.generic import View from .forms import user_form class UserFormView(View): form_class = user_form template_name = 'one/register_form.html' def get (self,request): form = self.form_class(None) return render(request,self.template_name,{'form':form}) def post (self,request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit = False) username= form.cleaned_data['username'] password= form.cleaned_data['password'] user.set_password(password) user.save() user= authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) redirect('one:profile') return render(request,self.template_name,{'form':form}) -
Django Admin - Sending full QuerySet data in template POST
I'm trying to display a bunch of values from a queryset, have the user select some, and then click submit so I can process those values. However, despite the view on the admin page showing the full data, in the request.POST, I only get the key, and not the value. Concretely: My form field: class ResponseListForm(django.forms.Form): responses = django.forms.ModelMultipleChoiceField( queryset=qs, label="Responses to pick from", help_text="List of completed and deleted responses for the selected project", widget=django.forms.CheckboxSelectMultiple) where qs = Response.objects.filter(project_id=proj_id).values("response_id") In the admin page view, I see: {'response_id': 'id_string'} which is great but when I click submit and check the request body, I only see the response_id and not the id itself: (pdb) request.POST <QueryDict: {'responses': ["['response_id']"]}> Any idea what I'm doing wrong? How can I pass the whole value into the request. Many thanks! -
How To register signals in django?
I am developing a Django app 1.11 i want to email should send after user registration, so I decide to use signals for send email, now when i trying to connect/register the signal with appropriate modal by ready in application configuration class. but I am getting error like follow django.core.exceptions.ImproperlyConfigured: Cannot import 'common'. Check that 'apps.common.apps.CommonConfig.name' is correct. My project folder Structure Looks like /myproject /myproject /apps /common /configs /settings /static /templates Installed Apps Looks Like Follow INSTALLED_APPS = [ 'django.contrib.messages', 'django.contrib.staticfiles', 'storages', 'rest_framework', 'apps.common.apps.CommonConfig',] and my apps\common\apps.py looks like follow ` from django.apps import AppConfig class CommonConfig(AppConfig): name = "common" ` What Mistake i made here, how to register the signal with django? -
django UserProfile and RegistrationProfile : Same model or different
So i am making a website which requires me to register a user and ask for their email and username and verify the email.After that i ask them to fill a Profile form with information such as name,age,sex,image etc. So should i go about creating seperate models for UserProfile and RegistrationProfile or make it in same model -
django-background-tasks BACKGROUND_TASK_RUN_ASYNC isn't working?
I use django-background-tasks with my Django project, the tasks check on certain files with sleep and take action as a file appears. Everything is working fine but I want the tasks to be executed asynchronously so that missing one file will not lock up everything else, so I went into setting.py to add BACKGROUND_TASK_RUN_ASYNC = True Looks like django-background-tasks just stop executing any task. Once I set: BACKGROUND_TASK_RUN_ASYNC = False it starts executing, synchronously... What am I missing? Thank you. -
Django ImproperlyConfigured: WSGI application 'myproject.wsgi.application' could not be loaded; Error importing module
I have an almost fresh install of django and it is is giving me this error: ImproperlyConfigured: WSGI application 'myproject.wsgi.application' could not be loaded; Error importing module. When I try to python manage.py runserver. settings.py WSGI_APPLICATION = 'myproject.wsgi.appli wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings") application = get_wsgi_application() -
Django - AttributeError: Manager isn't accessible via ManagerLog instances
Soy nuevo en python, actualmente estoy desarrollando una aplicación, la cual se encarga de generar varios reportes muy sencillos, sin embargo hay un reporte el cual no he podido resolver aun, he investigado pero aun no consigo la solución. Básicamente lo que quiero realizar es la siguiente consulta SQL a través del ORM: select log.* from file_managerfiles as file, log_managerlog as log where log.fileLog_id = file.id and file.lastUpload = TRUE los modelos son los siguientes: class ManagerFiles(models.Model): filesUpload = models.FileField(upload_to='log', unique=True) processingStatus = models.BooleanField(default=False) lastUpload = models.BooleanField(default=True) class ManagerLog(models.Model): date = models.CharField(max_length=10) time = models.CharField(max_length=30) serialNumber = models.CharField(max_length=30) sessionID = models.CharField(max_length=50) moduleName = models.CharField(max_length=50) operationName = models.CharField(max_length=100) operationSpecific = models.TextField(max_length=500) fileLog = models.ForeignKey(ManagerFiles) Dentro del ultimo modelo (ManagerLog) cree un método que retorna todos los registros del modelo ManagerLog donde ManagerFile.lastUpload sea igual a TRUE: # Report Last Upload File def report_last_upload(self): return self.__class__.objects.filter(ManagerFiles__lastUpload=True) Sin embargo al llamar este metedo (report_last_upload) en mi vista, obtengo el siguiente error: raise AttributeError("Manager isn't accessible via %s instances" % cls.__name__) AttributeError: Manager isn't accessible via ManagerLog instances No entiendo cual es el problema, espero me puedan ayudar, y de antemano gracias. -
regular expression in django blogs.html file error
Can anyone trouble shoot the error in the following code: Code: (in the blog.html file, that is in the blog app) 1 {% extends "aboutme/header.html" %} 2 3 {%block content %} 4 {% for post in object_list %} 5 <h5>{{post.date|date:Y-m-d"}}<a href="/blog/{{post.id}}">{{post.title}}</a></h5> 6 {% end for %} 7 {% endblock %} Error on running: http://127.0.0.1:8000/blog/ TemplateSyntaxError at /blog/ Could not parse the remainder: '-m-d"' from 'post.date|date:Y-m-d"' Request Method: GET Request URL: http://127.0.0.1:8000/blog/ Django Version: 2.0 Exception Type: TemplateSyntaxError Exception Value: Could not parse the remainder: '-m-d"' from 'post.date|date:Y-m-d"' Exception Location: C:\Python34\lib\site-packages\django\template\base.py in __init__, line 668 Python Executable: C:\Python34\python.exe Python Version: 3.4.3 Python Path: ['C:\\Users\\User\\Desktop\\pythonsite\\mysite', 'C:\\windows\\SYSTEM32\\python34.zip', 'C:\\Python34\\DLLs', 'C:\\Python34\\lib', 'C:\\Python34', 'C:\\Python34\\lib\\site-packages'] Server time: Wed, 13 Dec 2017 19:13:00 +0000 Error during template rendering In template C:\Users\User\Desktop\pythonsite\mysite\blog\templates\blog\blog.html, error at line 5 Could not parse the remainder: '-m-d"' from 'post.date|date:Y-m-d"' 1 {% extends "aboutme/header.html" %} 2 3 {%block content %} 4 {% for post in object_list %} 5 <h5>{{post.date|date:Y-m-d"}}<a href="/blog/{{post.id}}">{{post.title}}</a></h5> 6 {% end for %} 7 {% endblock %} -
Cannot save page with inline model inherited from a mixin
I created a reusable abstract model (mixin) which includes required fields (without blank=True). Then added to a page model inline model which inherits that mixin. Finally I cannot save a page despite I filled in all the required fields. My app crashes with a message those fields cannot be blank. When I eliminate required option everything works well. The same thing if I use this model obviously (as pure inline model, not a mixin) with required fields. What's wrong here? If my approach is quite complicated, what is a better way to reuse code in this case? Mixin: class ContentSectionOneMixin(models.Model): class Meta: abstract = True content_section_one_title = models.TextField(_('Title'), null=True) content_section_one_body = RichTextField(_('Lead'), null=True) content_section_button_caption = RichTextField( _('Caption'), null=True, blank=True ) content_panels = [ MultiFieldPanel( heading=_('Content Section One'), children=[ FieldPanel('content_section_one_title'), FieldPanel('content_section_one_body'), FieldPanel('content_section_button_caption'), ], classname='collapsible collapsed' ), ] Inline model class HomePageContentFlow(Orderable, ContentSectionOneMixin): page = ParentalKey('HomePage', related_name='content_flow') panels = ContentSectionOneMixin.content_panels -
(django) [Errno 11001] getaddrinfo failed
whats wrong with my code? in settings.py EMAIL_HOST = 'smtp.mail.********.info' EMAIL_HOST_USER = 'mail@*********.info' EMAIL_HOST_PASSWORD = '*********' EMAIL_PORT = 465 EMAIL_USE_TLS = True CORS_ORIGIN_ALLOW_ALL=True APPEND_SLASH= False in views.py send_mail('hello', 'pesanan.', 'noreply@server.info', ['arnoldfox21@gmail.com']) I get the following error message [Errno 11001] getaddrinfo failed -
How to make multiple join the Django query
I am new to Django platform. I have a situation where I need to show the data on a page where the table has multiple foreign key columns like status, Priority and task type.when I save the date it saves the ID from the Foreign key table like StatusTable, PriorityTable and TaskTypeTable.The save is working fine as expected.But when I retrieve the date from the table it's giving only the ID not the name. How can i achieve this in Django? Modle.py class StatusTable(models.Model): status = models.CharField(max_length=20,default='') def __str__(self): return self.status class PriorityTable(models.Model): priority = models.CharField(max_length=20,default='') def __str__(self): return self.priority class TeamTable(models.Model): team = models.CharField(max_length=20,default='') def __str__(self): return self.team class TaskTypeTable(models.Model): tasktype = models.CharField(max_length=30,default='') def __str__(self): return self.tasktype class DatacenterTable(models.Model): datacenter = models.CharField(max_length=10,default='') def __str__(self): return self.datacenter class TaskMaster(models.Model): sid = models.CharField(max_length=3) processor = models.ForeignKey(User,null=True) tasktype = models.ForeignKey(TaskTypeTable, null=True) task_title = models.TextField(null=True) task_description = models.TextField(null=True) datacenter = models.ForeignKey(DatacenterTable,null=True) priority = models.OneToOneField(PriorityTable, null=True) status = models.ForeignKey(StatusTable, null=True) pid = models.IntegerField(null=True) sourceincident = models.URLField(null=True) errorincident = models.URLField(null=True) processingteam = models.ForeignKey(TeamTable, null=True) createddate = models.DateField(("Date"), default=datetime.date.today) duedate = models.DateField(("Date"), default=datetime.date.today) istaskactive = models.BooleanField(default=True) forms.py class CreateTaskMaster(forms.Form): sid = forms.CharField(required=False,widget=forms.TextInput(attrs={'class': 'form-control mr-sm-2', 'placeholder': 'SID'})) tasktype_query = TaskTypeTable.objects.values_list('tasktype', flat=True).distinct() tasktype_query_choices = [('', 'Select TaskType')] + … -
Static File in HTML gets distorted when implemented in pythonanywhere server
Hello my question is about why the formatting language of my static file resource gets twisted when rendering. The thing that gets affected the most is spanish special characters like: 'ó' or 'ñ'. For instance: Indicadores de Gestión para Ciudad de México en el Mes de Noviembre 2017. Gets rendered like this: Indicadores de Gestión para Ciudad de México en el Mes de Noviembre 2017. I am using Django 1.11 and my app is hosted in pythonanywhere. Thank you. -
PyCharm does not support Django
I have PyCharm Community Edition 2017. I'm learning django. My PyCharm does not autocomplete django methods and in templates I dont have formatting. Why application for python does not support this ? Is this only for $$$ in PyCharm ?? -
Django formset rendering 3 formsets
I've made a formset that will update a model Client and a model ClientData,my problem is that instead of rendering a formset, it renders it 3 times and i can't identify why. views.py def client_data(request): data = dict() if request.method == "POST": form = ClientForm(request.POST) if form.is_valid(): client = form.save(commit=False) formset = ClientFormSet(request.POST, instance=client) if formset.is_valid(): client.save() formset.save() return redirect(reverse_lazy('core:index')) else: form = ClientForm() formset = ClientFormSet() data['form'] = form data['formset'] = formset return render(request, 'core/test.html', data) forms.py class ClientForm(ModelForm): class Meta: model = Client fields = '__all__' exclude = ['user', ] class ClientDataForm(ModelForm): class Meta: model = ClientData fields = '__all__' exclude = ['client', ] ClientFormSet = inlineformset_factory(Client, ClientData, fields=[ 'language', 'type', ]) template <form method="POST">{% csrf_token %} {{ form.as_p }} {{ formset }} <button type="submit" class="save btn btn-default">Save</button> </form> -
Get the change log for custom fields in Django admin
I have added two custom fields (Checkboxes) in a form under Django admin. These values are not fetching data from model, but I am fetching data from a micro service to show these checkboxes as checked/unchecked conditionally. Below is the sample code: class CustomFieldForm(ModelForm): first_custom_field = forms.BooleanField( label=_("First custom field"), widget=forms.CheckboxInput, required=False ) second_custom_field = forms.BooleanField( label=_("Second custom field"), widget=forms.CheckboxInput, required=False ) def __init__(self, *args, **kwargs): super(CustomFieldForm, self).__init__(*args, **kwargs) if self.instance and self.instance.user_id: if get_first_custom_field(self.instance.user.id): self.fields['first_custom_field'].widget.attrs['checked'] = 'checked' if get_second_custom_field(self.instance.user.id): self.fields['second_custom_field'].widget.attrs['checked'] = 'checked' Now the problem am facing is that every time, I call save_model method, and if these fields are checked, then these are logged in history every time although I haven't updated any of these. Here is the sample code for save_model def save_model(self, request, obj, form, change): super(ProfileAdmin, self).save_model(request, obj, form, change) update_custom_field(form.cleaned_data['first_custom_field'], obj.user) update_custom_field(form.cleaned_data['second_custom_field'], obj.user) After exploring the Django code, I came to know that Django form caches the initial field values and then compare these with submitted field values to know the change. But in my case, I am updating the form fields under __init__ method, based on data fetched from my micro service, so django form always caches my fields as unchecked. And every … -
How can I deploy multiple Python 2 and 3 Django projects on one apache server?
Problem: There is a similar question on StackOverflow: "Can I deploy both python 2 and 3 django app with apache using mod_wsgi?" From the answer there I know that it is possible two have multiple Django projects (written in Python 2 and 3) on one apache server. However, I can't manage to make this work. What I have so far: I'm using Linux (Debian/Ubuntu). Three Django projects are stored in three separate Python Virtual Environments (i.e. py3venv1, py3venv2, py2venv1): /var/www/ .........py3venv1/ <-- Python 3 venv ..................bin/ ..................include/ ..................lib/ ..................project1/ <-- Python 3 Django Project ........................../manage.py ........................../project1/wsgi.py ........................../myapp .........py3venv2/ <-- Python 3 venv ..................bin/ ..................include/ ..................lib/ ..................project2/ <-- Python 3 Django Project ........................../manage.py ........................../project2/wsgi.py ........................../myapp .........py2venv1/ <-- Python 2 venv ..................bin/ ..................include/ ..................lib/ ..................project3/ <-- Python 2 Django Project ........................../manage.py ........................../project3/wsgi.py ........................../myapp I installed mod_wsgi for Python3 (pip3 install mod_wsgi) Apache configuration: /etc/apache2/sites-available/000-default.conf for Projects 1 and 2 (Python3 only), Project 3 (Python 2) is not configured: <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined # Project 1 (Python3) WSGIScriptAlias /project1 /var/www/py3venv1/project1/project1/wsgi.py process-group=group1 WSGIDaemonProcess group1 python-home=/var/www/py3venv1/lib/python3.5 python-path=/var/www/py3venv1/project1 WSGIProcessGroup group1 <Directory /var/www/py3venv1/project1/project1> <Files wsgi.py> Require all granted </Files> </Directory> # Project 2 (Python3) WSGIScriptAlias /project2 /var/www/py3venv2/project2/project2/wsgi.py process-group=group2 WSGIDaemonProcess group2 … -
what is attrs.get in Django REST serializers?
I am trying to understand and learn Django serializers. The give an example: from rest_framework import serializers class CommentSerializer(serializers.Serializer): email = serializers.EmailField() content = serializers.CharField(max_length=200) created = serializers.DateTimeField() def restore_object(self, attrs, instance=None): """ Given a dictionary of deserialized field values, either update an existing model instance, or create a new model instance. """ if instance is not None: instance.email = attrs.get('email', instance.email) instance.content = attrs.get('content', instance.content) instance.created = attrs.get('created', instance.created) return instance return Comment(**attrs) I can't figure out where 'attrs.get' comes from, or what it does. Even less clear are the lines like this: instance.email = attrs.get('email', instance.email) instance.content = attrs.get('content', instance.content) instance.created = attrs.get('created', instance.created) Which feels like a snake eating its tail...if 'instance' already has an 'email' attribute, what is the point of what looks like looking it up and then setting it to itself? -
Dynamic filtering on Django admin form
I have a three simple models: class Tag(models.Model): name = models.CharField(max_length=200) class Task(models.Model): name = models.CharField(max_length=200) tag = models.ManyToManyField(Tag) class Session(models.Model): task = models.ForeignKey(Task) It is hard to uers to select Task from all tasks in database. I want to allow user to reduce number of choices by filterting task by tag. So, user can select tag and then find task (in reduced amount of tasks). It is possible to implement? -
Django import-export how to replace integer ids with uuid ids?
I am building a django application where the user can export a json file of many models which are related to each other. Then the json fiele can be imported on another server. Since its an other database i can not use the ids which are exported in the file. I use django import-export for that. How can i replace the integer ids from my database with uuids to prevent double id problems? (especially when using foreign keys or many to many relations). In the following code does not work completely since Group.name is not unique. model.py class Group(models.Model): name = models.CharField(max_length=255) class Subgroup(models.Model): parent_group = models.ForeignKey(Group, on_delete=models.CASCADE) name = models.CharField(max_length=255) resources.py parent_group_widget = fields.Field( column_name='group_natural_key', attribute='parent_group', widget=ForeignKeyWidget(Group, 'name')) class GroupResource(resources.ModelResource): class Meta: model = Group exclude = ('id',) import_id_fields = ('name', 'measurement_widget') class SubgroupResource(resources.ModelResource): parent_group_widget = parent_group_widget class Meta: model = Subgroup exclude = ('id',) import_id_fields = ('name', 'parent_group_widget') I would like to get the following result: {"Group": [ { "id": "1c4d4824-d890-4021-bb24-18dd5a2cd618", "name": "Group_0", }] "Subgroup": [ { "name": "FOOBAR", "parent_group": "1c4d4824-d890-4021-bb24-18dd5a2cd618", } }