Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why can't django's reverse() match an email parameter?
I'm using a DRF ViewSet to manage user accounts: class UserViewSet(ModelViewSet): lookup_field = 'email' queryset = User.objects.all() And have a testcase like: from django.urls import reverse from .base import BaseApiTestCase class UsersTestCase(BaseApiTestCase): def test_get_user_account(self): # ...Create a test user, login as test user... response = self.client.get( reverse('api:users-detail', kwargs={'email': 'test@user.com'}), content_type='application/json' ) self.assertStatusCode(response, 200) I get the error: django.urls.exceptions.NoReverseMatch: Reverse for 'users-detail' with keyword arguments '{'email': 'test@user.com'}' not found. 2 pattern(s) tried: ['api/users/(?P<email>[^/.]+)\\.(?P<format>[a-z0-9]+)/?$', 'api/users/(?P<email>[^/.]+)/$'] It's my understanding that the [^/.]+ regex should match test@user.com. Although reverse() should do this for me, I've also tried url-encoding the @ symbol, as in: reverse('api:users-account', kwargs={'email': 'test%40user.com'}), Running manage.py show_urls reveals that the URL is available: ... /api/users/<email>/ api.views.users.UserViewSet api:users-detail ... Why can't django's reverse() system find the url match? -
Django - Accessing Foreign Key values to save to dictionary
In Django, I would like to create a dictionary from model values which also include the Foreign Key values. So, for example, I have 2 models: --models.py-- class Item(models.Model): item_name = models.CharField(max_length=255) item_description = models.CharField(max_length=255) class Inventory(models.Model): inventory_name = models.CharField(max_length=255) inventory_date = models.DateTimeField(default=timezone.now) inventory_item = models.ForeignKey(Item, on_delete=models.DO_NOTHING) (not the best variable name examples since it could be a many to many relationship, but you get the point) In my urls, I need a path that shows the primary key because I will have some other functions based their pks from the URL. --urls.py-- urlpatterns = [ path('details/ < int : pk > /', views.GenerateDetails, name='details'), ] Now, here's were I'm having issues. I'm trying to create a dictionary from the Inventory model that will also have the ForeignKey values from Item. --views.py-- class GenerateDetails(View): def get(self, request, *args, **kwargs): inventory_data = Inventory.objects.get(pk=self.kwargs.get('pk')) # Create dictionary from selected contract_data inventory_data_dict = model_to_dict(inventory_data) ... return response From this solution, the only ForeingKey value that the dictionary saves is Item__id and that's it. I would like the dictionary to save all the data for Inventory as well as Item__name and Item__description. -
Error with Django Postgis DB as default backend
I am new to development generally and django. Currently I have the error below when I use the 'python manage.py runserver' command after changing Default Database Engine on setting to "'ENGINE': 'django.contrib.gis.db.backends.postgis'" cannot import name 'GDALRaster' from 'django.contrib.gis.gdal' What can I do. Please find picture below; error message -
Counting model field dynamically?
Is it possible to count a model field dynamically in django. I have tried using override save model but this is not dynamic: class MyAdminView(admin.ModelAdmin): def save_model(self, request, obj, form, change): super(MyAdminView, self).save_model(request, obj, form, change) Models.py class ClientProfile(models.Model): name=models.CharField(max_length=200) organization=models.CharField(max_length =150) email=models.EmailField(max_length =150) country= models.CharField(max_length =150) state=models.CharField(max_length =150) publish=models.BooleanField(default =True) active = models.CharField(max_length =150) present=models.CharField(max_length =150) I want to the present field to count the number of times a name(specific) to a user is mention and the active to count the publish field related to a user with name(specific) -
i just wanted to pass seperate fields to template via render, i tried deserializing but it didnt work, help will be really appreciated
here is my get function im sending whole serialized object to template which not letting me use fields seperately in template @api_view(['GET']) def get_employee(request): emp = employee.objects.all() serializer = employeeSerializer(emp, many=True) return render(request,'employee/employee_details.html',{'json_obj': serializer.data}) -
Need help to solve complex sql query with django queryset
I need help to translate a sql query to a django queryset... I have tried many things but nothing that can solve it The query below is exactly what I need and it actually give me the result I expect. Can anyone help me on this case ? SELECT DISTINCT on (name) * FROM my_table WHERE (name, job_result_id) = ANY( SELECT name, max(job_result_id) FROM my_table WHERE ticket != '' GROUP BY name, job_result_id) Thanks for your help -
Django rest framework: sendgird email with attachment without model only filefield to open file and send button to send email
I am new on Stackoverflow. Don't know how to ask question. I am new on Django Rest Framework Also. I am trying to send email with attachment. Here is my code. *****model.py******* class EmailModel(models.Model): upload_file = models.FileField(upload_to='location/location/files', blank=False) class Meta: verbose_name = 'Applicant CSV Upload' verbose_name_plural = 'Applicant CSV Upload' *****admin.py***** @admin.register(EmailModel) class EmailAdmin(admin.ModelAdmin): class Meta: model = EmailModel *****View.py****** def send_email(): email = EmailMessage( 'Title', ('abc', 'abc@gmail.com', '123123123'), 'abc@gmail.com', ['abc@gmail.com'] ) email.attach_file(EmailViewSet.upload_file) email.send() class EmailViewSet(viewsets.ModelViewSet): queryset = EmailModel.objects.all() serializer_class = EmailSerializer def create(self, request, *args, **kwargs): send_mail(' Test Subject here', 'Test here is the message.', 'abc@gmail.com', ['abc@gmail.com'], fail_silently=False) response = super(EmailViewSet, self).create(request, *args, **kwargs) send_email() # sending mail data = [{'location': request.data.get('location'), 'image': file} for file in request.FILES.getlist('image')] serializer = self.get_serializer(data=data, many=True) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) message = EmailMessage(subject='Applicant data', body='PFA', from_email='abc@gmail.com', to='abc@gmail.com', bcc='abc@gmail.com', connection=None, attachments=data, headers=self.data, cc='abc@gmail.com', reply_to=None) # Attach file # with open(attachment, 'rb') as file: # message.attachments = [ # (attachment, file.read(), 'application/pdf') # ] return response, message.send(), Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) *****Serializer.py****** class EmailSerializer(serializers.ModelSerializer): class Meta: model = EmailModel fields = ('upload_file',) ******settings.py****** EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = 'apikey' # this is exactly the value 'apikey' EMAIL_HOST_PASSWORD = 'here i am using my sendgrid api … -
CreateView form is not "rendering" in a template tag
Setup I have successfully setup a CreateView class that allows user to create a Journal. You only have to enter the name and press the "Add" button. views.py ... class CreateToJournal(LoginRequiredMixin, CreateView): model = to_journal template_name = 'to_journals/to_journal_list.html' fields = ('journal_name',) def get_success_url(self): return reverse('to-journals') def form_valid(self, form): form.instance.journal_user = self.request.user return super(CreateToJournal, self).form_valid(form) def get_context_data(self, **kwargs): context = super(CreateToJournal, self).get_context_data(**kwargs) context['to_journals'] = to_journal.objects.filter(journal_user=self.request.user) return context ... to_journal_list.html ... <form class="" id="myForm" action="" method="post"> {% csrf_token %} {{ form }} <button type="submit" id="add-button">Add</button> </form> ... This creates a new Journal and reloads the page to reflect the changes made. I am now trying to move the whole Journal creation process to the "home" page, using a template tag. Mostly it works fine and renders all user journals on the home page, but there is a problem with form rendering. Problem The new template tag does not render the form created by CreateView. The input field is not displayed here on the page with a template tag. I couldn't find any specific information (or general, for that matter) regarding the relationship between forms and templatetags. My setup for the template tag is the following: ... ├───pages │ └───templatetags │ └───__init__.py │ … -
Read multiple rows of a column from an excel sheet and save it as a dictionary
someone please help me with these 2 questions, am new to python language! I have an excel file with columns as Bank Name, About, Products, Popular Products, Loans, Insurance, Cards and Banking. Final Updated Banksheet what i have done is read the excel file and updated its value to my database but the format in which i want my databse to look like for Product type should be something like this: {"'Account':['Savings','Current'], 'Loan':['Consumer Loan','Personal Loan','Housing Loan','Vehicle Loan','MSME Loan'], 'Maha eTrade Online Share Trading':None, 'Maha Mobile Banking':None, 'Internet Banking':None} but currently my data in database is populating like this: {"{'Account':['Savings','Current']}","{'Loan':['Consumer Loan','Personal Loan','Housing Loan','Vehicle Loan','MSME Loan']}","Maha eTrade Online Share Trading","Maha Mobile Banking","Internet Banking"} Here is my Code: def update_bank_data(): from loans.models import BankData filename = 'filecontainer/ifscdata/Final Updated Banksheet.xlsx' exist =0 if os.path.isfile(filename): print("file exists") exist = 1 if exist: xl_workbook = xlrd.open_workbook(filename) print("------------new file=-----------------------") print(filename) sheet_names = xl_workbook.sheet_names() print('Sheet Names', sheet_names) j = 1 for sheet in sheet_names: xl_sheet = xl_workbook.sheet_by_name(sheet) no_of_row = xl_sheet.nrows + j print no_of_row next_bank_row_num=None currnt_bank_row_num=None j=1 try: while (j < no_of_row): if next_bank_row_num: currnt_bank_row_num = next_bank_row_num print("current bank----->", xl_sheet.cell_value(currnt_bank_row_num, 0)) else: currnt_bank_row_num = j print("current bank----->", xl_sheet.cell_value(currnt_bank_row_num, 0)) j = j + 1 while (xl_sheet.cell_value(j, 0) == … -
get ibject id with kwargs in drf
I have hardcoded one object that is wrong in my case. But I am facing some problems with solving this issue. I have a model looks like this class ProductCategory(MPTTModel): name = models.CharField(max_length=50, unique=True) parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True) is_top = models.BooleanField(default=False) class Cart(models.Model): product = models.ForeignKey(Product, related_name='product') size = models.ForeignKey(Size, related_name='size') count = models.IntegerField() order = models.ForeignKey(Order, blank=True, null=True, related_name='cart_items') is_free = models.BooleanField(default=False) and I have method: def transaction_saver(sender, instance, **kwargs): if kwargs['created']: cafe = instance.order.cafe order = instance.order order.state = Order.PAID order.save() customer = order.customer # name = ProductCategory.objects.get(category_id=kwargs.get('name')) total_count = order.cart_items.filter(is_free=False, product__category__name='Coffee/Tea').aggregate(Sum('count')) if total_count['count__sum'] is not None: count__sum = int(total_count['count__sum']) project_modules.point_free_item_calculation(cafe=cafe, client=customer, count=count__sum) clearly, here I have a product category that is named like 'Coffee/Tea' in this category I have many products. Now when customer buys a product from this category it should give one point to that user. But I have hardcoded this product__category__name='Coffee/Tea'. Unfortunately, it is wrong because I do not have only this category I have also other categories and to give point for other categories I cannot always change the code I should make it automate. How can I solve this problems? Any help please? Thank you in advance! -
Connection Django to MySql
I've created a new database. After that I created a new user and password CREATE USER 'new_user'@'localhost' IDENTIFIED BY 'new_password'; then to grant all access to the database GRANT ALL ON my_db.* TO 'new_user'@'localhost'; FLUSH PRIVILEGES; But then I run python manage.py runserver I got File "/home/y700/Env/pro/local/lib/python2.7/site-packages/MySQLdb/connections.py", line 166, in __init__ super(Connection, self).__init__(*args, **kwargs2) MySQLdb._exceptions.OperationalError: (1044, "Access denied for user 'new_user'@'localhost' to database 'my_db'") What am I doing wrong? -
Pre-loader won't register on refresh
I am using Python and Django to modify a website, I'm using bootstrap 4 as well. I am attempting to change the preloaded currently in use (the typical circle spinner). I have entered the preloader within my html file, my css file, and made a custom.js file to support the loader yet when I refresh the page the loader shows the standard circle. (I have deleted the previous spinner files and style code but for some reason it still shows when I use "div id=preloader" Here is my preloader css style. #preloader { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background-color: #f5f5f5; /* change if the mask should be a color other than white */ z-index: 1000; /* makes sure it stays on top */ } .pre-container { position: absolute; left: 50%; top: 50%; bottom: auto; right: auto; -webkit-transform: translateX(-50%) translateY(-50%); transform: translateX(-50%) translateY(-50%); text-align: center; } .spinner { width: 40px; height: 40px; position: relative; margin: 100px auto; } .double-bounce1, .double-bounce2 { width: 100%; height: 100%; border-radius: 50%; background-color: #53dd6c; opacity: 0.6; position: absolute; top: 0; left: 0; -webkit-animation: bounce 2.0s infinite ease-in-out; animation: bounce 2.0s infinite ease-in-out; } .double-bounce2 { -webkit-animation-delay: -1.0s; animation-delay: -1.0s; } @-webkit-keyframes … -
__init__() takes 1 positional argument but 2 were given: Multiple Inheritance
PLEASE READ THE QUESTION FIRST BEFORE MARKING IT AS DUPLICATE! This question is asked by many but almost all gave the same solution which I am already applying. So I have classes TestCase,B,C & D. Classes B & C inherit class TestCase & class D inherits both B & C. When I ran my code, class D was only running with methods for class B and ignoring C all along. Then I found this answer regarding multiple inheritance and tried to apply it in my code. Now my classes go like these from django.test import TestCase class B(TestCase): def __init__(self): super(B, self).__init__() class C(TestCase): def __init__(self): super(C, self).__init__() class D(B, C): def __init__(self): super(D, self).__init__() But when I try to run it, it says TypeError: __init__() takes 1 positional argument but 2 were given Why is it happening? How to fix this? Is the answer I am following right? Will this fix make D run for both B & C? This seems like a Python question mainly but tagging django too as TestCase class might have something to do with it. -
How to dynamically set value for a field in django
I'm building dynamic sorting of django query.I added additional column to sort on, like so: class MyModel(models.Model): order_column = models.IntegerField() class Meta: ordering = ('order_column',) and now need to update its value accordingly on every change / sort action. Right now I do it the following way: def some(self): my_query = MyModel.objects.all() my_list = list(my_query) pop_index = 4 insert_index = 2 obj = my_list[pop_index] my_list.insert(insert_index, obj) for i, item in enumerate(my_list): item.order_column = i item.save() It works, but I don't like the save in for-loop. I know that to update query one can call query.update, so I tried: my_query.update(order_column=lambda x: images_list.index(x)) But it doesn't work. Is there a way to achieve this in a single expression like update? -
How can I change django admin template?
I've written a blog website with Django and now I want to change the Django adminstrator themplate.. -
Form fields not appearing in add pages of django admin page
within my admin.py, I register a few models, and within those registered models, I define a few fields, such as a search field. The fields show up in the 'change' section of the model, but they do not appear in the 'add' section of the model admin page. Overall what I am trying to accomplish is to have a filter on the add page of my model AuthGroupFilePermissions, such that when a user is adding an auth group file permission, they don't have to look through a long list of filepatterns (over 1000, so it's extremely unfriendly). The key is actually Filepattern_id and it is a foreign key to another model. I have tried overriding the formfield_for_foreingkey method, as well as using filter_vertical and filter_horizontal @admin.register(models.AuthGroupFilePermissions) class AuthGroupFilePermissions(admin.ModelAdmin): list_filter = ('group', ) search_fields = ['file_pattern__filename_pattern'] filter_vertical = ('file_pattern',) def formfield_for_foreignkey(self, db_field, request, **kwargs): print2(kwargs) if db_field.name == 'file_pattern': kwargs['queryset'] = models.CentralFeedInfo.objects.filter(filename_pattern__icontains='') return super().formfield_for_foreignkey(db_field, request=request, **kwargs) class Media: js = ('/static/admin/js/filepattern_search.js',) So really I am having two issues. One, the fields that I am adding to modelAdmin are not showing up in the model admin, and two, I am not sure how to add a filter to the add page, similar … -
Environment variables are not being read in django/docker environment
I am running a dockerized django app and would like to pass my AWS credentials into my settings.py. So I set my environment variables in my .bash_profile and then in settings.py I do: os.getenv[AWS_ACCESS_KEY_ID]. I also tried os.environ[...]. When I enter my shell for debugging I get: /usr/local/lib/python3.6/os.py in __getitem__(self, key) 667 except KeyError: 668 # raise KeyError with the original key value --> 669 raise KeyError(key) from None 670 return self.decodevalue(value) So i figure the environment variable is None, thus is not read. Is that a problem with docker/bash? I mean that it is not accessible? Or should it be? Or do I have to set it in my Dockerfile? If so, how? Any hint or help is very much appreciated! Thanks in advance! -
Limited usage of voucher code (maximum 3 times) without being bound to an user
I want to generate voucher codes with limited usage up to maximum 3 times without being bound to a user. views.py: class ApplyFormView(FormView): template_name = 'vouchers/apply.html' model = Voucher form_class = VoucherApplyForm def get_success_url(self): voucher = get_object_or_404(Voucher, pk=self.kwargs['voucher_id']) discount_value = voucher.value discount_type = voucher.get_type_display() messages.add_message(self.request, messages.INFO, "Congratulations! You've successfully redeemed %s" " %s off the selected item(s)." % ( discount_value, discount_type, )) return reverse('vouchers:apply', kwargs={'voucher_id': self.kwargs['voucher_id']}) def form_valid(self, form): self.code = self.cleaned_data['code'] form.apply_voucher() return super(ApplyFormView, self).form_valid(form) class VoucherDetailView(generic.DetailView): template_name = 'vouchers/detail.html' model = Voucher def get_context_data(self, **kwargs): context = super(VoucherDetailView, self).get_context_data(**kwargs) context['redemption_form'] = VoucherApplyForm(initial={'voucher':self.object}) return context def redeem(request, voucher_id): voucher = get_object_or_404(Voucher, pk=voucher_id) try: redeemed_voucher = voucher.redemption.get(pk=request.POST['voucher']) except (KeyError, Voucher.DoesNotExist): return render(request, 'vouchers/detail.html', { 'voucher': voucher, 'error_message': "Voucher is invalid.", }) else: redeemed_voucher.redemption += 1 redeemed_voucher.save() return HttpResponseRedirect(reverse('vouchers:apply', args=(voucher.id,))) urls.py: from django.urls import path from . import views app_name = 'vouchers' urlpatterns = [ path('<int:pk>/', views.VoucherDetailView.as_view(), name='detail'), path('<int:voucher_id>/apply/', views.ApplyFormView.as_view(), name='apply'), path('<int:voucher_id>/redeem/', views.redeem, name='redeem'), ] models.py: class Voucher(models.Model): code = models.CharField(max_length=30, unique=True) valid_from = models.DateTimeField() valid_to = models.DateTimeField() value = models.IntegerField(default=10) VOUCHER_TYPES = ((0, 'money-based discount, in RM,'), (1, 'percent')) type = models.SmallIntegerField(("Type"), choices=VOUCHER_TYPES, default=0) usage_limit = models.PositiveIntegerField(("Usage limit"), default=3) active = models.BooleanField() def __str__(self): return self.code @property def due_to_expire(self): now … -
Why am I getting 'function upper(bytea)' error in python 3?
Currently I am working to convert my py-2 project in py-3 & during this conversion I have faced below kind of error. Partner.objects.filter(name__iexact = name_kv).count() When I am running above query in py2 it working perfectly & getting output '0', means getting empty list. When I am running above query in py3 it showing below kind of error. django.db.utils.ProgrammingError: function upper(bytea) does not exist LINE 1: ...alse AND UPPER("partners_partner"."name"::text) = UPPER('\x4... ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. I have searched lot online & SO other questions but but not able to find any solution. I figured out that it must have been python version problem & I am getting above error when my ORM query does not have any records. -
Stripe subscription creates duplicate payment
I've created a stripe subscription using Django/Stripe SDK and since the software is in Europe it used the new SCA (Strong Customer Authentication). So first I attach the source to customers and then I try to subscribe them, it works but for certain customers I am seeing duplicated payments on Stripe control panel. I've contacted Stripe and their customer support recommended the following but I couldn't figure it out: I see what you mean when you say the customers are being charged more than once. The issue boils down to the API call requesting them to be added to a subscription is being sent more than once to Stripe from your server. To solve this on your end, you will need to make sure your system is sending a request only once. I would recommend checking your server to see where the requests are coming from. It may be an easy solve on that end once this is determined. @login_required def PaymentView(request): profile = Profile.objects.filter(user=request.user).first() try: address = profile.address.get(address_type="home") except: address = None user_membership = get_user_membership(request) try: selected_membership = get_selected_membership(request) except: return redirect(reverse("membership:select")) publishKey = settings.STRIPE_PUBLISHABLE_KEY if request.method == "POST": # try: source = request.POST.get('stripeSource', "") amend = request.POST.get('amend', '') … -
CVAT Installation on Kubernetes
Using v0.5.1 from the GitHub repo (https://github.com/opencv/cvat), I've pulled it down locally, built and tagged it, and pushed it up to a local docker registry. When I try to deploy it on a kubernetes instance from the registry I get the following error in the pod logs: Error: Format string '%(ENV_HOME)s/wait-for-it.sh db:5432 -t 0 -- bash -ic \\n"/usr/bin/python3 ~/manage.py migrate && \\n/usr/bin/python3 ~/manage.py collectstatic --no-input && \\nexec /usr/bin/python3 $HOME/manage.py runmodwsgi --log-to-terminal --port 8080 \\n--limit-request-body 1073741824 --log-level INFO --include-file ~/mod_wsgi.conf \\n%(ENV_DJANGO_MODWSGI_EXTRA_ARGS)s --locale %(ENV_LC_ALL)s"' for 'program:runserver.command' contains names ('ENV_DJANGO_MODWSGI_EXTRA_ARGS') which cannot be expanded. Available names: ENV_CUDA_SUPPORT, ENV_CVAT_PORT, ENV_CVAT_PORT_8080_TCP, ENV_CVAT_PORT_8080_TCP_ADDR, ENV_CVAT_PORT_8080_TCP_PORT, ENV_CVAT_PORT_8080_TCP_PROTO, ENV_CVAT_PORT_8443_TCP, ENV_CVAT_PORT_8443_TCP_ADDR, ENV_CVAT_PORT_8443_TCP_PORT, ENV_CVAT_PORT_8443_TCP_PROTO, ENV_CVAT_SERVICE_HOST, ENV_CVAT_SERVICE_PORT, ENV_CVAT_SERVICE_PORT_8080_TCP, ENV_CVAT_SERVICE_PORT_8443_TCP, ENV_DB2_PORT, ENV_DB2_PORT_50000_TCP, ENV_DB2_PORT_50000_TCP_ADDR, ENV_DB2_PORT_50000_TCP_PORT, ENV_DB2_PORT_50000_TCP_PROTO, ENV_DB2_PORT_55000_TCP, ENV_DB2_PORT_55000_TCP_ADDR, ENV_DB2_PORT_55000_TCP_PORT, ENV_DB2_PORT_55000_TCP_PROTO, ENV_DB2_PORT_60006_TCP, ENV_DB2_PORT_60006_TCP_ADDR, ENV_DB2_PORT_60006_TCP_PORT, ENV_DB2_PORT_60006_TCP_PROTO, ENV_DB2_PORT_60007_TCP, ENV_DB2_PORT_60007_TCP_ADDR, ENV_DB2_PORT_60007_TCP_PORT, ENV_DB2_PORT_60007_TCP_PROTO, ENV_DB2_SERVICE_HOST, ENV_DB2_SERVICE_PORT, ENV_DB2_SERVICE_PORT_50000_TCP, ENV_DB2_SERVICE_PORT_55000_TCP, ENV_DB2_SERVICE_PORT_60006_TCP, ENV_DB2_SERVICE_PORT_60007_TCP, ENV_DEXTR_MODEL_DIR, ENV_DJANGO_CONFIGURATION, ENV_HOME, ENV_HOSTNAME, ENV_KUBERNETES_PORT, ENV_KUBERNETES_PORT_443_TCP, ENV_KUBERNETES_PORT_443_TCP_ADDR, ENV_KUBERNETES_PORT_443_TCP_PORT, ENV_KUBERNETES_PORT_443_TCP_PROTO, ENV_KUBERNETES_PORT_53_TCP, ENV_KUBERNETES_PORT_53_TCP_ADDR, ENV_KUBERNETES_PORT_53_TCP_PORT, ENV_KUBERNETES_PORT_53_TCP_PROTO, ENV_KUBERNETES_PORT_53_UDP, ENV_KUBERNETES_PORT_53_UDP_ADDR, ENV_KUBERNETES_PORT_53_UDP_PORT, ENV_KUBERNETES_PORT_53_UDP_PROTO, ENV_KUBERNETES_SERVICE_HOST, ENV_KUBERNETES_SERVICE_PORT, ENV_KUBERNETES_SERVICE_PORT_DNS, ENV_KUBERNETES_SERVICE_PORT_DNS_TCP, ENV_KUBERNETES_SERVICE_PORT_HTTPS, ENV_LANG, ENV_LC_ALL, ENV_NGINX_REVERSEPROXY_PORT, ENV_NGINX_REVERSEPROXY_PORT_8080_TCP, ENV_NGINX_REVERSEPROXY_PORT_8080_TCP_ADDR, ENV_NGINX_REVERSEPROXY_PORT_8080_TCP_PORT, ENV_NGINX_REVERSEPROXY_PORT_8080_TCP_PROTO, ENV_NGINX_REVERSEPROXY_PORT_8443_TCP, ENV_NGINX_REVERSEPROXY_PORT_8443_TCP_ADDR, ENV_NGINX_REVERSEPROXY_PORT_8443_TCP_PORT, ENV_NGINX_REVERSEPROXY_PORT_8443_TCP_PROTO, ENV_NGINX_REVERSEPROXY_SERVICE_HOST, ENV_NGINX_REVERSEPROXY_SERVICE_PORT, ENV_NGINX_REVERSEPROXY_SERVICE_PORT_8080_TCP, ENV_NGINX_REVERSEPROXY_SERVICE_PORT_8443_TCP, ENV_OPENVINO_TOOLKIT, ENV_PATH, ENV_REID_MODEL_DIR, ENV_TERM, ENV_TEST_UI_PORT, ENV_TEST_UI_PORT_8080_TCP, ENV_TEST_UI_PORT_8080_TCP_ADDR, ENV_TEST_UI_PORT_8080_TCP_PORT, ENV_TEST_UI_PORT_8080_TCP_PROTO, ENV_TEST_UI_SERVICE_HOST, ENV_TEST_UI_SERVICE_PORT, ENV_TEST_UI_SERVICE_PORT_8080_TCP, ENV_TF_ANNOTATION, ENV_TF_ANNOTATION_MODEL_PATH, ENV_TZ, ENV_USER, ENV_WITH_DEXTR, ENV_http_proxy, ENV_https_proxy, ENV_no_proxy, ENV_socks_proxy, group_name, here, host_node_name, process_num, program_name in section 'program:runserver' (file: 'supervisord.conf') For help, … -
How can I get the latest date using Django?
Hello I have this query : myObject.objects.filter(id=id, date=date).distinct('start').order_by('start') In my table I have only as fields : id, date, start and end. date, start and end are datetime type. The problem is that I would like to get in the end the latest date not a random date when I did the distinct on the field start. How can I do this ? Thank you very much ! -
Convert amount to word in Python In Indian Format
Would you help me to convert amount to word in Indian? Previously I was using num2words library but its is presenting wrong set of words while presenting 'lakhs' and 'crores'. For example: num2words(903614.55, lang='en-IN') Its printing 'nine hundred and three thousand, six hundred and fourteen point five five' But actual Indian Amount Presentation should be nine lakhs three thousand six hundred fourteen and five five paisa. Then, I tried the below code: def num2words(num): under_20 = ['Zero','One','Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten','Eleven','Twelve','Thirteen','Fourteen','Fifteen','Sixteen','Seventeen','Eighteen','Nineteen'] tens = ['Twenty','Thirty','Forty','Fifty','Sixty','Seventy','Eighty','Ninety'] above_100 = {100: 'Hundred',1000:'Thousand', 100000:'Lakhs', 10000000:'Crores'} if num < 20: return under_20[num] if num < 100: return tens[(int)(num/10)-2] + ('' if num%10==0 else ' ' + under_20[num%10]) # find the appropriate pivot - 'Million' in 3,603,550, or 'Thousand' in 603,550 pivot = max([key for key in above_100.keys() if key <= num]) return num2words((int)(num/pivot)) + ' ' + above_100[pivot] + ('' if num%pivot==0 else ' ' + num2words(num%pivot)) But now an error is coming TypeError : list indices must be integers or slices, not decimal.Decimal Any help is appreciatable Thank you -
ModuleNotFoundError: No module named 'companyname' with Django in docker container
I am getting an error about my module named "companyname" (fake name as to not reveal this project) despite the fact that it is in the folder with my Dockerfile. Here is my Dockerfile: FROM python:3.7 RUN apt-get update && apt-get upgrade -y && apt-get autoremove && apt-get autoclean RUN apt-get install -y \ libffi-dev \ libssl-dev \ default-libmysqlclient-dev \ libxml2-dev \ libxslt-dev \ libjpeg-dev \ libfreetype6-dev \ zlib1g-dev \ net-tools \ vim COPY * ./ RUN pip install -U pipenv RUN pipenv install --system EXPOSE 8000 STOPSIGNAL SIGINT ENTRYPOINT ["python3.7", "manage.py"] CMD ["runserver", "0.0.0.0:8000"] Here is my manage.py: #!/usr/bin/env python import os import sys import pymysql pymysql.install_as_MySQLdb() if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "companyname.settings.dev") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) And then there is a file that is located ./companyname/settings/dev.py from my Dockerfile - so ostensibly it should exist in my Docker image from the copy command. However when I run: docker run <image hash> I get: ModuleNotFoundError: No module named 'companyname' Why can't manage.py find my module? The same directory structure should be observed, correct? -
Make django-taggit-labels selectable on admin list view
I am using djang-taggit-labels for my project. The thing is that I can only select tags in the model edit view. I would like to make this list item editable on the main list view, so users do not have to click on the record but select tags on the list. I know how to make list_editable with model fields, which are not custom made, but I can't think off anything in this scenario. admin.py class YoutubeVideoAdmin(admin.ModelAdmin): form = YoutubeTagLabel model = YoutubeVideo list_display = ( 'admin_thumbnail', 'user', 'title', 'admin_url', 'published_at', 'description', # Categories are the tags. 'categories' ) list_editable = ['categories'] list_filter = ( ('user__user', admin.RelatedOnlyFieldListFilter), 'published_at', ('tags', custom_titled_filter('Category')), ) ordering = ('-published_at', ) search_fields = ('title', 'description', 'tags__name', ) readonly_fields = ('time_created', 'time_modified', 'user',) def admin_thumbnail(self, obj): if obj.thumbnail_url: return mark_safe('<img src="%s" height = "60"/>' % obj.thumbnail_url) else: return None def admin_url(self, obj): return mark_safe(f'<a href={obj.url} target="_blank"> {obj.url}</a>') def get_queryset(self, request): return super().get_queryset(request).prefetch_related('tags') # def categories populate tags def categories(self, obj): return u", ".join(o.name for o in obj.tags.all()) forms.py class YoutubeTagLabelsWidget(LabelWidget): tags = TagField(required=False, widget=LabelWidget) class YoutubeTagLabel(forms.ModelForm): tags = TagField(required=False, widget=YoutubeTagLabelsWidget) models.py class YoutubeVideo(TimeStampedModel): user = models.ForeignKey(YoutubeUser, on_delete=models.CASCADE) title = models.TextField() url = models.URLField() published_at = models.DateTimeField() description …