Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
html div not setting to 100% in django-template
I am new to HTML. I am developing a web application using Django template, I am trying to set the height of the div to the maximum of its parent . The page is as follows: <!DOCTYPE html> <html> <head><title>Billing Lookup</title> <title>Billing Interface</title> </script> <style> html { height: 100%; } body { min-height: 100%; } .main{ height:100%; margin-left:100px; padding-top:10px; padding-left:80px; } </style> </head> <body> <div id="mm" class="main"> {% block content %} {% endblock %} </div> </body> </html> But when i browse this page in chrome or firefox, i see that the body and html is set to 100% covering the whole screen, but the div mm is not showing 100%. Am i missing something here? Screen shot pasted below Note: if i remove this tag <!DOCTYPE html>then I get the height of the div set to 100% which i don't understand. The same happens even in ordinary html file without django env Can anyone please help? Thanks -
Django admin how to create custom view to redirect to another model add view?
I have two models and I want to create a custom view which would redirect to another model add view. My models: class PostAdmin(admin.ModelAdmin): list_display = ['text', 'media', 'send_type', 'created'] class Meta: model = Post admin.site.register(Post, PostAdmin) and class ChannelAdmin(admin.ModelAdmin): list_display = ['title','invite_link', 'account_actions'] def my_custom_view(self, request, *args, **kwargs): !!!!HERE!!! class Meta: model = Channel admin.site.register(Channel, ChannelAdmin) I tried but for it I need self parametr from PostAdmin def my_custom_view(self, request, *args, **kwargs): return PostAdmin.add_view(self, request}) -
Docker: When should we get the variables from vault
I'm trying to use Vault with my Django project which is running on Docker. We had a dispute within the team regarding the place where/when should we get the variables from Vault and allow the application to access them. Let me explain two possible approaches that we discussed but I'm not sure which one is more preferable. When building the docker image, inside the Dockerfile ... RUN get_all_variables_from_vault CMD uwsgi --ini uwsgi.ini Inside the Application(Runtime instead of build-time in above option). This means, Image has been built and we are trying to spawn a container. and once the container is starting-up, we would get all the variables and export them as env variables before actually running the application. Docker image -> spawning the container -> get all variables from vault & export them as env variables -> start application I can understand a few pros/cons of both such as - Suppose vault is down or for some reason we are unable to communicate with Vault API, in that case, 1st option would not even allow us to build an image and hence the previous version of the application would keep running without affecting the end-user. in the 2nd option, it … -
django Testing views works only with a primary key
I am working on a django project. i have build the front end and back-end. now i want to write unit test. i want to test a class based view for creating,deleting and retrieving blog post from url '''path('posts/', Postview.as_view(),name="posts"),''' my Postview view is here: class Postview(views.APIView, LimitOffsetPagination): authentication_classes = [TokenAuthentication, ] permission_classes = [IsAuthenticated, ] def get(self, request, pk=None): if pk: try: query = Post.objects.filter(pk=pk) # print(query) print("in post get") serializer = PostSerializer( query, many=True, context={'request': request}) data = commonPost(serializer.data, request) return Response(data) except: return Response({"message": "No Data found"}) else: query = Post.objects.all().order_by('-id') serializer = PostSerializer( query, many=True, context={'request': request}) data = commonPost(serializer.data, request) return Response(data) def post(self, request, pk=None): if pk: snapshot = Post.objects.get(pk=pk) serializers = PostSerializer( snapshot, data=request.data, context={'request': request}) if serializers.is_valid(): serializers.save() return Response({'error': False}) return Response({'error': True}) else: serializer = PostSerializer( data=request.data, context={'request': request}) if serializer.is_valid(): serializer.save() return Response({'error': False}) return Response({'error': True}) def delete(self, request, pk): try: snippet = Post.objects.get(pk=pk) if snippet.profile.id == request.user.profile.id: snippet.delete() return Response({"error": False}) else: return Response({"error": True}) except: return Response({"message": "No data found for this ID"}) now my unit test def test_post_view(self): client=self.get_client() response=client.get("/api/posts/")# this line self.assertEqual(response.status_code,200) this test gives error of 401!=200 but if i change the url … -
Add Calculated Virtual Column to Django Model Queryset
I'm having a tough time trying to add a virtual column to my django model. My Store model has the following database fields: class Store(models.Model): time_opening = models.TimeField() time_closing = models.TimeField() How can I add an is_open field to the results of my Store queryset? The logic for the field is something like: time_opening <= datetime.now() <= time_closing I have attempted to use annotations in a StoreManager class but I'm not sure how to construct an expression with the logic mentioned above. class StoreManager(Manager): def get_queryset(self): return super().get_queryset().annotate(is_open=??????) I also wrote the raw sql as a backup which returns a virtual column is_open based on the desired logic. For example: SELECT Store.*, True as is_open; In this case, I'm unsure where to use my raw sql. Do I put it in the StoreManager get_queryset function? Do I call Store.objects.raw()? If so, where should I call it? How will it affect built-in django filtering and pagination? -
how to access the foreignkey value from a dict value in django
I am using foreignkey as my dropdown and I wanted to remove the dupicate values from my dropdown so I used query distinct(),but now i am getting dict values and I am not able to access my foreignkey value now. I am getting foreign key ID instead of string. I want to do something like for values in queryset: values.item_name.name my models.py class Requesition(models.Model): item_name = models.ForeignKey(Item,on_delete=models.CASCADE,limit_choices_to={'status':True}) date = models.CharField(max_length=20) quantity = models.IntegerField() requested_by = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) status = models.BooleanField(default=1) approved = models.BooleanField(default=0) def __str__(self): return '%s--%s' % (self.item_name.item_name, self.item_name.specification) my forms.py class Purchase_order(forms.ModelForm): products = forms.ModelChoiceField(queryset= Requesition.objects.all().select_related('item_name').values('item_name').distinct()) class Meta: model = Purchase fields=('__all__') exclude = ('status','select','Total') -
django rest model-view-set list action raise 404 if pass query parameter
if i pass any query parameter get 404 class BusinessViewSet(ModelViewSet): queryset = Business.objects.all() permission_classes = [IsAuthenticated, HasUsernamePermission] filter_backends = [SearchFilter, DjangoFilterBackend, DistanceFilterBackend] ordering_fields = ['name'] pagination_class = LimitOffsetPagination filterset_fields = ['name', 'category'] def get_serializer_class(self): if self.request.method == 'POST': return BusinessCreateSerializer return BusinessSerializer for example if i request /api/businesses/ response code is 200 but if i request /api/businesses/?search=a response code is 404 -
Django Save Unicode unescaped /u into MySQL Database
I'm having a problem when saving the unicode data without unescape /u. The data that got from the client was: {"text": "निम्न प्रश्नोंको हल"} However, when I saved it into the database (MySQL) it's changed into unescape unicode characters: {"text": "\u0928\u093f\u092e\u094d\u0928 \u092a\u094d\u0930\u0936\u094d\u0928\u094b\u0902\u0915\u094b \u0939\u0932"} Both my table and column already using utf8mb4_general_ci collation. I can paste the character into the table manually and it shows the real character. Here's my code: question = Questions() question.data = json.dumps(data, ensure_ascii=False) question.save() It shows fine on the browser, but it makes an issue when I want to export the data into JSON later on. -
Connecting Django Celery Beat to the correct database
I am getting started with celery (4.4.7) using this tutorial. I believe I have set up everything correctly but whenever I run the following command: celery -A myproj beat -l INFO --scheduler django_celery_beat.schedulers:DatabaseScheduler I get the error: django.db.utils ProgrammingError :relation "django_celery_beat_periodictask" does not exist I migrated the DB and so the celery beat tables do exist. This closed issue https://github.com/celery/django-celery-results/issues/22 is exactly the error I am getting, however, what seems to be the solution does not work for me possibly because I don't know how to do it. -
Django PDF generated not download last version
I have a Django view to show a preview of Pdf generated and works well. I have configured an AWS S3 service to save Pdf generated files and overwrite if existing with same name and works well because i have checked and downloaded manually from bucket. When it's generated again it's visualized well in the browser preview but when downloaded it appears the old version. views.py: @login_required() def budget_pdf(request, id=None): budget = get_object_or_404(app_models.Budget, id=id) concepts = budget.concept_budget.all() file = app_pdf.PDF(None, budget, concepts) pdf_file = file.generate_budget() file_name = 'Pto_' + str(budget.brand.client.name) + '_' + str(budget.name) + '_' + str(budget.code) + ".pdf" budget.pdf.save(file_name, ContentFile(pdf_file), save=True) return render(request, 'file.html', {'element': budget}) file.html: <iframe height=100% width="100%" src="{{ element.pdf.url }}" style="min-height: 800px;"></iframe> Anybody could help me please ? Thanks in advance. -
Django How to call a function in views.py from ajax by clicking submit button with variable
I am facing issue with calling a functions in views.py from script html HTML: <form method="POST" class="msger-inputarea"> {% csrf_token %} <input type="text" name="msg" class="msger-input" placeholder="Enter your message..."> <button type="submit" name="answer" class="msger-send-btn">Send</button> </form> <script type="text/javascript"> msgerForm.addEventListener("submit", event => { event.preventDefault(); const msgText = msgerInput.value; if (!msgText) return; appendMessage(PERSON_NAME, PERSON_IMG, "right", msgText); msgerInput.value = ""; botResponse(msgText); }); function botResponse(rawText) { alert(rawText) alert('inside ajax') $.ajax({ url: "{% url 'ajaxview' %}", method: 'POST', data: {'rawText': rawText , csrfmiddlewaretoken: '{{ csrf_token }}'}, success: function (response) { appendMessage(PERSON_NAME, PERSON_IMG, "left", response); }, }); } URL.py : path('/ajax-test-view', views.myajaxtestview, name='ajaxview') VIEWS.py : def myajaxtestview(request): input = request.POST.get('rawText') return HttpResponse(input) -
save to model after computed in serializer
The serializer will computed the average score of the data and return to view in field weekly_score class BrandChartsSerializer(serializers.ModelSerializer): rankings = serializers.SerializerMethodField() instagram = IGSerializer(allow_null=True) facebook = FBSerializer(allow_null=True) hashtags = BrandHashtagSerializer(allow_null=True, many=True) # rename the json field brand_uid = serializers.IntegerField(source='id') brand_name = serializers.CharField(source='name') origin = serializers.CharField(source="country") weekly_score = serializers.SerializerMethodField() class Meta: model = Brand fields = [ "rankings", "brand_uid", "brand_name", "origin", "instagram", "facebook", "hashtags", "weekly_score", ] def get_weekly_score(self,instance): data = self.get_rankings(instance) result = 0 counter = 0 while data: rankings = data.pop() for key,value in rankings.items(): isFloat = isinstance(value,float) if isFloat: result += value counter += 1 if counter is not 0: result = result/counter return result And I will do sorting in view by sorted() and return as list. It's work but I found that the speed of it is very very slow, so I would like to speed it up. One way I think I could try is, save the computed weekly_score to the models (it already have field in model design) So that i could use order_by of models. So the problem is, it is possible for me to do read and update at same view? It's possbile for me do save/update action in BrandChartsSerializer ? or … -
Chat Group Request is not Saving in Admin
I am building a ChatApp and I am stuck on a Problem. What i am trying to do :- I am trying to send user_1 group chat request from user_2 BUT The Problem is that, The request is not saving in Django Admin. Also request is unable to reach to user_1 What am i using ? I am using Ajax views.py def send_group_invite(request, user_pk, group_pk): request_sender = request.user reciever = get_object_or_404(User, pk=user_pk) group = get_object_or_404(ChatGroup, pk=group_pk) if request_sender == reciever: message = { 'text': f'You can\'t invite yourself', 'tags': 'error', } return JsonResponse({'message': message}) group_request = GroupRequest( request_sender=request_sender, reciever=reciever, group=group) group_request_check = GroupRequest.objects.filter( request_sender=request_sender, reciever=reciever) group_request.save() return JsonResponse({'message': message}) models.py class ChatGroup(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) group_admins = models.ManyToManyField(User, related_name='gropu_admins', blank=True) members = models.ManyToManyField(User, related_name='group_memebers', blank=True) template.html for (result of response.results) { let invite = `<a class="float-right inviteFriend btn" href="/social/send_group_invite/${result.id}/{{ group.id }}/"> <i class="fas fa-user-plus" style="font-size: 36px; color: green;"></i> Invites </a>` if (!result.is_allowed_group_invite) { invite = `<p class="float-right"><i class="fas fa-shield-alt" style="font-size: 36px; color: red;"></i> You can't add</p>` } let phone = '' let email = '' if (result.phone) { phone = `<i class="fas fa-phone-alt"></i>${result.phone}` } if (result.email) { email = `<i class="fas fa-envelope"></i>${result.email}` } $('.inviteUserResults').append(` <li class="media"> <a href="/people/${result.id}" target="_blank"> … -
'QuerySet' object has no attribute 'likes'
I am implementing a likes system for my post. I have used a ManyToManyField in my model. models.py class MarketingMaestro (models.Model): product_title = models.CharField(max_length=250) total_value = models.IntegerField() branding_video = models.CharField(max_length=300) likes = models.ManyToManyField(User, related_name='likes', blank=True) In this I get all the list of the users, and if someone likes the post it is updated in the field. But when I am trying to implement the logic where if the user has already liked the post he/she will be able to see the dislike button only. While doing so I am fetching all the values from the db and checking particular likes field but it is showing error 'QuerySet' object has no attribute 'likes' It is giving me error on the line if marking_maestro.likes.filter(id=request.user.id).exists(): I tried printing the value but is it returning just the queryset <QuerySet [<MarketingMaestro: MarketingMaestro object (1)>]> and if i print the product_title using (marking_maestro.product_title) but then I get the error saying 'QuerySet' object has no attribute 'product_title' -views.py def brand(request): # fetching all the projects marking_maestro = MarketingMaestro.objects.all() is_liked = False print(marking_maestro) if marking_maestro.likes.filter(id=request.user.id).exists(): is_liked = True # fetching the votes emailID = request.user.email context = { 'is_liked' : is_liked } return render(request, 'brand.html', {'marking_maestro' : … -
run a set of queries faster with python and postgres
in my example, I have a list of 3000 words to search in a database, so with this pyhton code (I am using django) the operation takes a lot of time and is done in 3.5 minutes with the average of 120ms for a querie. is there a method to speed up the execution of these queries with a script python using threads or something like that? def my_custom_sql(ent): for e in ent: with connection.cursor() as cursor: entity=e.replace("'","''") cursor.execute("SELECT object FROM yagofacts WHERE subject='{}' AND object LIKE '<wordnet_%>';".format(entity)) row = cursor.fetchall() print(row) -
How to import Session model in __init__.py ? - Django
How to import Session model in init.py ? - Django I'm trying to change the name of the default django table. I can do this and it works perfectly by changing the direct link on site-packages and it works perfectly. But this is bad, because for the project the nomenclature is different so I need to do this at run time app/__init __.py from django.contrib.sessions.models import Session Session._meta.db_table = "my_session" Error: D:\PyEnv38\lib\site-packages\django\apps\registry.py", line 136, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. -
how to add excel sheet data to mysql database using django
I have tried to get a code for adding excel sheet details to MySQL database using Python Django but i could not find a better code .Can anyone suggest a better way of adding data from excel sheet to database using Django. -
AttributeError at /api/updateorder/71 'RelatedManager' object has no attribute 'save'
I am trying to make update api for order objects. OrderItem model is in many to one relationship (with Foreignkey) with Order Model. Also, Billing Details model is one to one relationship with Order model. I am able to update Billing details fields and also Order fields, but cant update the OrderItem fields. I got this error saying 'RelatedManager' object has no attribute 'save' My models: class Order(models.Model): ORDER_STATUS = ( ('To_Ship', 'To Ship',), ('Shipped', 'Shipped',), ('Delivered', 'Delivered',), ('Cancelled', 'Cancelled',), ) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) order_status = models.CharField(max_length=50,choices=ORDER_STATUS,default='To_Ship') ordered_date = models.DateTimeField(auto_now_add=True) ordered = models.BooleanField(default=False) total_price = models.CharField(max_length=50,blank=True,null=True) #billing_details = models.OneToOneField('BillingDetails',on_delete=models.CASCADE,null=True,blank=True,related_name="order") def __str__(self): return self.user.email class Meta: verbose_name_plural = "Orders" ordering = ('-id',) class OrderItem(models.Model): #user = models.ForeignKey(User,on_delete=models.CASCADE, blank=True) order = models.ForeignKey(Order,on_delete=models.CASCADE, blank=True,null=True,related_name='order_items') item = models.ForeignKey(Product, on_delete=models.CASCADE,blank=True, null=True) order_variants = models.ForeignKey(Variants,on_delete=models.CASCADE,blank=True,null=True) quantity = models.IntegerField(default=1) # def price(self): # total_item_price = self.quantity * self.item.varaints.price # return total_item_price total_item_price = models.PositiveIntegerField(blank=True,null=True,) def __str__(self): return f"{self.quantity} items of {self.item} of {self.order.user}" class Meta: verbose_name_plural = "Cart Items" ordering = ('-id',) class BillingDetails(models.Model): PAYMENT_TYPE = ( ('cash_on_delivery', 'Cash On Delivery',), ('credit/debit_card', 'Credit/Debit Card',), ('connect_ips', 'Connect IPS',), ('fonepay', 'Fonepay',), ) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) order = models.OneToOneField(Order, on_delete=models.CASCADE, blank=True, null=True, related_name='billing_details') address = models.CharField(max_length=100,blank=True,null=True) … -
How can I perform operation over model field and filter in django?
My model has a field named key, it looks like; key = models.CharField(max_length=64) I store encrypted string generated using pycrypto python package into key field. key = encrypted string of string 'abc' Now I try to filter over model using field key with encrypted string of same string, does not get any record beacaus each time i encrypt string 'abc' get different encrypted string. model.objects.filter(key=new encrypted string of abc) is that any way to perform decryption operation into model field and filter out using plain string like model.objects.filter(operation on key = 'abc') or do I need to go with any other solution. -
wfastcgi-enable it show 'Ensure your user has sufficient privileges and try again.'
I want to deploy my django website in window server 2008 by follow this tutorial https://www.youtube.com/watch?v=CpFU16KrJcQ&t=191s In step wfastcgi-enable it show message like this. command prompt Microsoft Windows [Version 6.0.6002] Copyright (c) 2006 Microsoft Corporation. All rights reserved. C:\Users\Administrator>wfastcgi-enable ERROR ( message:Unknown attribute "signalBeforeTerminateSeconds". ) An error occurred running the command: ['C:\\Windows\\system32\\inetsrv\\appcmd.exe', 'set', 'config', '/section:system .webServer/fastCGI', "/+[fullPath='c:\\users\\administrator\\appdata\\local\\pro grams\\python\\python37\\python.exe', arguments='c:\\users\\administrator\\appda ta\\local\\programs\\python\\python37\\lib\\site-packages\\wfastcgi.py', signalB eforeTerminateSeconds='30']"] Ensure your user has sufficient privileges and try again. C:\Users\Administrator> -
DRF how to sort value by custom field
serizalizer: class BrandChartsSerializer(serializers.ModelSerializer): rankings = serializers.SerializerMethodField() instagram = IGSerializer(allow_null=True) facebook = FBSerializer(allow_null=True) hashtags = BrandHashtagSerializer(allow_null=True, many=True) # rename the json field brand_uid = serializers.IntegerField(source='id') brand_name = serializers.CharField(source='name') origin = serializers.CharField(source="country") weekly_score = serializers.SerializerMethodField() class Meta: model = Brand fields = [ "rankings", "brand_uid", "brand_name", "origin", "instagram", "facebook", "hashtags", "weekly_score", ] def get_weekly_score(self,instance): data = self.get_rankings(instance) result = 0 counter = 0 while data: rankings = data.pop() for key,value in rankings.items(): isFloat = isinstance(value,float) if isFloat: result += value counter += 1 if counter is not 0: result = result/counter return result the field weekly_score is empty nullable field in model Brand and set value in serizalizer here is the viewset code: class BrandChartsViewSet(ModelViewSet): pagination_class = BrandChartsPagination serializer_class = BrandChartsSerializer queryset = Brand.objects.none() def get_serializer(self, *args, **kwargs): """ Return the serializer instance that should be used for validating and deserializing input, and for serializing output. """ serializer_class = self.get_serializer_class() kwargs['context'] = self.get_serializer_context() return serializer_class(*args, **kwargs) def get_serializer_context(self): start_date = self.request.query_params.get('start_date',None) end_date = self.request.query_params.get('end_date',None) if start_date is None: raise InvalidInputError() if end_date is None: raise InvalidInputError() start_date_obj = datetime.strptime(start_date,'%Y%m%d') end_date_obj = datetime.strptime(end_date,'%Y%m%d') return { 'start_date': start_date_obj, 'end_date': end_date_obj, } def list(self, *args, **kwargs): kwargs['context'] = self.get_serializer_context() queryset = Brand.objects.all() serializer = BrandChartsSerializer(queryset,many=True) … -
Celery Worker Error : self.buffer = mmap.mmap(self.fd, self.size) FileNotFoundError: [Errno 2] No such file or directory
I am getting self.buffer = mmap.mmap(self.fd, self.size) FileNotFoundError: [Errno 2] No such file or directory error while running celery with docker on windows. It is working perfectly on mac. dvu-celeryworker | [2021-03-26 11:08:20,286: CRITICAL/MainProcess] Unrecoverable error: FileNotFoundError(2, 'No such file or directory') dvu-celeryworker | Traceback (most recent call last): dvu-celeryworker | File "/usr/local/lib/python3.8/site-packages/celery/worker/worker.py", line 208, in start dvu-celeryworker | self.blueprint.start(self) dvu-celeryworker | File "/usr/local/lib/python3.8/site-packages/celery/bootsteps.py", line 119, in start dvu-celeryworker | step.start(parent) dvu-celeryworker | File "/usr/local/lib/python3.8/site-packages/celery/bootsteps.py", line 369, in start dvu-celeryworker | return self.obj.start() dvu-celeryworker | File "/usr/local/lib/python3.8/site-packages/celery/concurrency/base.py", line 132, in start dvu-celeryworker | self.on_start() dvu-celeryworker | File "/usr/local/lib/python3.8/site-packages/celery/concurrency/prefork.py", line 111, in on_start dvu-celeryworker | P = self._pool = Pool(processes=self.limit, dvu-celeryworker | File "/usr/local/lib/python3.8/site-packages/celery/concurrency/asynpool.py", line 486, in __init__ dvu-celeryworker | super(AsynPool, self).__init__(processes, *args, **kwargs) dvu-celeryworker | File "/usr/local/lib/python3.8/site-packages/billiard/pool.py", line 1046, in __init__ dvu-celeryworker | self._create_worker_process(i) dvu-celeryworker | File "/usr/local/lib/python3.8/site-packages/celery/concurrency/asynpool.py", line 503, in _create_worker_process dvu-celeryworker | return super(AsynPool, self)._create_worker_process(i) dvu-celeryworker | File "/usr/local/lib/python3.8/site-packages/billiard/pool.py", line 1142, in _create_worker_process dvu-celeryworker | on_ready_counter = self._ctx.Value('i') dvu-celeryworker | File "/usr/local/lib/python3.8/site-packages/billiard/context.py", line 181, in Value dvu-celeryworker | return Value(typecode_or_type, *args, lock=lock, dvu-celeryworker | File "/usr/local/lib/python3.8/site-packages/billiard/sharedctypes.py", line 78, in Value dvu-celeryworker | obj = RawValue(typecode_or_type, *args) dvu-celeryworker | File "/usr/local/lib/python3.8/site-packages/billiard/sharedctypes.py", line 46, in RawValue dvu-celeryworker | obj = … -
django.db.utils.OperationalError: (1366, "Incorrect string value: '\\xC2\\x8E\\xC3\\xA9co...' for column 'announce' at row 1")
I am migrationg data from legacy database to new database. I tried code on local, it worked fine. When I am running code in production, for some fields, it's giving error django.db.utils.OperationalError: (1366, "Incorrect string value: '\\xC2\\x8E\\xC3\\xA9co...' for column 'announce' at row 1") mysql version on local - 8.0.16 mysql version in production server - 5.7.33- How can I fix this. -
Single django data model with multiple subclasses for methods only
I want a single datamodel but to support inherited methods on the same data based on a field type. The simplest way I know to do it is class Foo(models.Model) name = models.CharField(max_length=16) role = models.CharField(max_length=16) data = models.JSONField() def html(self): if role == 'bar': return self.method_bar() elif role == 'baz': return self.method_baz() elif role == 'qux': return self.method_qux() else: return None def method_bar(self): # do something with self.data return def method_baz(self): # do something with self.data return def method_qux(self): # do something with self.data return I really do not like this approach because I have to add a new method when I add a new role rather than adding a new module with the transformation for that role and not risk breaking existing code. Is this alternative wasteful? class Foo(models.Model) name = models.CharField() role = models.CharField(choices=['bar', 'baz', 'qux'], default=None) data = models.JSONField() module = models.CharField(max_length=256) class = models.CharField(max_length=256) def html(self): mod = importlib.import_module(class_module) cls = getattr(mod, class_name, None) if cls is None: return None obj = cls() return obj.html() What are better/more elegant ways to achieve the same result? -
Request timeout/delay Issue
My Applications posts to Instagram using the Django rest-framework. Posting to Instagram is a two step process. First you must send the content to a media container. Then you must wait until Instagram finishes processing the photo/video. Once the media is done being processed you send the creation ID to Instagram to make the post public. In order to ensure that Instagram has enough time to process the media before the creation ID is sent, I use Django's time.sleep function to pause the request for 60 seconds. The problem is that this works on my desktop, but on my ec2 instance the same code fails when I pause the request longer than 10 seconds. To run my application I am using amazon EC2, Gunicorn and nginx. My Django code is this ```#print('posting photo to facebook') video_url = data.get('video_url') container_url = "https://graph.facebook.com/" + page_id + "/media?media_type=VIDEO&\ video_url=" + video_url + "&caption=" + text + "&access_token=" + access_token res = requests.post(container_url) data = res.json() time.sleep(60) publish_url = "https://graph.facebook.com/" + page_id + "/media_publish?\ creation_id=" + data['id'] + "&access_token=" + access_token res = requests.post(publish_url) data = res.json() print('result of video posting attempt') print(json.dumps(data)); a = res.status_code b = 200 #print(res.text) if a != b: …