Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError: 'str' object has no attribute '_meta' / Python 3.6
File "manage.py", line 15, in execute_from_command_line(sys.argv) File "C:\Users\INUSCG\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management__init__.py", line 364, in execute_from_command_line utility.execute() File "C:\Users\INUSCG\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\INUSCG\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\INUSCG\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 327, in execute self.check() File "C:\Users\INUSCG\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "C:\Users\INUSCG\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\commands\migrate.py", line 62, in _run_checks issues.extend(super(Command, self)._run_checks(**kwargs)) File "C:\Users\INUSCG\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\INUSCG\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\INUSCG\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\checks.py", line 25, in check_admin_app errors.extend(site.check(app_configs)) File "C:\Users\INUSCG\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\sites.py", line 81, in check errors.extend(modeladmin.check()) File "C:\Users\INUSCG\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\options.py", line 117, in check return self.checks_class().check(self, **kwargs) File "C:\Users\INUSCG\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\checks.py", line 526, in check errors.extend(self._check_list_filter(admin_obj)) File "C:\Users\INUSCG\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\checks.py", line 697, in _check_list_filter for index, item in enumerate(obj.list_filter) File "C:\Users\INUSCG\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\checks.py", line 697, in for index, item in enumerate(obj.list_filter) File "C:\Users\INUSCG\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\checks.py", line 740, in _check_list_filter_item get_fields_from_path(model, field) File "C:\Users\INUSCG\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\utils.py", line 500, in get_fields_from_path parent = get_model_from_relation(fields[-1]) File "C:\Users\INUSCG\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\utils.py", line 451, in get_model_from_relation return field.get_path_info()[-1].to_opts.model File "C:\Users\INUSCG\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\fields\related.py", line 723, in get_path_info opts = self.remote_field.model._meta AttributeError: 'str' object has no attribute '_meta' I am facing this Error on python 3.6, I got this error when i migrate my django project -
Django: Cannot Update the Value of IntegerField
I have an IntegerField in my model and I try to update it in the admin page. No matter what value I input (e.g. 100, 200), the value is restored to 0 after saving it. models.py class inputform(models.Model): ... age = models.IntegerField('Age', blank=True, null=True) ... I have tried change the value via SQL in the database directly and it updated successfully. However, when I read it in the admin page and saved it without any change, the value restore to 0. Is there any wrong with my code? Thanks! -
Making field required = False on ModelForm
I've got a model of UserCoupon that a user can create and edit. Upon edit, I only want them to be able to edit the 'code' field on the instance of UserCoupon if there are no orders associated with that code. When there are orders associated with that coupon code, rather than outputting {{form.code}} on the edit coupon form, I'm outputting {{form.instance.code}}. When the user attempts to submit the form, I get an error saying that the field is required. How can I make this field not required or otherwise address this situation so that the user can submit the form when one of the fields defined for the model form shows up in the template as an instance of the field rather than an input box? Models.py class UserCoupon(models.Model): code = models.CharField(max_length=15, unique=True) amount = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) forms.py class EditUserCouponForm (forms.ModelForm): class Meta: model = UserCoupon def __init__(self, *args, **kwargs): self.user = kwargs.pop('user',None) super(EditUserCouponForm, self).__init__(*args, **kwargs) def clean(self): cleaned_data = super(EditUserCouponForm, self).clean() template {% if coupon_order_count > 0 %} {{form.instance.code}} {% else %} {{form.code}} {% endif %} Thanks! -
Django Unittest mockset patching doens't always work
I wrote the following unit test, which succeeds when I run it individually via the VSCode IDE / unit test browser. api\test\test_views.py: class ProductListViewTest(APITestCase): def test_get_products(self): mock_products = MockSet() mock_products.add(MockModel( mock_name='e1', prod_id='1') # hit the API endpoint client = APIClient() with patch('api.models.Product.objects', mock_products): response = client.get(reverse('product-list')) # expected result expected = [ { 'prod_id': '1', } ] serialized = ProductSerializer(expected, many=True) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data, serialized.data) api\views.py: from api.models import Product class ProductViewSet(viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer api\urls.py: # ... path('product/', views.ProductListView.as_view(), name='product'), # ... However, as soon as I run it by python manage.py test, it fails, because response.data is an empty array - which probably means it is quering the empty test_ database and not the patched object. I tried to patch with patch('api.views.Exception.objects', mock_products): instead of with patch('api.models.Exception.objects', mock_products): but then the unittest fails in both cases. -
inilah 13 cara menggugurkan kandungan yang paling banyak di minati 082226222691
Info Konsultasi Wa : 082226222691, Inilah 12 Obat aborsi di jakarta Yang Paling Banyak Di Minati, Jual 13 Jenis Dan Merk Obat Aborsi Di Kota Bandung Provinsi Jawa Barat, klinik terpecaya untuk : menggugurkan kandungan , Tersedia juga : jamu penggugur kandungan, cara menggugurkan kandungan dengan paracetamol, cara menggugurkan kandungan 1 bulan, obat terlambat haid , cara menggugurkan kehamilan , penggugur kandungan, semua akan teratasi jika anda memesan obat, janin 1 bulan, cara menggugurkan , cara mengatasi telat haid, cara menggugurkan kandungan 100 berhasil, Kami Menberikan Pelayanan Semaksimal Mungkin Dengan Pengalaman Kami, cara gugurin kandungan, cara menggugurkan janin, cara menggugurkan hamil muda, cara menggugurkan kandungan 2 bulan, telat datang bulan 1 bulan, cara gugurkan kandungan, cara menggugurkan kandungan 2 minggu, makanan penggugur kandungan, penyebab telat datang bulan selama 2 bulan, cara aborsi, sitotek, cara menggugurkan kandungan 4 bulan, Mengggurkan kandungan alias aborsi sering diidentikkan dengan mengakhiri kehamilan yang tidak diinginkan cara menggugurkan kandungan usia 1 bulan, Jangan Untuk Juga Menonton video aborsi, cara menggugurkan kandungan dengan cepat, cara menggugurkan bayi, cara menggugurkan kandungan 1 minggu, kandungan 3 bulan, cara menggagalkan kehamilan, cara menggugurkan kandungan secara tradisional, Jangan Membeli Produk Di Warung-Warung Untuk Obat Telat Bulan Anda, kenapa bodrex dan sprite … -
TypeError: Direct assignment to the reverse side of a related set is prohibited. Use order_items.set() instead
I have Ordel model in my project models.py class Order(models.Model): order_id = models.CharField(max_length=50, unique=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True, related_name='orders') total = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='order_items') product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='order_items') quantity = models.PositiveIntegerField(null=True, blank=True, default=1) serializers.py class OrderSerializer(serializers.ModelSerializer): order_items = serializers.StringRelatedField(many=True, required=False) class Meta: model = Order fields = ['id', 'user', 'total', 'order_items'] def create(self, validated_data): return Order.objects.create(**validated_data) class OrderItemSerializer(serializers.ModelSerializer): class Meta: model = OrderItem fields = ['id', 'order', 'product', 'quantity'] finally views.py class OrderViewSet(viewsets.ModelViewSet): queryset = Order.objects.all() serializer_class = OrderSerializer def perform_create(self, serializer): try: purchaser_id = self.request.data['user'] user = User.objects.get(pk=purchaser_id) except: raise serializers.ValidationError( 'User was not found' ) cart = user.cart for cart_item in cart.items.all(): if cart_item.product.inventory - cart_item.quantity < 0: raise serializers.ValidationError( 'We do not have enough inventory of ' + str(cart_item.product.name) + \ 'to complete your purchase. Sorry, we will restock soon' ) total_aggregated_dict = cart.items.aggregate(total=Sum(F('quantity')*F('product__price'),output_field=FloatField())) order_total = round(total_aggregated_dict['total'], 2) order = serializer.save(customer=user, total=order_total) order_items = [] for cart_item in cart.items.all(): order_items.append(OrderItem(order=order, product=cart_item.product, quantity=cart_item.quantity)) cart_item.product.available_inventory -= cart_item.quantity cart_item.product.save() OrderItem.objects.bulk_create(order_items) cart.items.clear() def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) when send Post request to the url /orders/ it throws error … -
Visual studio code breakpoint set to grey color & not working.error(may be excluded because of "justMyCode" option)
I have set breakpoint in Django core library in visual studio code but when I am starting debugging of my project , those debug point color changed from red to grey & show me notification like below. Breakpoint in file excluded by filters. Note: may be excluded because of "justMyCode" option (default == true). I have set justmycode value to false from visual code option but still I am not able to set breakpoint. Even I have read SO question related but not able to solve my issue so I have to post my question. I have tried to set localroot & remoteroot but not working even. -
How to update history record in Django?
I got question about Django history. When I am in admin and change something in database, it will make an record in history of that object, that I made it or I update some record of that specific object. When I paste the data to database through some form (when the user is log in), it will not make an record in history. I also tried to update value and it works fine but it will not make and record in history, that this and this was changed... Can someone help me how to do it please? What should I add to this part of code? t = Pool.objects.get(pk=Pools_id) t.Status = "New" t.save() return HttpResponseRedirect('#') -
Django - change datafield on database
i am creating a real estate website in Django. I want users to insert/delete images for their properties. It´s all working as expected, except the delete images. In my views.py i have the code: listing = Listing.objects.get(id=1511) if listing: listing.photo_5 = None listing.save(['photo_5']) return True photo_5 is an Imagefield and i want to change the value of that field in database to None. I am saving the image to media folder and save the url in database. photo_5 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) Then when the user clicks in trash can icon, i have an ajax request (working and receives response from view) to delete the image from database. But there is the problem, i am not able to update the url in database or to delete. I already tried with update Listing.objects.all().filter(id = 1511).update(photo_5 = None) It seems that i can not change the value of photo_5. Why is not changing? -
is it bad to have en directory in locale? is there any use for it?
the main language is English for my website, some tutorials suggest to use django-admin makemessages -a and others suggest to use django-admin makemessages -l -de but when i use -a it make the en-us directory as shown below and it seems pretty much useless or is it? it there any merit for having a en-us directory for a website with English as it's main Lang? or should i just delete it? . ├── db.sqlite3 ├── some_industry ├── locale │ ├── en_us │ │ └── LC_MESSAGES │ │ └── django.po │ └── de │ └── LC_MESSAGES │ └── django.po ├── machine_request │ ├── __init__.py │ ├── admin.py │ ├── locale │ │ ├── en_us │ │ │ └── LC_MESSAGES │ │ │ └── django.po │ │ └── de │ │ └── LC_MESSAGES │ │ └── django.po │ ├── migrations │ ├── static │ │ └── machine_request │ ├── templates │ ├── urls.py ├── manage.py └── users ├── __init__.py ├── admin.py ├── locale │ ├── en_us │ └── de └── views.py -
why is form.is_valid returns false?with this error?
what is this error???? <ul class="errorlist"><li>username<ul class="errorlist"><li>This field is required.</li></ul></li><li>password<ul class="errorlist"><li>This field is required.</li></ul></li></ul> -
Removing Brackets from itertools combination list results
I have this code import itertools import random def gen_reset_key(): key = random.randint(100, 199) return key key_combinations = list(itertools.combinations(str(gen_reset_key()), 2)) key_one = key_combinations[0] key_two = key_combinations[1] key_three = key_combinations[2] print("Key one is: {}".format(key_one)) print("Key two is: {}".format(key_two)) print("Key three is: {}".format(key_three)) The output is: Key one is: ('1', '9') Key two is: ('1', '9') Key three is: ('9', '9') I want to remove the brackets and speech marks from the output. How can I achieve that? so that my output would be: Key one is 19 Key two is 19 Key three is 99 -
Django admin site customization
\models class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, related_name='+', on_delete=models.CASCADE,null=True) School_Year = models.ForeignKey(SchoolYear, on_delete=models.CASCADE, null=True, blank=True) Courses = models.ForeignKey(Course, on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, on_delete=models.CASCADE, null=True,blank=True) Payment_Type = models.ForeignKey(PaymentType, related_name='paymenttype', on_delete=models.CASCADE, null=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='gradelevel', on_delete=models.CASCADE,null=True) Discount_Type = models.ForeignKey(Discount, on_delete=models.CASCADE,null=True) Remarks = models.TextField(max_length=500,null=True) def __str__(self): suser = '{0.Student_Users} {0.Education_Levels}' return suser.format(self) what i want to search class StudentsEnrolledSubject(models.Model): Students_Enrollment_Records = models.ForeignKey(StudentsEnrollmentRecord, related_name='+', on_delete=models.CASCADE,null=True) Subject_Section_Teacher = models.ForeignKey(SubjectSectionTeacher, related_name='+', on_delete=models.CASCADE,null=True) def __str__(self): suser = '{0.Students_Enrollment_Records} {0.Subject_Section_Teacher}' return suser.format(self) Can i search here if i select what ever i want in section, my search will appear below? do you guys have an idea or better solution? -
UserSocialAuth model for shopify not able to create while performing authentication using python social_core shopify library
My aim is to get access token from shopify so that i can create webhook.I am using https://github.com/python-social-auth/social-core library to authenticate. Though i am able to navigate to shopify store admin section but i am not able to get "access token" from shopify.Generally UserSocialauth is the object which is having model attributes "extra_data" which gives access token but when i am going to shell of Django to list UserSocialAuth.objects.all().There is no model created for shopify app.Any Help https://github.com/python-social-auth/social-core/blob/master/social_core/backends/shopify.py -
Foreign Key column with keys from different models
Lets say I have 4 models, A, B, C, X A contains A1,A2,...An (similarly B and C) I have an object in X, say X1 which is related to an object from category either A, B or C. I have a column in X's model as category. How can I relate it to different models of A, B and C? If this cannot be done with a single column, what is the best way to implement this? Sorry for asking a noob question. Thanks in advance :) -
Password reset email not sending
I have a dynamic email configuration so that i customize the PasswordResetView like this to use my dynamic email .But this is not working properly . ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it [17/Oct/2019 14:49:42] "POST /password-reset/ HTTP/1.1" 500 148748 I think i need to pass this backend like this email = EmailMessage(.....,connection=backend) but i got stuck here.how can i do this here ? Any idea or solution for this? Is this approach is correct or not ? Any help would be great. form_class = EmailValidationOnForgotPassword but this form_class is working fine but email is not sending urls.py path('password-reset/', CustomPasswordResetView.as_view(),name='password_reset'), views.py class CustomPasswordResetView(PasswordContextMixin, FormView): config = EmailConfig.objects.order_by('-date').first() backend = EmailBackend(host=config.email_host, port=config.email_port, username=config.email_host_user, password=config.email_host_password, use_tls=config.email_use_tls) email_template_name = 'app/password_reset_email.html' extra_email_context = None form_class = EmailValidationOnForgotPassword from_email = config.email_host_user html_email_template_name = None subject_template_name = 'app/password_reset.html' success_url = reverse_lazy('password_reset_done') template_name = 'app/password_reset.html' title = 'Password Reset' token_generator = default_token_generator @method_decorator(csrf_protect) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) def form_valid(self, form): opts = { 'use_https': self.request.is_secure(), 'token_generator': self.token_generator, 'from_email': self.from_email, 'email_template_name': self.email_template_name, 'subject_template_name': self.subject_template_name, 'request': self.request, 'html_email_template_name': self.html_email_template_name, 'extra_email_context': self.extra_email_context, } form.save(**opts) return super().form_valid(form) INTERNAL_RESET_SESSION_TOKEN = '_password_reset_token' -
Return file as a download in Django Python
I have made a site using Django and I have made a function that returns an autogenerated pdf from database data. To make the PDF I use pyFPDF. pdfreport = FPDF() #Code for the PDF here pdfreport.output(name='mypdf.pdf') With this code everything works well, the PDF is correctly generated. But in order to return the file as an HTTP Response, I save the file with dest='S' and make the response. pdf = pdfreport.output(dest='S') response = = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="mypdf.pdf"' return(response) Using this, the response is correct and I got the file to save, the browser load the file as a pdf, but the pdf is blank. And I don't know why this happen. I have tried saving the file, open the file with open() and attach its content, but I still got the same result, a blank pdf. pdfreport.output(name=pdfname) pdf = open(pdfname, 'r') response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="mypdf.pdf"' return(response) Anyone that could help me? -
Deploying django project in cloudfoundry
I am new to django. I have a django project with multiple application. My project name is : DCMS_API. Procfile web: gunicorn DCMS_API.wsgi:application My manifest.yml: --- applications: - name: facility path: ./facility - name: connect_DB path: ./connect_DB buildpacks: - https://github.com/cloudfoundry/apt-buildpack.git - https://github.com/cloudfoundry/python-buildpack.git env: ACCEPT_EULA: Y i am trying to host it in cloudfoundry. i am uploading using following commands: cf login -a ****.com -u @.com -o DJANGO Cf target -s Development cf push But in cloudfoundry it is hosting as multiple applications different URL. facility.*****.com & connect_DB.*****.com How do we add a single project? like *****.com/facility & *****.com/connect_DB Not sure how to put it as. giving a same domain name/ URL, just adding the application name at the end rather than hosting 2 separate application or hosting the project. -
Single Sign On with Django and Salesforce
I'm trying to implement SSO between my Django app (the identity provider) and Salesforce (the service provider). My app is supposed to send SAML assertions to Salesforce. I have generated a self-signed certificate with which I'm build the SAML assertion (the xml tree). I configured my Salesforce SSO settings and uploaded the public certificate I previously generated on my local machine. Now when I try to validate the xml tree (or the base64 encoded version of it), I get this error in their UI which I can't pass because the error is very obscure and doesn't tell me much about the root of the problem. My guess is that Salesforce can't read the certificate part of the XML I'm sending, but I don't know why. Has anyone seen this before? -
Switched from Django Server to Apacher Server and RUINED my layout
The layout(using bootstrap) was perfect when I deployed my blog using the Django server as is. But, when I turned of the Django server and switched it to the Apache2 server, the format got completely ruined. I am not sure how the format was affected by me switching to an Apache2 server. Everything else remains the same except I had to make sure the I was correctly pointing to the static files right? Messed up version The Correct version2 I followed an amazing youtube tutorial to a tee, but still nothing. Here is the Apache configuration I used, as per the youtube video(Of course, I made sure to change the YOURUSER/YOURPROJECT to the correct location on my server) Alias /static /home/YOURUSER/YOURPROJECT/static <Directory /home/YOURUSER/YOURPROJECT/static> Require all granted </Directory> Alias /media /home/YOURUSER/YOURPROJECT/media <Directory /home/YOURUSER/YOURPROJECT/media> Require all granted </Directory> <Directory /home/YOURUSER/YOURPROJECT/YOURPROJECT> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/YOURUSER/YOURPROJECT/YOURPROJECT/wsgi.py WSGIDaemonProcess django_app python-path=/home/YOURUSER/YOURPROJECT python-home=/home/YOURUSER/YOURPROJECT/venv WSGIProcessGroup django_app -
Django coding - Why is it necessary to pass two separate arguments?
I am looking to add email account verification in Django and found a nice open source code that I can adopt. But there is one line which I'm not familiar with. Why does the function "password_reset_confirm" need to return two **kwargs in separate brackets and how each of them is used in the class "PasswordResetConfirm"? This question might be related to Python rather than Django. But anyway, thank you for your help! urls.py url(r"^password/reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za- z]{1,13}-[0-9A-Za-z]{1,20})/$",views.password_reset_confirm, name="reset- password-confirm",) views.py from django.contrib.auth import views as django_views class PasswordResetConfirm(django_views.PasswordResetConfirmView): template_name = "account/password_reset_from_key.html" success_url = reverse_lazy("account:reset-password-complete") token = None uidb64 = None def form_valid(self, form): response = super(PasswordResetConfirm, self).form_valid(form) account_events.customer_password_reset_event(user=self.user) return response def password_reset_confirm(request, uidb64=None, token=None): kwargs = { "template_name": "account/password_reset_from_key.html", "success_url": reverse_lazy("account:reset-password-complete"), "token": token, "uidb64": uidb64, } return PasswordResetConfirm.as_view(**kwargs)(request, **kwargs) -
Docker-compose service exited with code 0
I'm quite new to Docker. I'm trying to run Django on Docker. Following is my docker-compose file. version: '2' services: django: build: context: . dockerfile: ./deploy/dev/Dockerfile tty: true ports: - "8000:8000" volumes: - ./app:/src/app depends_on: - "workflow_db" - "rabbitmq" env_file: - ./deploy/dev/envvar.env workflow_db: image: postgres:9.6 volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=hello_django - POSTGRES_PASSWORD=hello_django - POSTGRES_DB=hello_django rabbitmq: image: "rabbitmq:3-management" hostname: "rabbitmq" environment: RABBITMQ_ERLANG_COOKIE: "SWQOKODSQALRPCLNMEQG" RABBITMQ_DEFAULT_USER: "rabbitmq" RABBITMQ_DEFAULT_PASS: "rabbitmq" RABBITMQ_DEFAULT_VHOST: "/" ports: - "15672:15672" - "5672:5672" volumes: postgres_data: DockerFile FROM python:3.7-alpine RUN apk update && apk add --no-cache gcc libffi-dev g++ python-dev build-base linux-headers postgresql-dev postgresql postgresql-contrib pcre-dev bash alpine-sdk \ && pip install wheel #Copy over application files COPY ./app /src/app #Copy over, and grant executable permission to the startup script COPY ./deploy/dev/entrypoint.sh / RUN chmod +x /entrypoint.sh WORKDIR /src/app #Install requirements pre-startup to reduce entrypoint time RUN pip install -r requirements.txt ENTRYPOINT [ "/entrypoint.sh" ] And finally my entrypoint.sh ! /bin/bash cd /src/app || exit echo "PIP INSTALLATION" && pip install -r requirements.txt echo "UPGRADE" && python manage.py migrate # echo "uwsgi" && uwsgi "uwsgi.ini" I do django-compose up, it builds the image, but django_1 exited with code 0. However, if I uncomment the last line of entrypoint.sh, it runs … -
ReverseManyToOne create object from children through django form
Using: Python 3.7.3 django 2.2.5 mysql 5.7.27 I have the following models: class Item(models.Model): ... class Comments(models.Model): Item = models.ForeignKey('Item', default=None, null=True, on_delete=models.SET_DEFAULT) Comment = models.TextField(max_length=512, default="", blank=True) I would like to create a Comments object, when creating the Item through a django form. I tried to do: class ItemInsertForm(forms.ModelForm): ... Comments = forms.CharField(required=False, widget=forms.Textarea(attrs={'placeholder':"Use comments to describe item details \ or issues that other users should know", 'rows':5, 'cols':50, } ) ) def clean_Comments(self, *args, **kwargs): _comment = self.cleaned_data.get('Comments') _comments = Item.comments_set.create(Comment=_comment) return _comments but I get the following error: 'ReverseManyToOneDescriptor' object has no attribute 'create' Both tables are empty, so no Item and no Comments currently exist. I guess that's why there is no 'create' method available. Is there a way I could achieve what I want? Or is there another way to manage the comments for the Item object? I created another table to be able to associate multiple comments to the same item and differentiate between them. A character field in the Item class would concatenate all comments in a single string. -
"Failed to establish a new connection" when trying to access Elasticsearch Cloud with elasticsearch-dsl Python package
I'm experimenting with Elasticsearch and indexing some Django data using the elasticsearch-dsl Python package. I have created a relatively basic test, search.py, but receive a connection error when I try to index any data. from elasticsearch_dsl.connections import connections from elasticsearch_dsl import Document, Text from elasticsearch.helpers import bulk from elasticsearch import Elasticsearch from . import models connections.create_connection(hosts=['ELASTICSEARCH_ENDPOINT_URL'], http_auth='USERNAME:PASSWORD') class MyIndex(Document): title = Text() description = Text() class Index: name = 'my-index' def bulk_indexing(): MyIndex.init() es = Elasticsearch() bulk(client=es, actions=(a.indexing() for a in models.MyModel.objects.all().iterator())) When I run bulk_indexing() I get the following error: elasticsearch.exceptions.ConnectionError: ConnectionError(<urllib3.connection.HTTPConnection object at 0x1282266d8>: Failed to establish a new connection: [Errno 61] Connection refused) caused by: NewConnectionError(<urllib3.connection.HTTPConnection object at 0x1282266d8>: Failed to establish a new connection: [Errno 61] Connection refused) I suspect the syntax is wrong or I am missing some credentials when creating a connection, but I cannot find any further information. I am using Elasticsearch v7.4.0 deployed using Elastic Cloud. I can connect when I access the URL via my browser. -
I want to know a good way to implement pagination within a modal
I would like to apply pagination within the modal so that only 20 posts per page are displayed. How can I implement a pagination view? Can you recommend a good example or resource? Can't I ask this question? I'll erase this question if it matters