Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
pest practice in for loop
1- in the code below I get an error name should be unique because there is a loop in for... def test_new_user_email_normalized(self): """Test email is normalized for new users.""" sample_emails = [ ["test1@EXAMPLE.com", "test1@example.com"], ["Test2@Example.com", "Test2@example.com"], ["TEST3@EXAMPLE.com", "TEST3@example.com"], ["test4@example.COM", "test4@example.com"], ] for email, expected in sample_emails: user = get_user_model().objects.create_user(email, name, "sample123") self.assertEqual(user.email, expected) I fixed the problem by editing the code to be like that def test_new_user_email_normalized(self): """Test email is normalized for new users.""" sample_emails = [ ["test1@EXAMPLE.com", "test1@example.com"], ["Test2@Example.com", "Test2@example.com"], ["TEST3@EXAMPLE.com", "TEST3@example.com"], ["test4@example.COM", "test4@example.com"], ] n = 1 # new for email, expected in sample_emails: n = n + 1 # new name = "name" + str(n) # new user = get_user_model().objects.create_user(email, name, "sample123") self.assertEqual(user.email, expected) and here is my question did I do it right as the best practice or anything else or there is a better way like in my question 2 for example? 2- can I add my condition in "for" itself like for email, expected in sample_emails and n in range(1,5): -
Django-cron library does not seems to work?
my project.settings.py CRON_CLASSES = ["user_statistic_status.cron.UserLoginCronJob",] my user_statistic_status.cron.py class UserLoginCronJob(CronJobBase): # checking if the user has taken a class in the last 24 h RUN_EVERY_MINS = 1 # every 2 hours schedule = Schedule(run_every_mins=RUN_EVERY_MINS) code = 'user_statistic_status.UserLoginCronJob' def do(self, request): today: date = timezone.now().date() print(f"Today's date is {today}") My app is registered in the settings.py When I run python manage.py runcrons I get : Running Crons ======================================== [✘] user_statistic_status.UserLoginCronJob Can anyone help out here, not sure why my task is not being triggered at all as I don't get the print() call -
How to properly set Passkeys for Django?
I'm trying to apply Passkeys to a Django project, but I'm new to both and am finding difficulties. So following instructions I found here on how to add Passkeys I'm supposed to the following code to my settings.py file: AUTHENTICATION_BACKENDS = \['passkeys.backend.PasskeyModelBackend'\] # Change your authentication backend FIDO_SERVER_ID="localhost" # Server rp id for FIDO2, it the full domain of your project FIDO_SERVER_NAME="MTGStore" import passkeys KEY_ATTACHMENT = NONE | passkeys.Attachment.CROSS_PLATFORM | passkeys.Attachment.PLATFORM NONE is not a keyword in Python though, so I've tried using None but that gave me a TypeError: unsupported operand type(s) for *: 'NoneType' and 'AuthenticatorAttachment' error. Also thought I am using localhost for my server ID, I'm not sure what to add for my authentication backend. What am I missing? Thanks! -
Query set to count all records on secondary table in ManyToMany relationship in Django Templates
How to count the total number of readers associated with each book in the index.html file? The first loop loops through readers and provides a sum for the number of books associated with each reader. The second loop does not count the number of books a reader has read (I understand why). I'm trying to count the total number of readers associated with each book. Is there a way to complete this task within the index.html file? Or should this be done in views.py? -
cronjob is failing to send email in production server whereas in localhost it is working fine
I'm working on a project in which a reminder email has to be sent whenever the scheduled time is met. For example, if the reminder date and time is set to the Dec17, 6am. then the email has to be sent automatically on Dec17, 6am. This works fine in my local host without any issue, But when I deploy it in production environment the auto email is not getting sent. `def my_scheduled_job(): try: if settings.RUN_SCHEDULER: utc = pytz.utc ist = pytz.timezone('Asia/Calcutta') json_data = {} tickets = Ticket.objects.filter(is_active = True).exclude(state_history__state__item = 'Completed') for rem in tickets: for dt in rem.reminder.all(): ind_utc = datetime.today() + timedelta(hours=5, minutes=30) remainder_date = dt.date_time d1 = datetime.strptime(remainder_date.strftime('%Y-%m-%d %H:%M:%S'), '%Y-%m-%d %H:%M:%S') d2 = datetime.strptime(ind_utc.strftime('%Y-%m-%d %H:%M'), '%Y-%m-%d %H:%M') if d1 == d2: to_addr, obj_cnt = [], rem.reminder.count() filt_cnt = rem.reminder.filter(id__gte = dt.id).count() if obj_cnt == filt_cnt: if rem.users.all(): for user in rem.users.all(): user_name = User.objects.values_list('username',flat=True).get(id=user.id) to_addr.append(user_name) else: for group in rem.groups.all(): users = User.objects.filter(groups__id=group.id) for user in users: to_addr.append(user.username) to_addr = list(set(to_addr)) json_data['tickets'] = rem # json_data['urlObject'] = base.HOSTNAME html = render_to_string('email/cronjob.html', json_data) mail = mail_function('sending mail from FMS', to_addr, html) cron_logger.info("-------Scheduled mail sent to assigned user-----") elif (obj_cnt-1) == filt_cnt: if rem.users.all(): for user in rem.users.all(): user_name … -
How to solve CSRF verification faileld?
Request aborted. Help Reason given for failure: Origin checking failed - https://teamsparrowpp-qrgen-production 6a43.up.railway.app does not match any trusted origins. I have <form method="POST">{% csrf_token %} on my html. I have tried adding on settings CSRF_TRUSTED_ORIGINS = ['https://teamsparrowpp-qrgen-production-6a43.up.railway.app'] But it's not working. -
Django Apache and name-based VirtualHost
I have recently locally deployed Django project on Apache server Fedora 36. Everything work good when accessing site by ip. The issue that could not access it by hostname. I am getting "Bad Request (400)" error. here my httpd.conf <VirtualHost *:80> ServerName calljournal.local alias /static /var/www/django_project/call_journal/static <Directory /var/www/django_project/call_journal/static> Require all granted </Directory> <Directory /var/www/django_project/call_journal> Require all granted </Directory> WSGIDaemonProcess calljournal.local python-path=/var/www/django_project/virt/lib/python3.8/site-packages WSGIProcessGroup calljournal.local WSGIScriptAlias / /var/www/django_project/call_journal/call_journal/wsgi.py redirect / https://192.168.1.109 </VirtualHost> and my hosts file ::1 localhost localhost.localdomain localhost6 localhost6.localdomain6 192.168.1.109 calljournal.local -
Subquery in Django ORM
I have following models. My goal is to extract 2 recent Comments per Post. Is that possible? class Post(models.Model): author = models.ForeignKey(Author, related_name="posts", on_delete=models.CASCADE) title = models.CharField(max_length=256) text = models.TextField(blank=True, default="") created_at = models.DateTimeField(default=datetime.now, blank=True) @property def comments_number(self): return self.comments.count() def __str__(self, *args, **kwargs): return f"{self.title}" class Comment(models.Model): post = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE) author = models.ForeignKey(Author, related_name="comment", on_delete=models.CASCADE) text = models.TextField() created_at = models.DateTimeField(default=datetime.now, blank=True) The closest try I've got is this one: newest = Comment.objects.filter(post=OuterRef('pk')).order_by('-created_at') recent_comments = Post.objects.annotate(newest_comments=Subquery(newest.values('text')[:2])) And than when I call recent_comments.values_list() I can see the newest one comment per Post obj (only one) but this is not what I want exactly. I have spend a lot of time on it guys and have no clue... -
Multiple Django Projects using IIS but Getting Blank Page on Second Site
I'm running two django projects in IIS with wfastcgi enabled. The first django project is running without an issue but the second project displays a blank page (code 200) returned. Second Project Info: A virtual folder, within it's own application pool in IIS, is created to host the second project. The second project was created in an python environment folder. The second project runs from django using python manage.py runserver 0.0.0.0:8080, but displays a blank page when browsing to the virtual folder page. The root folder was granted with "everyone" full control access to all sub-folders for the second project, wfastcgi application and handler is pointing to the virtual environment python and wfastcgi file correctly. Can you have two wfastcgi applications and handlers "Second Python FastCGI" C:\project_folder\project_env\Scripts\python.exe|C:\project_folder\project_env\lib\site-packages\wfastcgi.py" I wanted them separate so that two developers don't interfere with each others work, but they need to run within the same server and port. -
Django queryset filter with if condition?
I want to write conditions for fields in a model in Django filter. but i don't know how to do it.I try but it doesn't work views.py telefonS = MateryalEkle.objects.filter( eklenmeTarihi__range=(baslangicTarihi, bitisTarihi), dosyaBilgileriBaglanti__durum="ŞUBEDE", (islemDurumu="İŞLEM BEKLİYOR" or islemDurumu="GELEN" ) and exportDurumu = "" ).values('cinsi').annotate(Count('cinsi')) models.py class MateryalEkle(models.Model): cinsi = models.CharField(max_length=50, choices=MATERYALCINSI, verbose_name='MATERYAL CİNSİ') islemDurumu = models.CharField(max_length=50, choices=ISLEMDURUM, verbose_name='İşlem Durumu', default='İŞLEM BEKLİYOR') exportDurumu = models.CharField(max_length=50, choices=EXPORTDURUM, verbose_name='Export Durumu', blank=True) imajTuru = models.CharField(max_length=50, choices=IMAJTURU, verbose_name='İmaj Türü', blank=Tru -
I'm creating update in model using django framework pthon and facing issue of page not found 404
Using the URLconf defined in BVH.urls, Django tried these URL patterns, in this order: -
Django - How to display a list friend requests
I am currently following a guide on making friends in Django and stumbled upon a problem. As i am fairly new to Django and Python, i am unsure of to display a list of friend requests that has been to a user. I am following this guide https://medium.com/analytics-vidhya/add-friends-with-689a2fa4e41d and i have tried to implement the for loop in Step 5 part 2 as they stated that they can display a list of all friend requests. However, i can not seem to display anything and they have not shown their code on how to do so. Here is my friend_request function in views.py in an attempt to try and gather all friend requests. All my other code are the same as guide previously linked above. So if possible, can anyone guide me on how to display all friend requests that are sent to a user? def friend_requests(request, requestID): all_friend_requests = FriendRequest.objects.get(to_user=requestID) context = { 'all_friend_requests': all_friend_requests } return ('/', context) -
running django project on another pc
I am using mysql as the database of the django project, mysql is installed on the computer I will install, but after the migrate process on the other computer I installed, an error comes up and only django does its own migrate process, the models in my models.py files do not pass to the database. ?:(mysql.w002) MariaDB Strict Mode is not set for database connection 'default' HINT: MariaDB's strict mode fixes many data intergity problems in mariadb, such as data truncation upon insertion,by escalating warnings into errors. It is strongly recommended you active it see: https://docs.djangoproject.com/en/ref/databases/mysql-sql-mode enter image description here -
quickbooks-api did not recognize attribute auth
I recently update may Django app which is connected to quickbooks to python 3.9.16. Due to this change, I've an issue : QuickBooks' object has no attribute 'auth_client': My code is : try: auth_client = AuthClient( client_id=CLIENT_ID, client_secret=CLIENT_SECRET, environment=ENV, redirect_uri=REDIRECT_URI, ) except Exception as exc: logging.info('log credentials SELECT Errors: {} - {}'.format(companyId, exc)) chek = 'Nok' # creating the client object to access the QBO account - if not able to connect, make 3 tries dans then stop if chek != 'Nok': tries = 1 logging.info('Trying to connect to QBO') for i in range(tries): try: client = QuickBooks( auth_client=auth_client, refresh_token=REFRESH_TOKEN, company_id=COMPANY_ID, ) # get the refresh token returned refresh_token_new = client.auth_client.refresh_token Error is on last lign. seems that it does not understand: client.auth_client in requirements.txt I have (extract): sqlalchemy intuit-oauth python-quickbooks pandas unidecode gunicorn without version infos.So should be last version -
Javascript file is not working on templates in django?
Static setting is right?My javascript file is not running in django templates? Tried using static file setting and loading static before tags -
How to filter objects by value of one of its fields in django?
I have django application with urls.py: path('<str:slug>/', views.article), When user types name of product in my website, the view is triggered: def article(request, slug): videos = models.Video.objects.filter(article=slug) return render(request, 'videos/at_detail.html', {'videos': videos}) If I add print(slug) somewhere in function it returns the word I entered in url, so this part works. models: class article(models.Model): name = models.CharField(max_length=30, null=True) slug = AutoSlugField(populate_from='name', unique=True, default=None) created_on = models.DateTimeField(default=timezone.now) owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, default=None) def __str__(self): return self.name class Meta: verbose_name = "Articles" class Video(models.Model): video_id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False ) title = models.CharField(max_length=50) description = models.CharField(max_length=500) file = models.FileField() article = models.ForeignKey(at, on_delete=models.CASCADE) def __str__(self): return str(self.title) + " - " + str(self.at) class Meta: verbose_name_plural = "Videos" verbose_name = "Video" What doesn't work, and what I'm trying to do, is to get all objects, which have same value 'article', that what I entered in my url. So for example: if I type 127.0.0.1:8000/blueberry/ I will get all objects with field article=blueberry. Is this possible and if it is, how can I do that? -
Django template is rendering in Multi-step form, but context data is not visible
I am working on this problem and somehow resolved it to a very great extent and almost everything is done. But the Django is rendering my template but not the Context. I don't know why I have checked it by debugging and my context is rendering but not showing in frontend. On this template, there is a form with 4 fieldset , I am submitting data in 1st fieldset and the dynamically show o/p accordingly on the second fieldset. I am attaching screenshot to show what is rendering in template(2nd fieldset) before submitting After submitting #views.py def createQuotePage(request): if request.method == "POST": # Getting all the value # saving in Table saveInUnitsTable(-------some code, removed to shorten question ------) saveInCustomerTable(-------some code, removed to shorten question ------) saveInInquiryTable(-------some code, removed to shorten question ------) flight_suggestions =Flight.objects.filter(sourceairportid=1,destinationairportid=51) context = {'flight_suggestions':flight_suggestions,"test":"99999999999999999999999999999999999999"} return render(request,"Freight/create_quote.html",context=context) # <-- here is the PROBLEM if request.method == "GET": print("========================GET=======================") context = {'airport_data' : list(Airport.objects.all()), 'commodity_data':list(Commodity.objects.all()), 'customerType_data':list(Entity.objects.all()), } return render(request,"Freight/create_quote.html",context=context) #scripts.js (function($) { "use strict"; $.backstretch; $('#top-navbar-1').on('shown.bs.collapse', function(){ $.backstretch("resize"); }); $('#top-navbar-1').on('hidden.bs.collapse', function(){ $.backstretch("resize"); }); $('.f1 fieldset:first').fadeIn('slow'); $('.f1 .btn-next').on('click', function() { // var parent_fieldset = $(this).parents('fieldset'); var next_step = true; var current_active_step = $(this).parents('.f1').find('.f1-step.active'); var progress_line = $(this).parents('.f1').find('.f1-progress-line'); // var formData1 … -
Why not use "authentication.views import *" to prevent typing "views." before every call in urls.py?
Why not use: from django.urls import path from authentication.views import * urlpatterns = [ path('login/', login_view, name='auth.login'), } Instead of: from django.urls import path from authentication import views urlpatterns = [ path('login/', views.login_view, name='auth.login'), } I couldn't find much information about it. -
JsTree invisible after reload the page
I have a button to create first node in jstree after submit that form page reload and jstree not visible. **JS:** $(document).on("click", "#templatename", function() { let templatename = $(".template_name").val(); let csr = $("input[name=csrfmiddlewaretoken]").val(); mydata = { templatename: templatename, csrfmiddlewaretoken: csr }; $.ajax({ url: '/templatename/', type: "POST", data: mydata, success: function (data) { let template_name = data.data createJSTree(template_name) }, error: function (e) { console.error(e) } }); }); function for creating jstree: function createJSTree(template_name) { $('#jstree_template').jstree({ "core": { "themes": { "responsive": false }, "check_callback": true, 'data': template_name, }, "types": { "default": { "icon": "fa fa-folder text-primary" }, "file": { "icon": "fa fa-file text-primary" } }, "state": { "key": "demo2" }, "plugins": ["contextmenu", "state", "types"], "contextmenu": { "items": function ($node) { var tree = $("#jstree_template").jstree(true); return { "Create": { "separator_before": false, "separator_after": true, "label": "Create", "action": function (obj) { for (let i = 0; i<template_name.length; i++){ debugger obj_id = obj.reference[0].id.split('_')[0] obj_hastag = obj.reference[0].href.split('/')[3] data_id= `${template_name[i].id}` data_hastag = `${template_name[i].parent}` obj_id_hastag = obj_id + obj_hastag data_id_hastag = data_id + data_hastag if(obj_id_hastag == data_id_hastag) { $('#template_modal').modal('show'); } else if(obj.reference[0].id.split('_').slice(0,2).join('_') == `${template_name[i].id}`){ $('#mode_modal').modal('show'); } else if(obj.reference[0].id.split('_').slice(0,2).join('_') == `${template_name[i].id}_anchor`){ $('#mode_modal').modal('show'); } } } }, "Rename": { "separator_before": false, "separator_after": false, "label": "Rename", "action": function (obj) { tree.edit($node); } … -
Patch Django EmailMultiAlternatives send() in a Celery Task so that an exception is raised
I want to test a Celery Task by raising an SMTPException when sending an email. With the following code, located in: my_app.mailer.tasks from django.core.mail import EmailMultiAlternatives @app.task(bind=True ) def send_mail(self): subject, from_email, to = 'hello', 'from@example.com', 'to@example.com' text_content = 'This is an important message.' html_content = '<p>This is an <strong>important</strong> message.</p>' msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") try: msg.send(fail_silently=False) except SMTPException as exc: print('Exception ', exc) and then running the following test against it: class SendMailTest(TestCase): @patch('my_app.mailer.tasks.EmailMultiAlternatives.send') def test_task_state(self, mock_send): mock_send.side_effect = SMTPException() task = send_mail.delay() results = task.get() self.assertEqual(task.state, 'SUCCESS') The email is sent without error. However, if I turn the task into a standard function (my_app.mailer.views) and then run the following test against it: class SendMailTest(TestCase): @patch('myapp.mailer.views.EmailMultiAlternatives.send') def test_task_state(self, mock_send): mock_send.side_effect = SMTPException() send_mail(fail_silently=False) The string 'Exception' is displayed, but there is no exc information as to what caused the exception. Please, what am I doing wrong? -
How to Close a Modal properly with jquery or javascript from within the injected HTML?
Script to Call Modal, and HTML Skeleton for Modal: (which is working) <script> $(document).on("click", ".addworker", function (e) { e.preventDefault(); var $popup = $("#popup"); var popup_url = $(this).data("popup-url"); $(".modal-content", $popup).load(popup_url, function () { $popup.modal("show"); }); }); </script> <div id="popup" class="modal fade" role="dialog"> <div class="modal-dialog modal-lg"> <div class="modal-content"> </div> </div> </div> The HTML loaded into modal-content is returned by a django view which sits behind the url. (this part is working too) Inside this HTML i have the Button, which i want to use to then close the modal again. But when the Modal got injected with the HTML and is open, it seems like the modal is out of scope, so i tried to get it back with var $popup = $("#popup");. And i indeed get back the Object, but the $popup.modal("hide"); Method doesnt work. <script> $(document).on("click", ".cancel", function (e) { var $popup = $("#popup"); $popup.modal("hide"); }); </script> <div class="modal-header"> <h1>{{ aoe }} Worker: {{ id }}</h1> </div> <form action="add/" method="post"> {% csrf_token %} <div class="modal-body"> {{ form|crispy }} </div> <div class="modal-footer"> <input type="button" class="btn btn-secondary cancel" value="Cancel"> <input type="submit" class="btn btn-primary" value="Submit"> </div> </form> -
How to run selenium in Docker with Flask?
My goal is to run Selenium with Flask. The problem is that it throws an error. [2022-12-16 11:30:05 +0000] [1] [INFO] Starting gunicorn 20.1.0 [2022-12-16 11:30:05 +0000] [1] [INFO] Listening at: http://0.0.0.0:8080 (1) [2022-12-16 11:30:05 +0000] [1] [INFO] Using worker: sync [2022-12-16 11:30:05 +0000] [6] [INFO] Booting worker with pid: 6 [WDM] - Downloading: 100%|██████████| 6.96M/6.96M [00:00<00:00, 12.6MB/s] [2022-12-16 11:30:07 +0000] [6] [ERROR] Exception in worker process Traceback (most recent call last): File "/usr/local/lib/python3.10/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker worker.init_process() File "/usr/local/lib/python3.10/site-packages/gunicorn/workers/base.py", line 134, in init_process self.load_wsgi() File "/usr/local/lib/python3.10/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi self.wsgi = self.app.wsgi() File "/usr/local/lib/python3.10/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/usr/local/lib/python3.10/site-packages/gunicorn/app/wsgiapp.py", line 58, in load return self.load_wsgiapp() File "/usr/local/lib/python3.10/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp return util.import_app(self.app_uri) File "/usr/local/lib/python3.10/site-packages/gunicorn/util.py", line 359, in import_app mod = importlib.import_module(module) File "/usr/local/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/app.py", line 2, in <module> from scrapeutil import get_db File "/scrapeutil.py", line 14, in <module> driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()), … -
Seperaet the response in DRF
Im returning the summary of orders in which order_total, order_number ,quantity and the payment is repeated but I only want it to be shown one time. Like all the products should be the one only in nested serializer response and other should be shown singly without any repetition #Serializer class OrderSummarySerializer(ModelSerializer): product = ProductSerializer() payment = PaymentSerializer() order_number = SerializerMethodField() order_total = SerializerMethodField() class Meta: model = OrderProducts fields = ["order_number", "payment", "product", "quantity", "order_total"] def get_order_total(self, obj): return obj.order.order_total def get_order_number(self, obj): print(obj) return obj.order.order_number #Views class OrderSummary(APIView): def get(self, request): try: order_number = request.GET.get("order_number") orders = Orders.objects.get(user=request.user, order_number=order_number) order_summary = OrderProducts.objects.filter( user=request.user, order__order_number=order_number, is_ordered=True ) context = { "request": request, } serializer = OrderSummarySerializer( order_summary, many=True, context=context ) return Response(serializer.data, status=status.HTTP_200_OK) except Exception as e: print(e) return Response( {"error": "Something went wrong"}, status=status.HTTP_400_BAD_REQUEST #Response I get [ { "order_number": "ypVtT1", "payment": { "payment_method": "cod", "amount_paid": "", "status": "Pending", "created_at": "2022-12-16T16:46:30.915646+05:30" }, "product": { "id": 1, "product_name": "Pendant1", "sub_product_name": null, "slug": "pendant-1", "highest_offer_price": 250.0, "category_offer_discount": 1250.0, "product_offer_discount": 2250.0, "base_price": 2500, "stock": 5, "is_available": true, "product_image": "http://127.0.0.1:8000/media/photos/products/pendant3.webp" }, "quantity": 1, "order_total": 2170.0 }, { "order_number": "ypVtT1", "payment": { "payment_method": "cod", "amount_paid": "", "status": "Pending", "created_at": "2022-12-16T16:46:30.915646+05:30" }, "product": { "id": … -
How to change position of endpoints in drf-yasg Django
I'm trying to customize drf api documentation with drf-yasg. I want to change order of display endpoints. For example to change: GET /endpoint/number1/ GET /endpoint/number2/ to GET /endpoint/number2/ GET /endpoint/number1/ in swagger document. How can I do that? -
mptt not linking children and parent - Django
I'm having an issue that I seriously can't wrap my head around. I am using Django MPTT models and evrerything seems to be working fine (i.e. I can run the migrations and insert data in the database), but for some reason the TreeForeignKey table and the TreeManyToManyField table are not linking in the database. Here are the models in question... from mptt.models import MPTTModel, TreeForeignKey, TreeManyToManyField class Category(MPTTModel): name = models.CharField( max_length=100, verbose_name=_('category name'), help_text=_('format: required, max=100'), ) slug = models.SlugField( max_length=150, verbose_name=_('category safe URL'), help_text=_('format: required, letters, numbers, underscore or hyphons'), ) is_active = models.BooleanField(default=True) parent = TreeForeignKey( 'self', on_delete=models.PROTECT, related_name='children', null=True, blank=True, ) class MPTTMeta: order_insertion_by = ['name'] class Meta: verbose_name=_('product category') verbose_name_plural=_('product categories') def __str__(self): return self.name class Product(models.Model): web_id = models.CharField( unique=True, max_length=50, verbose_name=_('product website ID'), ) slug = models.SlugField( max_length=255, verbose_name=_('product safe URL'), help_text=_('format: required, letters, numbers, underscore or hyphons'), ) name = models.CharField(max_length=150) description = models.TextField(help_text='Required') category = TreeManyToManyField(Category) is_active = models.BooleanField( default=False, verbose_name=_('product visibility'), ) created_at = models.DateTimeField( editable=False, auto_now_add=True, help_text=_('format: Y-m-d H:M:S'), ) updated_at = models.DateTimeField(auto_now=True, help_text=_('format: Y-m-d H:M:S')) def __str__(self): return self.name I'm following the documentation verbatum, and really I have no idea why this is not working... If anyone has …