Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Import "project4.app4.models" could not be resolved
I made two projects in django, project4 and project5 and then made two apps app4 and app5 respectively. Now I want to import models of project4 in project5. I add 'project4.app4' in settings.py file of project5 and I add this line sys.path.append('E:\Internship\Djangoenv\project4') in wsgi.py file of project5. Now I am importing that model by writing 'from project4.app4.models import Hero (my model class is Hero) then it is showing error "Import "project4.app4.models" could not be resolved". admin.py of project5[wsgi.py of project5settings.py of project5 -
Url Formation with multiple urls in django
mysite.urls file: urlpatterns = [ path('admin/', admin.site.urls), path('' , include('store.urls')), path('', include('blog.urls')), path('/wishlist/', include('wishlist.urls')), ] wishlist.urls file: urlpatterns = [ url('admin/', admin.site.urls), url(r'^$', WishlistView.as_view(), name='wishlist'), url(r'^add/$', WishlistAddView.as_view(), name='wishlist_add'), url(r'^clear/$', WishlistClearView.as_view(), name='wishlist_clear'), url(r'^(?P<pk>\d+)/remove/$', WishlistRemoveView.as_view(), name='wishlist_remove'), url(r'^login$', auth_views.LoginView.as_view(template_name='accounts/login.html')), ] wishlist and urls dont combine to create a page not found error. -
Can we update a value after it has been referenced as a foreign key in django?
I have two tables: class LocationType(models.Model): location_type = models.CharField(max_length=120, unique=True) comment = models.TextField(null=True, blank=True) def __str__(self): return self.location_type class Location(models.Model): location = models.CharField(max_length=100, unique=True) location_type = models.ForeignKey(LocationType, to_field="location_type", on_delete=models.CASCADE) comment = models.TextField(null=True, blank=True) def __str__(self): return self.location and I have created a location_type 'PLANT' and then referenced it while creating a location "GUJRAT". location_type1 = LocationType.objects.create(location_type="PLANT") location1 = Location.objects.create(location="GUJRAT", location_type=location_type1) Now after creating these two entries I want to change location_types value from "PLANT" to "FACTORIES". location_type1.location_type = "FACTORIES" location_type1.save() But I am getting below error: Traceback (most recent call last): File "/home/jayantseth/Projects/ip_manager/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "/home/jayantseth/Projects/ip_manager/venv/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 477, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: FOREIGN KEY constraint failed The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/jayantseth/Projects/ip_manager/IpManagerBackend/ipmanager/models.py", line 58, in save super(LocationType, self).save(*args, **kwargs) File "/home/jayantseth/Projects/ip_manager/venv/lib/python3.8/site-packages/django/db/models/base.py", line 806, in save self.save_base( File "/home/jayantseth/Projects/ip_manager/venv/lib/python3.8/site-packages/django/db/models/base.py", line 857, in save_base updated = self._save_table( File "/home/jayantseth/Projects/ip_manager/venv/lib/python3.8/site-packages/django/db/models/base.py", line 970, in _save_table updated = self._do_update( File "/home/jayantseth/Projects/ip_manager/venv/lib/python3.8/site-packages/django/db/models/base.py", line 1034, in _do_update return filtered._update(values) > 0 File "/home/jayantseth/Projects/ip_manager/venv/lib/python3.8/site-packages/django/db/models/query.py", line 885, in _update return query.get_compiler(self.db).execute_sql(CURSOR) File "/home/jayantseth/Projects/ip_manager/venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1783, in execute_sql cursor = super().execute_sql(result_type) File "/home/jayantseth/Projects/ip_manager/venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", … -
Digital ocean droplet is only showing the default nginx page when connected with a namecheap domain
I'm using a Django Digital Ocean droplet to run a website where I recently tried connecting the IP address of the droplet to a namecheap domain name, but when I connected them it only showed this on the domain: Welcome to nginx! If you see this page, the nginx web server is successfully installed and working. Further configuration is required. For online documentation and support please refer to nginx.org. Commercial support is available at nginx.com. Thank you for using nginx. However, the website was working as intended on the IP address, can anyone tell me how to fix this? my abbreviated /etc/nginx/sites-available/default file server { listen 80 default_server; listen [::]:80 default_server; root /var/www/html; index index.html index.htm index.nginx-debian.html; server_name sanskarhandicrafts.com; location / { try_files $uri $uri/ =404; } } -
Url Pattern giving me a url mismatch error
url(r'^(?P<pk>\d+)/remove/$', WishlistRemoveView.as_view(), name='wishlist_remove'), <form action="{% url 'wishlist_remove' pk=item.wishlistitem_set.all.0.pk %}" method="post"> {% csrf_token %} <input type="submit" value="{% trans 'Remove' %}"> </form> When i click on the remove button I get the following error:- NoReverseMatch at /product/7/ Reverse for 'wishlist_remove' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['(?P<pk>\\d+)/remove/$'] Something is wrong -
No indentations for the options in the select box in an inlined table (Django MPTT)
I created many-to-many relationship with the tables "Category", "Product" and "CategoryProduct" which is the middle table between "Category" and "Product": "models.py": from django.db import models from mptt.models import MPTTModel, TreeForeignKey class Category(MPTTModel): name = models.CharField(max_length=50, unique=True) parent = TreeForeignKey( "self", on_delete=models.CASCADE, null=True, blank=True, related_name="children" ) class MPTTMeta: order_insertion_by = ["name"] def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class CategoryProduct(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) class Meta: unique_together = [['category', 'product']] Then, I registered "Category" and "Product" inlined "CategoryProduct" to: "admin.py": from django.contrib import admin from mptt.admin import MPTTModelAdmin from .models import Category, Product, CategoryProduct admin.site.register(Category, MPTTModelAdmin) class CategoryProductInline(admin.TabularInline): model = CategoryProduct @admin.register(Product) class ProductAdmin(admin.ModelAdmin): inlines = [CategoryProductInline] Then, I added some categories and as you can see, the options in the select box of "Parent" have indentations: But when I tried to add a product, as you can see, the options in the select box of "Category" don't have indentations: Is it possible to give indentations to the options in the select box of "Category"? If possible, how can I do this? -
Django : Create a Form for a dropdown list depending of ID User and Models
I am Newbee in Django. I want to create a Form for a dropdown list. The Dropdown list should show different choices depending on User and the models. I did something directly on the view.py that displays the choices without using a Form from Django and it does not store it. So it is not ideal for what I want to do after the POST. Here are my Models.py class TblAadJntGroup(models.Model): id = models.AutoField(db_column='ID', primary_key=True) # Field name made lowercase. id_aadgroup = models.IntegerField(db_column='ID_AADGroup', blank=True, null=True) # Field name made lowercase. id_aaduser = models.IntegerField(db_column='ID_AADUser', blank=True, null=True) # Field name made lowercase. createdon = models.DateTimeField(db_column='CreatedOn', blank=True, null=True) # Field name made lowercase. createdby = models.CharField(db_column='CreatedBy', max_length=255, blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'tbl_AAD_jnt_Group' class TblAadGroups(models.Model): id = models.AutoField(db_column='ID', primary_key=True) # Field name made lowercase. idcustomer = models.IntegerField(db_column='IDCustomer', blank=True, null=True) # Field name made lowercase. displayname = models.CharField(db_column='DisplayName', max_length=255, blank=True, null=True) # Field name made lowercase. timestampm = models.DateTimeField(db_column='TimeStampm', blank=True, null=True) # Field name made lowercase. username = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = False db_table = 'tbl_AAD_Groups' So to get the data that I want to display in the dropdown. I start to … -
Django migrations circular dependency what is the best practice?
I would like to know the best practice to handle CircularDependency when migrating apps. Our CRM has two Apps with several model fields depending on each other. We need to reconstruct the database everyday and this lead us to regenerate and apply migrations everyday. In our code the foreign keys are referenced with : model_name = models.ForeignKey('app.model', ...) So no issues at runtime. But at night, when we regenerate and apply the migrations, we made a migrate script that basically swaps the foreign keys as IntegerField to prevent CircularDependencyError and reswaps them after the depencies are solved. Is there a better way to do this ? -
How to get model objects with AJAX?
I have a Customer model in my Django application. New users are constantly being added to this model in the background and I want to list these customers dynamically with AJAX. But I cannot figure it out. How can I do that? def ajax_view(request): obj = Customer.objects.filter(company=request.user.company) customers = [] for customer in obj: customers.append(customer) data = { "obj": customers } return JsonResponse(data) html <h3 id="status"></h3> <script> var refresh = setInterval(function() {$.ajax({ url: "{% url 'user:ajax_customer' %}", type: "GET", dataType: 'json', success: function (data) { if (data) { console.log(data); console.log(status); document.getElementById("status").innerHTML = data.obj; } } });}, 1000); </script> I try to do that but It gives an error: TypeError: Object of type Customer is not JSON serializable -
Django setUpTestData does not deepcopy related files
I want to use django setUpTestData to prepare some heavy data shared between multiples unit tests. Instances of my Model are created with some file fields. However, from one test to another, file contents are not renewed, it has side effects between my tests here is a minimalist example : models.py from django.db import models class MyModel(models.Model): my_file = models.FileField(upload_to="tests/") test.py from django.core.files.base import ContentFile from django.test import TestCase from core.models import MyModel class Test(TestCase): @classmethod def setUpTestData(cls): cls.instance = MyModel() cls.instance.my_file.save("file.txt", ContentFile("Hello from setUpTestData")) def test_a(self): with open(self.instance.my_file.path, "r") as fp: self.assertEqual(fp.read(), "Hello from setUpTestData") self.instance.my_file.save("file.txt", ContentFile("Modified data")) def test_b(self): with open(self.instance.my_file.path, "r") as fp: self.assertEqual(fp.read(), "Hello from setUpTestData") self.instance.my_file.save("file.txt", ContentFile("Modified data")) Running any of the two test alone works, however running one after the other one fails: AssertionError: 'Modified datatUpTestData' != 'Hello from setUpTestData' - Modified datatUpTestData + Hello from setUpTestData How to ensure that file are correctly reset? Am I concerned by theses lines from the documentation ? Objects assigned to class attributes in setUpTestData() must support creating deep copies with copy.deepcopy() I feel like fileField should be handled by default by Django but it doesn't work, what should I do? Should I try to override __deepcopy__ … -
Custom command line parameter for testing
I found a way to pass a custom parameter to Django testing from command line: class TestRunner(DiscoverRunner): @classmethod def add_arguments(cls, parser): DiscoverRunner.add_arguments(parser) parser.add_argument('-b', '--browser', help='Browser test') But how can I get this parameter value inside my TestCase ? -
Why in unit test object's field doesn't change in Django
I don't understand why my test doesn't work. I have a page with product. There is a form with button 'Buy product'. After pushing this button, if a client have enough money, the item will bought and the ammount of money in the account will change. But in my test the ammount of money will be the same after buying a product, although the object(purchased item) will be created. Purchased item model: class BoughtItem(models.Model): name = models.CharField(max_length=100, verbose_name='Название товара или акции', blank=True) price = models.IntegerField(verbose_name='Цена', blank=True) created_at = models.DateTimeField(auto_now_add=True) Profile model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) money = models.IntegerField(default=0) form: class BuyForm(forms.ModelForm): class Meta: model = BoughtItem fields = ('name',) widgets = {'name': forms.HiddenInput()} view: class ItemDetailView(generic.DetailView): model = Item template_name = 'item_detail.html' context_object_name = 'item' def get_object(self, queryset=None): return get_object_or_404(Item, pk=self.kwargs.get('pk')) def post(self, request, *args, **kwargs): buy_form = BuyForm(request.POST) if buy_form.is_valid(): purchase = buy_form.save(commit=False) item = self.get_object() user = Profile.objects.get(user__username=request.user.username) if user.money >= item.price: sum_difference = user.money - item.price user.money = sum_difference user.save() purchase.name = item.name purchase.price = item.price purchase.save() return HttpResponseRedirect(reverse('account', kwargs={'username': request.user.username})) else: return HttpResponseRedirect(reverse('purchase_error')) else: return render(request, 'item_detail.html', context={'buy_form': buy_form, 'object': self.get_object()}) urls: urlpatterns = [ path('shop_list/', ShopListView.as_view(), name='shop_list'), path('<str:name>', ItemListView.as_view(), name='shop_detail'), path('item/<int:pk>', ItemDetailView.as_view(), name='item_detail'), … -
define a Generic, non serialising field in django rest serializers
This is just a layout of my serializer class SerializerA(serializers.ModelSerializer): field_a = serializers.SerializerMethodField() field_b = serializers.SerializerMethodField() field_c = serializers.SerializerMethodField() field_d = serializers.SerializerMethodField() class Meta: model = TestModel fields = ("field_a", "field_b", "field_c", "field_d", "name", "designation") def get_field_a(self, obj): temp = TempUserModel.objects.get(pk=obj.uuid) field_a = "some ORM query related to temp and TestModel model" return field_a def get_field_b(self, obj): temp = TempUserModel.objects.get(pk=obj.uuid) field_b = "some ORM query related to temp and TestModel model" return field_b def get_field_c(self, obj): temp = TempUserModel.objects.get(pk=obj.uuid) field_c = "some ORM query related to temp and TestModel model" return field_c def get_field_d(self, obj): field_d = "some ORM query related to TestModel model" return field_d Here temp = TempuserModel.objects.get(pk=obj.uuid) is same in 3 out of 4 of the class methods. So is there any way that I can define it once somewhere in a serializer loop and use it without doing the same ORM query again and again? -
Count the courses that a particular instructor has created
I am building an elearning platform where an instructor can create courses. I am facing a problem when displaying the number of courses that a particular instructor has. I wanted to count the number of courses that the instructor has created. However, my code displays all the courses that are in the database. Please help. index.html <div class="col-xl-3 col-md-6 mb-4"> <div class="card border-left-info shadow h-100 py-2"> <div class="card-body"> <div class="row no-gutters align-items-center"> <div class="col mr-2"> <div class="text-xs font-weight-bold text-info text-uppercase mb-1">Total Courses </div> <div class="row no-gutters align-items-center"> <div class="col-auto"> <div class="h5 mb-0 mr-3 font-weight-bold text-gray-800">{{ course_count }}</div> </div> </div> </div> <div class="col-auto"> <i class="fas fa-clipboard-list fa-2x text-gray-300"></i> </div> </div> </div> </div> views.py def instructorDashboard(request): customer = Users.objects.all() course = Course.objects.all() course_count = course.count() context = {'customer':customer, 'course_count': course_count} return render(request, 'instructor_dashboard/index.html', context) -
graphene-django send Arries to front-end barchart
I have connected to sql server database and have got table data from columns of tables. Now I want to cretae 2 list of data set for xand y dirextion to show them i a barchart in Vuejs. I know how to send sting and integer, but how to send tw0 dataset for x and y valuse to show in barchart? thanks -
I changed the class name in document via "getElementById" but it doesn't take effect [duplicate]
Thank you for advance. I changed the class name in JavaScript, but it doesn't change. [javascript] for (i = 0; i < storeBtns.length; i++) { storeBtns[i].addEventListener('click', function(){ document.getElementById(this.dataset.product).class = 'btn-primary'})} When I check (document.getElementById(this.dataset.product).class by adding alert to the bottom line, "btn-primary" appears, but this does not apply in the page. What should I do? I also tried with classList.add , but it didn't work, so I was wondering if there is anything else to do, such as returning document . Thank you. -
Django rest framework: Mixed content
I am quite new in Django rest framework. I have a project which contain Django restframework API inside a Django site project(with simple frontend code) and it works fine in my local environment. However in the production domain(HTTPS) it shows as below: Mixed Content: The page at 'https://<my production domain>/audience/labeling_jobs/' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://<my production domain>/audience/labeling_jobs/api/jobs/?page=2'. This request has been blocked; the content must be served over HTTPS. I have setup the configuration about SSL/HTTPS according to Django document SSL/HTTPS beforehand but it still got this error. USE_X_FORWARDED_HOST = True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_HSTS_INCLUDE_SUBDOMAINS = True SECURE_HSTS_PRELOAD = True SECURE_SSL_REDIRECT = True It seems that the Django rest cannot get the correct HTTPS, but it works fine with other django paths, they can be showed on the production page. Is there anything I have missed? -
How to call an API constantly with a function?
I have a customer management system. I am using an API to get all of the customers. It works perfectly. I am using an ID, if there is no customer who has this ID, then it creates a new customer. Here is my code for that: def handle_get_customers(company): customer_service = requests.get(settings.API_ADDRESS + "customer/get/all", headers={'Authorization': "Bearer " + token_key}).json() service_customers = [] for customer in customer_service["data"]: service_customers.append(customer) for person in service_customers: new_customer, obj = Customer.objects.get_or_create(api_id=person["id"]) new_customer.customer_name = person["name"] country, d = Country.objects.get_or_create(country_name=person["countryName"]) new_customer.country = country new_customer.address = person["fullAddress"] new_customer.phone_number = person["phoneNumber"] new_customer.email_address = person["email"] new_customer.currency_choice = person["currency"] new_customer.api_id = person["id"] new_customer.company = company new_customer.save() return service_customers And I am listing all customers on a page. It has a basic listing function like; def customer_list(request): current_user = request.user handle_get_customers(current_user.company) customer_list = Customer.objects.filter(company=current_user.company) context = { 'customer_list': customer_list, } return render(request, 'customer_list.html', context) I want to get all new companies without refreshing the page. I don't know if I can use Ajax for that but I guess the handle_get_customers function should work constantly but I cannot figure out how can I do it? -
Django set value of ForeignKey field in ModelForm upon submission
I have RequisitionModel that takes siteID from my User model as its ForeignKey. How do I have RequisitionModelForm pull the current user's siteID and pass it into the form? *I do not want the HTML template to display the siteID field, but have it set in the "background" upon form submission. forms.py class RequisitionModelForm(forms.ModelForm): class Meta: model = MaterialRequisition fields = ( 'reqDescription', 'reqDateNeeded', 'reqItems' ) widgets = { 'reqDateNeeded': forms.DateInput(attrs={'type': 'date'}), } def __init__(self, *args, **kwargs): super(RequisitionModelForm, self).__init__(*args, **kwargs) queryset=Item.objects.all(), widget=forms.CheckboxSelectMultiple, ) models.py class MaterialRequisition(models.Model): req = models.AutoField(primary_key=True) #change to UUIDField if needed site = models.ForeignKey("project_site.Site", related_name='destinationSite', on_delete=models.CASCADE) reqDescription = models.CharField(max_length=1000, blank=True) reqDateSubmitted = models.DateTimeField(auto_now=True) reqDateNeeded = models.DateField(auto_now=False) reqItems = models.ManyToManyField( Item, through="MaterialRequisitionItems", through_fields=('reqID', 'itemID'), related_name="mat_req_items" ) -
How to show foregin key of another django model in django admin fields or django admin fieldsets
I have two Django models: Bot and Seller. class Bot (models.Model): nick_name = models.CharField (verbose_name="Nick Name", max_length=100) wallet_coins = models.CharField (verbose_name="Bot Coins", max_length=30, default="0") wallet_coins_initial = models.CharField (verbose_name="Initial Coins", max_length=30, default="0") order_amount = models.CharField (verbose_name="Order Amount", max_length=30, default="0") ## it's obtained from sum of initial-coins and order-amount: final_coins = models.CharField (verbose_name="Final Coins", max_length=30, default="0") class Seller (models.Model): bot = models.ForeignKey ('Bot', on_delete=models.CASCADE, verbose_name="Bot Name", blank=True, null=True) market = models.ManyToManyField ('MarketTransfer', verbose_name="Market Card(s)") name = models.CharField (verbose_name="Seller Name", max_length=100) price_ratio = models.CharField (verbose_name="Price Ratio", max_length=10, default="1.5") emulate_final_coins = models.CharField ( verbose_name="Emulated Final Coins", max_length=30, default="0") When i want to use fields or fieldsets property to change the order of fields, i see error below: Picture of Error: https://imgur.com/a/HxgcN24 FieldError at /admin/ea_app/seller/1/change/ Unknown field(s) (show_bot_name) specified for Seller. Check fields/fieldsets/exclude attributes of class SellerAdmin. I want to change the location of fields in Django Admin. codes below works without problem. but i need to change the locations. unfortunately i see error (picture above). class SellerAdminInLine (admin.TabularInline): model = Seller.market.through verbose_name = "In-Use Cards" verbose_name_plural = "In-Use Cards" class SellerAdmin (admin.ModelAdmin): readonly_fields = ['total_price', 'show_bot_coins', 'show_bot_final_coins', 'emulate_final_coins'] list_per_page = 10 list_display_links = ['name'] list_display = ['name', 'wallet_coins', 'price_ratio', 'show_bot_name', 'show_bot_coins', 'added_at'] search_fields = … -
Django - AWS Elastic beanstalk- I was following the Aws documentation - Error: $ eb --version bash: eb: command not found
I was following the AWS documentation, have done - pip install awsebcli in gitbash when I checked for version (eb --version) it has thrown me the error - bash: eb: command not found what should I do - is that a path error - if so how should I correct it?? I appreciate your help -
Django orm foreignkey get latest data
reference class Model1(model.Model): master = models.ForeignKey(User, on_delete=models.CASCADE) member = models.ForeignKey(User, on_delete=models.CASCADE) status = models.PositiveIntegerField(default=0) class Model2(models.Model): model1 = models.ForeignKey(Model1, on_delete=models.CASCADE) writer = models.ForeignKey(User, on_delete=models.CASCADE) text = models.TextField() created_at = models.DateTimeField(auto_now_add=True, null=True) How to get latest model2 data I want to have response{ master="USER1", member="USER2", status=0, last_content="latest Model2 text" last_date="2020.03.21" } Is there any better way instead of subquery? -
Heroku ModuleNoteFoundError with django-qr-code
I am currently working on the Backend of my small application. During deployment, I am getting the following error: ModuleNotFoundError: No module named 'qr_code' I am not using the pypi qrcode library, instead I am using the django-qr-code library https://django-qr-code.readthedocs.io/en/latest/pages/README.html My Requirements.txt > asgiref==3.5.0 backports.entry-points-selectable==1.1.1 certifi==2021.10.8 distlib==0.3.4 dj-database-url==0.5.0 Django==4.0.3 django-heroku==0.0.0 django-qr-code==3.0.0 filelock==3.4.0 gunicorn==20.1.0 Pillow==9.0.1 pipenv==2021.11.23 platformdirs==2.4.0 segno==1.4.1 six==1.16.0 sqlparse==0.4.2 virtualenv==20.10.0 virtualenv-clone==0.5.7 whitenoise==6.0.0 My settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sessions', 'sendqr', 'qr_code', ] Somehow Heroku can't seem to properly find the django-qr-code library even though it is inside of my requirements.txt. Is there a way to maybe manually push it onto the heroku server or something? -
New clients cannot connect to Django site when site are being used by other clients
We have a Django based web application that is being deployed with Apache and mod_wsgi. The users logs in and can start some CPU-bound processes that can take up to 1-2 minutes. Our problem is, when these CPU-bound processes are being run, the new clients cannot even load the site. Even if they can load it and enter their credentials and press log in button, the site is not opening before the ongoing processes are completed. DEBUG option is False in deployment environment. We are not using django.contrib.staticfiles serve() function to serve our static files. How can I find the reason behind this delay? I suspect that this happens because static content are not being served with a different server? How can I make sure that this is the problem? If that is the problem, can serving the static files with a different virtual host solve the issue? Due to company policy, I cannot share the code directly here. However please let me know if there is any other information I need to elaborate. Thanks for your time and attention in advance. -
django-import-export does not export child class
I wanted to export the parent class of the models alongside with related child class included, but after exporting csv file, only data from parent class is present except for child class. I'm not sure what did I do wrong. class Membership(models.Model): name = models.CharField(max_length=128) email = models.EmailField() class References(models.Model): member = models.ForeignKey('Membership', on_delete=models.CASCADE, blank=True, null=True) name = models.CharField(max_length=128, blank=True, null=True) contact_details = models.CharField(max_length=128, blank=True, null=True) here's my resources.py class MemberResources(resources.ModelResources): reference_name = Field(attribute='name', widget=ForeignKeyWidget(References, 'name') class Meta: model = Membership admin.py class MembershipAdmin(ExportActionMixin, admin.ModelAdmin): resource_class = MemberResources admin.site.register(Member, MembershipAdmin) I attempted using ForeignKeyWidget but the reference_name is still blank even theres data inside the instance