Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to fix the admin bug in django?
i created a Snippet model and registered an admin to this model and created a form to add records of this model but when clicking the snippet button on the admin page it takes me to the form i have created this is myu views method: def snippet(request): if request.method == "POST": form = SnippetForm(request.POST) if form.is_valid(): form.save() form = SnippetForm() return render(request,'form.html',{'form':form}) this is my form.py: class SnippetForm(forms.ModelForm): class Meta: model = Snippet fields = ('name', 'body') and this is my models.py class Snippet(models.Model): name = models.CharField(max_length=200) body = models.TextField() def __str__(self): return self.name -
Bootstrap sidebar overlaps with main
So I have been trying to make a webpage with a sidebar and a main content. Problem is that when the size goes to S/XS, the main content gets pushed to the left, leaving a margin to the right and the sidebar and main content overlaps. I hope to get rid of this problem. Here is some code and some screenshots.This is what it looks like on a computer screen sized screen (works fine) This is what looks like in ~m or maybe ~s sized screen, which also looks fine And this is the terrible looking s/XS screen, with overlapping content and what I'm hoping to avoid (I want it to look more like the previous picture and not make the main content shift left) <body> <div class="container-fluid"> <div class="row d-flex d-md-block flex-nowrap wrapper"> <div class="col-md-2 float-left pl-0 pr-0 collapse width show" id="sidebar"> <div class="list-group border-0 card bg-faded text-center text-md-left"> <a href="{% url 'landing:index' %}" class="list-group-item d-inline-block collapsed" data-parent="#sidebar"><i class="fas fa-home"></i> <span class="hidden-sm-down">返回首页</span></a> <a href="{% url 'dashboard:dashboard' %}" class="list-group-item d-inline-block collapsed" data-parent="#sidebar"><i class="fas fa-tachometer-alt"></i> <span class="hidden-sm-down">仪表盘</span></a> <a href="#menu1" class="list-group-item d-inline-block collapsed" data-toggle="collapse" data-parent="#sidebar" aria-expanded="false"><i class="fas fa-user"></i> <span class="hidden-sm-down">角色管理</span> </a> <div class="collapse {% if player_bar %}show{% endif %}" id="menu1"> <a href="{% … -
Django Downloading a media file using XHR gives error
Django Set-up. Requirement.txt asgiref==3.2.3 Django==3.0.2 django-cors-headers==3.2.1 django-filter==2.2.0 djangorestframework==3.11.0 Markdown==3.1.1 pytz==2019.3 sqlparse==0.3.0 URLS urlpatterns = [ path('admin/', admin.site.urls), path('fbx/', include('fbx.urls')), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Settings.py STATIC_ROOT = os.path.join(BASE_DIR,'static') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = '/media/' Upload model from django.db import models class Fbx(models.Model): name = models.CharField(max_length=200) fbx = models.FileField(max_length=200, blank=True) normals = models.FileField(max_length=200, blank=True) bump = models.FileField(max_length=200, blank=True) texture = models.FileField(max_length=200, blank=True) status = models.BooleanField(default=False) pub_date = models.DateTimeField(auto_now=True) IMPORTS and MIDDLEWARES INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'rest_framework', 'fbx.apps.FbxConfig' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', ] I have no issues with upload, everything works fine. I'm using Threejs FBXloader to download the FBX. This is an XHR call. This call fails. But if I put the same link on the browser it works fine. What could be the issue here? -
ERROR: THESE PACKAGES DO NOT MATCH THE HASHES FROM THE REQUIREMENTS FILE. when updating Django
I have Django 2.2.7 and now I want to install Django 3.0.2. I read that I need to run the command pip install -U Django to update it, but when I try it shows this error message ERROR: THESE PACKAGES DO NOT MATCH THE HASHES FROM THE REQUIREMENTS FILE. If you have updated the package versions, please update the hashes. Otherwise, examine the package contents carefully; someone may have tampered with them. Django from https://files.pythonhosted.org/packages/55/d1/8ade70e65fa157e1903fe4078305ca53b6819ab212d9fbbe5755afc8ea2e/Django-3.0.2-py3-none-any.whl#sha256=4f2c913303be4f874015993420bf0bd8fd2097a9c88e6b49c6a92f9bdd3fb13a: Expected sha256 4f2c913303be4f874015993420bf0bd8fd2097a9c88e6b49c6a92f9bdd3fb13a Got f97dfd0d593c3c78e81ca2f4fd095a21cd0a30752e7b8754294bf1d42541a218 What should I do? -
Django: Use dynamic API URLs in an REST API ENDPOINT
I am working on an API in Django and one of my GET (Retrieve) URLs should follow the following format. Ex: http://127.0.0.1:8000/api/customer/booking/approve/151236/ http://127.0.0.1:8000/api/customer/booking/decline/151236/ In the retrieve method we pass the PK which is according to this URL is 151236 while keeping the section before to change between approve or decline. Is it possible to create a single API endpoint that dynamically change like in the above requirement without having to write two separate API endpoints for approve and decline? -
Recursive function for Menu and Submenu until the last child is coming in Django
I've a MySQL Table Module which contains my Menu and Sub-menu both. Also I've created a relationship of Module table with same table itself like the Primary key of Module table(id) is the foreign key of Module Table it self(parent_id). Now I want a recursive function which will fetch all the modules as well as sub modules in a tree format in Django. Menu-1 + |-Sub-menu-1 |-Sub-Menu-2 |-Sub-Menu-2.1 |-Sub-Menu-2.2 parent_id of Sub-menu-1 will be the primary key of Menu-1 and parent_id of Sub-Menu-2.1 will be the primary key of Sub-menu-1. I'm new to Python and Djnago.. Can somebody help and do let me know if you need more info. -
How to use Django 2.2 with legacy PostgreSQL 8.4 database?
I am developing a new application on Django (DRF + Angular). The current LTS version of Django 2.2. The required data is stored in the PostgreSQL 8.4 database. But Django 2.2 supports PostgreSQL 9.4 and higher. Update PostgreSQL is not possible. What to do in this situation? What are the options? -
Python Django Web App does not work on docker
I created a default Django Web Project from Visual Studio 2017 and it runs fine. Even when I run the following command from the directory of projects, the app the app runs on http://localhost:5001 python manage.py runserver 0.0.0.0:5001 Then I created a Dockerfile with the following contents: FROM python:3.6 ENV PYTHONUNBUFFERED 1 RUN mkdir /app WORKDIR /app ADD . /app/ RUN pip install -r requirements.txt EXPOSE 5001 CMD ["python", "manage.py", "makemigrations"] CMD ["python", "manage.py", "migrate"] CMD ["python", "manage.py", "runserver", "0.0.0.0:5001"] Then, I use the following commands from the Dockerfile/Project Directory: docker build -t pydemo . and docker run pydemo The terminal does show that app is running on 0.0.0.0:5001, but http://localhost:5001 returns that site can't be reached. Can somebody please guide me to access the app through docker? -
Django ORM exclude result if found annihilation pair
I am using django-activity-stream to do my twitter clone for fun and sharpening my Django skills after daytime. Now I am using it to keep track the action in my system. I am tracking hidden and liked on the Tweet message Action.objects.filter(actor_content_type__id=user_ct.id, ...: target_content_type__id=tweet_ct.id).values_list('target_object_id', 'target_content_type', 'verb') Out[37]: <GFKQuerySet [('1', 28, 'hidden'), ('1', 28, 'liked')]> This is queryset that I feed the DjangoREST serializer to serialize out the response Problem: hidden and liked pair is considered as annihilation case(Sorry I don't know the best term so I adopt Particle Physics term to programming) and I need blank queryset as an answer Workaround: Switch main model to one another and use reverse relation back to the problem Question: How can I make conditional query like annihilation pair use case? -
I need help using sql statements about where conditions in my Django program
This is my program. I need to change the where condition in the sql statement to be dynamically generated using a python program, because sometimes a condition in my where statement may have no value. I do n’t want him to appear in the sql statement when there is no value. in Thank you very much, I really need help, I'm a newbie, I can't figure it out @csrf_exempt def test(request): if request.method == "GET": req_type = request.GET.get("get_data") if req_type: customer = request.GET.get('customer') order_type = request.GET.get("orderType") order_status = request.GET.get("orderStatus") with connection.cursor() as cursor: cursor.execute( "SELECT account,order_id,start_at,update_at " "FROM once WHERE user_id=%s OR %s='' AND order_id=%s OR %s='' AND status=%s OR %s='' ORDER BY order_id DESC ", (customer, customer, order_type, order_type, order_status,order_status)) verify_list = dict_fetchall(cursor) return HttpResponse(json.dumps(verify_list, cls=DecimalEncoder)) else: with connection.cursor() as cursor: cursor.execute('SELECT id,`name` FROM goods;') goods_data = cursor.fetchall() with connection.cursor() as cursor1: cursor1.execute('SELECT id,account FROM `user`;') user_data = cursor1.fetchall() content = {"goods_data": goods_data, "user_data": user_data} return render(request, 'user/test.html', content) else: return HttpResponseRedirect(reverse('users:login')) -
How to upload an image to a folder and pass its path to a view function in django?
I want to upload an image file using an input file tag from a django template. Then i want to do 2 things: 1) First i want to store the uploaded image in a directory in my project. I want to upload the file in img directory under static directory in my app so to access it easily. 2) Second i want to send the path of this newly stored image to a view function called detect_im() TEMPLATE: <form style="display:inline-block;"> <input type="file" class="form-control-file"> <input type="submit" value="Upload"=> </form> VIEW FUNCTION in views.py def detect_im(request): haar_file = 'C:\\Users\\Aayush\\ev_manage\\face_detector\\haarcascade_frontalface_default.xml' datasets = 'datasets\\' myid = random.randint(1111, 9999) path = "C:\\Users\\Aayush\\ev_manage\\face_detector\\" + datasets + str(myid) if not os.path.isdir(path): os.mkdir(path) (width, height) = (130, 100) face_cascade = cv2.CascadeClassifier(haar_file) filename = "" //I WANT THE STORED FILE NAME VALUE HERE TO COMPLETE THE PATH FOR FURTHER DETECTION PROCESS BY OPENCV. image_path = "C:\\Users\\Aayush\\ev_manage\\face_detector\\static\\img\\" + filename count = 1 while count < 30: im = cv2.imread(image_path) gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1.3, 4) for (x, y, w, h) in faces: cv2.rectangle(im, (x, y), (x + w, y + h), (255, 0, 0), 2) face = gray[y:y + h, x:x + w] face_resize = cv2.resize(face, (width, height)) … -
one to Many relationship in Django
I have two models with one to many relations such as class Speciality(models.Model): name = models.CharField(max_length = 256) code = models.CharField(max_length = 256) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length = 256) code = models.CharField(max_length = 256) reg_code = models.CharField(max_length = 256) packe_size = models.CharField(max_length = 256) type = models.CharField(max_length = 256) category = models.ForeignKey(Speciality, on_delete=models.CASCADE) its url path('speciality/<int:pk>',views.SpecialityDetailView.as_view(),name = 'speciality_product'), and here is CBV class SpecialityProductView(generic.ListView): model = Product def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['product_list'] = self.object.category_id.all() return context I want products list based on specifinc Speciality -
Django REST API login from different auth table
I need to login, logout a user with Django REST. Its an API created to be called from different apps, so I need to mantain a session. My problem is that I found a lot of solutions but I dont know witch work best with my case. I have Model named User, and I want to register, login and logout with him, with a email and password. My first question is, does work for me login with Django auth methods? Its like for every user I create with my API in table User , I need to create another instance on django auth to login, logout? And it will work to be able to do API calls? Im a bit lost. If you know some reference that I can check that work perfectly with my case, please send it to me. -
How to add JWT token into credentials in Django
In testing, I cannot authenticate my test user. How to add JWT token into self.client.credentials. def test_retrive_profile_success(self): """Test retriving profile for authenticated user""" res1 = self.client.post(TOKEN_URL, {'email':'test@greatsoft.uz', 'password':'password'}) token = res1.data['token'] self.client.credentials(HTTP_AUTHORIZATION='Token ' + token) res = self.client.get(ME_URL) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(res.data, { 'email':self.user.email }) I am getting a response of 401. -
How can we achieve custom validation in django class based views(create and update view)
I want to use uniqueness validation in class-based views. Here I have createView where I want to add part_no uniqueness validation at the time of form post. How can we achieve this? Any solutions. Views.py class SparePartsCreate(CreateView): template = 'maint/spareparts_form.html' model = SpareParts fields = ['name', 'description', 'part_no'] success_url = reverse_lazy('spare_parts') form.py class SparePartForm(forms.ModelForm): name = forms.CharField(required=True, label='Spare Part Name') description = forms.CharField(required=True, label='Spare Part Description') part_no = forms.CharField(required=True, label='Spare Part Number', max_length=6) class Meta: model = SpareParts fields = ['name','description','part_no'] def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super(SparePartForm, self).__init__(*args, **kwargs) As we implement validation in function-based views in form.py under clean method. For class-based views anything is there? -
Django - is it required to use/overwrite form_valid() when using CBV?
I'm using the below class based view in Django in order to be able to create/insert new object in the database which works: class AddAreaMapView(CreateView): model = AreaMap fields = ['fCityCode', 'fCountyCode', 'fCountryCode', ] template_name = 'myapp/blank.html' success_url = '/' However, I've seen that there is recommended to use form_valid() method together with the CreateView. Why is it required to overwrite it since Django is already doing that? Is a missing piece of information and I would appreciate if anyone could provide a relevant answer. Thanks! -
Django returning no such column id
I made some changes to my signup form to capture more information. However, when I go through the signup process now I get the following error message. Not sure what the issue is. I already ran makemigrations and migrate (after deleting all prior migrations): views.py (teachers.py): def edit_user(request): user = request.user mentorform = MentorProfileForm() if request.method == 'POST': form = UserForm(request.POST, request.FILES, instance=user) if form.is_valid(): form.save() messages.success(request, f'Your profile was successfully updated!') return HttpResponseRedirect('%s' % (reverse('teachers:edit_user'))) else: form = UserForm(instance=user) return render(request, 'classroom/teachers/app-instructor-profile.html', {'form': form}) forms.py: class TeacherSignUpForm(UserCreationForm): email = forms.EmailField(max_length=100) first_name = forms.CharField(max_length=100) last_name = forms.CharField(max_length=100) linkedin = forms.URLField(max_length=200) address = forms.CharField(max_length=500) invoice_name = forms.CharField(max_length=200) account_num = forms.IntegerField() bank_name = forms.CharField(max_length=50) branch_code = forms.IntegerField() class Meta(UserCreationForm.Meta): model = User fields = ('email', 'username', 'first_name', 'last_name') def save(self, commit=True): self.instance.is_teacher = True user = super(UserCreationForm, self).save(commit=False) user.email = self.cleaned_data['email'] user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.save() mentor = Mentor.objects.get_or_create( user=user, linkedin=self.cleaned_data['linkedin'], address=self.cleaned_data['address'], invoice_name=self.cleaned_data['invoice_name'], account_num=self.cleaned_data['account_num'], bank_name=self.cleaned_data['bank_name'], branch_code=self.cleaned_data['branch_code'], ) return user models.py: class Mentor(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='mentor') linkedin = models.URLField(max_length=200,null=True,blank=True) invoice_name = models.CharField(max_length=200, null=False, blank=False) account_num = models.IntegerField(default=1234) bank_name = models.CharField(max_length=50, null=False) branch_code = models.IntegerField(default=1234) def __str__(self): return "Profile of user {}".format(self.user.username) I get this error message when I try … -
How to pass parameter in url?
I'm new to Django. I have a task in which in have to create view.py, template, url.py and model.py in django, In which I have four Button D1, D2, D3, D4 in template. When I click on D1 it redirect me a page in which the link which i get is http://127.0.0.1:8000/uploads/test/D1. And while clicking on D2 link redirect me one same page and link is http://127.0.0.1:8000/uploads/test/D2. Similarly while clicking on D2 and D3 links are http://127.0.0.1:8000/uploads/test/D3 and http://127.0.0.1:8000/uploads/test/D4 -
Django: Celery override Celery base class for logging
Currently, I am going through the answer to a question in StackOverflow. In the answer, the author talked about logging celery tasks. As he said I need to override the base class of Celery. I need some help here that where should I place the code and how to get it working right. Link to the answer I mentioned. -
How to get the foreignkey with sending objects.all() related to the Model
I can't figure out how I retrieve data in the template that is related to the foreign key. I will show you what I have now, that will clear things out for you. CompanyProfile: class CompanyProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, related_name='company_profile') company_name = models.CharField(max_length=30) def __str__(self): return self.company_name Job: class Job(models.Model): user = models.ForeignKey(CompanyProfile, on_delete=models.CASCADE) title = models.CharField(max_length=300) is_active = models.BooleanField(default=True) def __str__(self): return self.title JobFunction: class JobFunction(models.Model): job = models.ForeignKey(Job, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=60) def __str__(self): return self.name The view: def show_jobs(request): jobs = Job.objects.all() job_type = JobFunction.objects.all() context = { 'jobs': jobs, 'job_type': job_type, } return render(request, 'jobportal/jobs/browse-job.html', context, { }) One Job can have multiple Job Functions, or just 1 it doesn't matter but I need to get the one where JobFunction is related to a Job. I do the folowwing: {% for job in jobs %} {{ job.title }} {% for jf in job_type %} {{ jf.name }} {% endfor %} {% endfor %} The 'job' is showing everything fine but the jf is not dynamic, it shows the same functions in all the jobs in the list. The loop has an id, I mean I want to say that job.id = job_type.id but … -
How to call a function in views.py on clicking a button in template.html in django
I have a form in which there is a button . I want to call a view function named def recognize(): in my views.py but after clicking the page should not reload and the values filled in the inputs before the button should not be cleared. TEMPLATE FILE <form> <div class="form-row"> <div class="form-group col-md-6"> <label for="first_name">First Name</label> <input type="text" name="first_name" class="form-control" id="first_name" required/> </div> <div class="form-group col-md-6"> <label for="last_name">Last Name</label> <input type="text" name="last_name" class="form-control" id="last_name" required/> </div> </div> <button type="button" class="mybtn">Open Camera</button> // THIS IS THE BUTTON TO BE CLICKED <button type="submit" class="btn btn-danger">Submit</button> </form> VIEWS.PY (hiding extra details) def recognize(request): size = 4 haar_file = 'C:\\Users\\Aayush\\ev_manage\\face_detector\\haarcascade_frontalface_default.xml' datasets = 'C:\\Users\\Aayush\\ev_manage\\face_detector\\datasets' while True: (_, im) = webcam.read() gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1.3, 5) for (x, y, w, h) in faces: cv2.rectangle(im, (x, y), (x + w, y + h), (255, 0, 0), 2) face = gray[y:y + h, x:x + w] face_resize = cv2.resize(face, (width, height)) # Try to recognize the face prediction = model.predict(face_resize) cv2.rectangle(im, (x, y), (x + w, y + h), (0, 255, 0), 3) if prediction[1] < 90: cv2.putText(im, '% s - %.0f' % (names[prediction[0]], prediction[1]), (x - 10, y - 10), cv2.FONT_HERSHEY_PLAIN, 1, … -
Show data from other tables __str__(self) function & bad post request error if foreign key related entry does not exists in django
I am writing django 3.0 based web app and using mysql version 5.7 database along with django rest framework My models.py is as shown below class Visitor(models.Model): firstname = models.CharField(max_length=50,blank=True,default="") lastname = models.CharField(max_length=100,blank=True,default="") employeeid = models.CharField(max_length=30,unique=True) class Meta: db_table = "visitor" def __str__(self): return self.firstname + " " + self.lastname class AttendanceScan(models.Model): scantime = models.DateTimeField() employeeid = models.CharField(max_length=30) #employeeid = models.ForeignKey('Visitor', to_field='employeeid',on_delete=models.SET_NULL,null=True,blank=True,) class Meta: db_table = "attendancescan" def __str__(self): return self.employeeid + " \t" + str(self.scantime) #my serializer.py is as shown below class attendancescanSerializer(serializers.ModelSerializer): class Meta: model = AttendanceScan fields= '__all__' #my views.py is as shown below class AttendanceReportListView(viewsets.ModelViewSet): queryset = AttendanceScan.objects.all() serializer_class = attendancescanSerializer #My admin.py as shown below class AttendanceScanAdmin(admin.ModelAdmin): list_display = ['Visitor', 'scantime', ] def Visitor(self, obj): return obj.employeeid # get_employeeid.admin_order_field = 'author' #Allows column order sorting admin.site.register(AttendanceScan, AttendanceScanAdmin) On the admin page it displays data as shown below Visitor scan time 1 Jan 19,2020,3.57 pm 2 Jan 19,2020, 4.20 pm 3 Jan 19,2020, 5.20 pm Instead of visitor id I need to show visitor first name and visitor last name from Visitor table on /attendancescan webpage Visitor scan time Visitor1FirstName visitor1LastName Jan 19,2020,3.57 pm Visitor2FirstName visitor2LastName Jan 19,2020,4.20 pm Visitor3FirstName visitor3LastName Jan 19,2020,5.20 pm. Further if … -
Challenges with Django Profiles
I have my models as below: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') role = models.CharField(max_length=25,choices=role, default='Freelancer') def __str__(self): return f'{self.user.username} Profile' and my view as below: def profile(request): if request.method == 'POST': p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if p_form.is_valid(): p_form.save() messages.success(request, f'Your account has been updated!') return redirect('profile') else: p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'p_form': p_form } return render(request, 'profile.html', context) and my signals file as below: @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) profile.save() @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() But when I try to create a new user the profile is not created and I get RelatedObjectDoesNotExist at /profile/ User has no profile. I have no idea why this is not working. I must also mention I am using Django allauth for my authentication -
What am I doing wrong, it seems all my codes are right but I'm I'm getting an error 404 on my add to cart Django e-commerce app
My server is starting correctly but I keep getting a page not found error. from django.urls import path from .Views import Home from cart views import Home, add_to_cart, remove_from_cart app_name= 'mainapp' urlpatterns = [ path('', Home.as_view(), name='cart'), path('cart/<slug>', add_to_cart, name='cart'), path('remove/<slug>', remove_from_cart, name='remove-cart'), ] This is the code in my products/urls.py -
Django Import Export Inline
I got stuck when using it in inline model class Order(models.Model): customer = models.ForeignKey(User, on_delete=models.CASCADE, default=None, null=True, blank=False) courier = models.ForeignKey(Courier, on_delete=models.CASCADE, null=True, blank=False) shipping_charges = models.DecimalField(max_digits=25, decimal_places=2, null=True, blank=False) payment = models.CharField(max_length=100, choices=Payment, default='Bank Transfer', null=True, blank=False) status = models.CharField(max_length=100, choices=Status, default='Pending', null=True, blank=False) date_added = models.DateField(auto_now_add=False, null=True, blank=False) date_modified = models.DateField(auto_now=True, null=True, blank=True) def __str__(self): return 'by ' + str(self.customer) class Item(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, null=True, blank=False) product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True, blank=False) attribute = models.ForeignKey(Attribute, on_delete=models.CASCADE, null=True, blank=True) quantity = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=False) total = models.DecimalField(max_digits=25, decimal_places=2, null=True, blank=False) def __str__(self): return self.product.title I used compactinline with jet admin, when i trying to export data for ITEM got blank data, i want export product too in each order detail. This my export class class OrderExport(resources.ModelResource): date_added = Field(attribute='date_added', column_name='Date') customer = Field(attribute='customer', column_name='Customer') product = fields.Field(attribute='product', column_name='Product', widget=ForeignKeyWidget(Item, 'product')) courier = Field(attribute='courier', column_name='Courier') shipping_charges = Field(attribute='shipping_charges', column_name='Shipping Charges') payment = Field(attribute='payment', column_name='Payment') status = Field(attribute='status', column_name='Status') class Meta: model = Order fields = ('date_added', 'customer', 'product', 'courier', 'shipping_charges', 'payment', 'status')