Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Celery/django - chunk tasks
I have a lot of tasks that are being generated that I would like to group in to chunks, but I think in the opposite way as Celery does. From my understanding, I can use the chunks feature to split up a list of items when I create the task. I would like to do the opposite. The data I have is being produced one at a time from different endpoints. But I would like to process them in chunks so that I can insert them in to a database in single transactions. So essentially I'd like to add items to a queue 1 at a time, and dequeue them 100 at a time (either at some specified time interval or once the queue reaches a certain level) and use a transaction to insert all of them in to a database. This would save me from Is this possible with celery? Would it be easier to drop down to redis and create a custom queue there? -
python - Django Operational Error, No such table
I am learning django and I really can't solve this error, I tried modifying every file but I can't find where the issue is. Error: OperationalError at /topics/ no such table: pizzas_topic I have to mention that this exercise is from Python Crash Course 2nd Edition Thanks Here is the code from my project: base.html: <p> <a href="{% url 'pizzas:index' %}">Pizzeria</a> - <a href="{% url 'pizzas:topics' %}">Pizzas</a> </p> {% block content %}{% endblock content %} index.html {% extends "pizzas/base.html"%} {% block content %} <p>Pizzeria</p> <p>Hi</p> {% endblock content%} topic.html {% extends 'pizzas/base.html' %} {% block content %} <p>Topic: {{topic}}</p> <p>Entries:</p> <ul> {% for entry in entries %} <li> <p>{{entry.date_added|date:'M d, Y H:i'}}</p> <p>{{entry.text|linebreaks}}</p> </li> {% empty %} <li>There are no entries for this topic yet.</li> {% endfor %} </ul> {% endblock content %} topics.html {% extends "pizzas/base.html" %} {% block content %} <p> Topics</p> <ul> {% for topic in topics %} <li> <a href="{% url 'pizzas:topic' topic.id %}">{{ topic }}</a> </li> {% empty %} <li>No topics have been addet yet.</li> {% endfor %} </ul> {% endblock content %} urls.py """Defines URL patterns for pizzeria.""" from django.urls import path from . import views app_name = 'pizzas' urlpatterns = [ # Home … -
How to pass Serizalizer Fields to front-end Framework from RESTful API - DRF (Django)?
I want to use Svelte in the front-end and DRF (Django) in the back-end. This is what I have right now: #models.py class Student(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) # serializers.py class StudentSerializer(serializers.ModelSerializer): class Meta: model = Student fields = "__all__" But when I know want to create a form in the front-end (Svelte) I have to manually do that? Is there a way of requesting a json with all the required fields and the to build a form around it. Like first I request api.com/students/form wich returns a json: { "fields":[ "first_name", "last_name" ] } And then I could just iterate over the fields in "fields" and create <input> tags for the form acordingly. -
Django: How to get parameters used in filter() from a QuerySet?
For the following QuerySet, qs = MyModel.objects.filter(attribute_one='value 1', attribute_two='value 2') How can I retrieve the parameters used in the filter (i.e. attribute_one and attribute_two) and the corresponding values (i.e. value 1 and value 2) from qs? Thank you! -
API call interation store each response
I have a list of items that I pass into an API call for each item and return a response for each one. For each response, I extract the values I want. The list of items will grow over time. How do I collect the response of each call and reference that in the template? for item in tokens: data = cg.get_coin_by_id(item.token_slug) price = (data['market_data']['current_price']['usd']) symbol = (data['symbol']) day_change_percentage = (data['market_data']['price_change_percentage_24h']) logo = (data['image']['small']) I have been adding each value to the database so that I can reference the values using query set using tokens = profile.tokens.all() and then using {% for token in tokens%} ... , but I don't really need to be storing this long-term. Thanks -
Python: SystemError: null argument to internal routine
After installation of python packages I am running into below error. It doesn't give any idea what is doing wrong. garg10may@DESKTOP-TVRLQTQ MINGW64 /e/coding/github/product-factory-composer/backend ((bf13ffe...)) $ python manage.py migrate Traceback (most recent call last): File "E:\coding\github\product-factory-composer\backend\manage.py", line 22, in <module> main() File "E:\coding\github\product-factory-composer\backend\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Python310\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Python310\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Python310\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python310\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Python310\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "<e:\coding\github\product-factory-composer\backend\src\core-utils\src\core_utils\__init__.py>", line 3, in <module> File "<frozen core_utils>", line 6, in <module> SystemError: null argument to internal routine -
how to display multiple videos in django
Here code is working fine but I want to display multiple videos. Here only displaying one video. when Uploading second video, second video file is storing but it is not displaying. Please help me out to solve this. Please. views.py: def showvideo(request): lastvideo= Video.objects.all() form= VideoForm(request.POST or None, request.FILES or None) if form.is_valid(): form.save() context= {'lastvideo': lastvideo, 'form': form } return render(request, 'master/video.html', context) forms.py: class VideoForm(forms.ModelForm): class Meta: model= Video fields= ["name", "videofile"] models.py: class Video(models.Model): name= models.CharField(max_length=500) videofile= models.FileField(upload_to='videos/', null=True, verbose_name="") def __str__(self): return self.name + ": " + str(self.videofile) video.html: <html> <head> <meta charset="UTF-8"> <title>Upload Videos</title> </head> <body> <h1>Video Uploader</h1> <form enctype="multipart/form-data" method="post" action=""> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Upload"/> </form> <br><br> <video width='400' controls> <source src='{{videofile.url}}' type='video/mp4'> Your browser does not support the video tag. </video> <br><br> </p> </body> <script>'undefined'=== typeof _trfq || (window._trfq = []);'undefined'=== typeof _trfd && (window._trfd=[]),_trfd.push({'tccl.baseHost':'secureserver.net'}),_trfd.push({'ap':'cpbh-mt'},{'server':'p3plmcpnl487010'},{'id':'8437534'}) // Monitoring performance to make your website faster. If you want to opt-out, please contact web hosting support.</script> <script src='https://img1.wsimg.com/tcc/tcc_l.combined.1.0.6.min.js'></script> </html> urls.py: path('videos/',views.showvideo,name='showvideo'), -
Could not parse the remainder: '(audio_only=True)'
in my templates/videos.html, <div class="grid grid-cols-3 gap-2"> {% for vid in videos.streams.filter(audio_only=True) %} <a href="{{vid.url}}">{{vid.resolution}}</a> {% endfor %} </div> Error is, Could not parse the remainder: '(audio_only=True)' from 'videos.streams.filter(audio_only=True)' I can solve this when i pass all_videos = videos.streams.filter(audio_only=True) from my views.py as context, and in templates/videos.html i replace videos.streams.filter(audio_only=True) with all_videos, but I want to know that is there any other method to solve this -
Sentry is working on local but not working in server
I'm troubled with the sentry, I configured sentry in my Django application it's working fine and an error arrives in sentry UI from localhost, but in the same case, I run from the server it's not working, and no error arrives into sentry UI. DEBUG=False ALLOWED_HOSTS = ["*"] sentry_sdk.init( dsn="https://sentry-url", integrations=[DjangoIntegration(), CeleryIntegration(), RedisIntegration()], # Set traces_sample_rate to 1.0 to capture 100% # of transactions for performance monitoring. # We recommend adjusting this value in production. traces_sample_rate=1.0, # If you wish to associate users to errors (assuming you are using # django.contrib.auth) you may enable sending PII data. send_default_pii=True, ) -
Not correct scope for accessing events
HttpError at /calendar <HttpError 403 when requesting https://www.googleapis.com/calendar/v3/calendars/primary/events?singleEvents=true&orderBy=startTime&alt=json returned "Request had insufficient authentication scopes.". Details: "[{'message': 'Insufficient Permission', 'domain': 'global', 'reason': 'insufficientPermissions'}]"> Request Method: GET Request URL: http://localhost:8000/calendar Django Version: 3.2.9 Exception Type: HttpError Exception Value: Then does this after a while RefreshError at /calendar The credentials do not contain the necessary fields need to refresh the access token. You must specify refresh_token, token_uri, client_id, and client_secret. It seems I don't possess the right scope when accessing the calendar and it seems currently the access_token does appear. from google.oauth2.credentials import Credentials def get_user_events(request): credentials = Credentials(get_access_token(request), scopes=SCOPES) service = googleapiclient.discovery.build('calendar', 'v3', credentials=credentials) google_calendar_events = service.events().list(calendarId='primary', singleEvents=True, orderBy='startTime').execute() google_calendar_events = google_calendar_events.get('items', []) return google_calendar_events def get_access_token(request): social = request.user.social_auth.get(provider='google-oauth2') return social.extra_data['access_token'] -
attach domain name with lightsail instense and django
I have created static ip in lightsail and attached it to the django instanse. I bought domain name from godaddy. I then created domain zone in lightsail and created 2 DNS records type "A" with the following: @.drmahahabib.com www.drmahahabib.com Then i copied the name servers from the same page for my lightsail then took that to godaddy site and changed the name servers there. Now i get the page that confirms that the lightsail is working but not the site instense of django. do i need to do some modification? below is the screenshot or just visit the webpage. my site -
how go through and see the library source code
hello friends i code django and python in pycharm for a company .i have 2 project in one of them i can see the source code of django and django rest framework with "command + mose over" and in another one it doesnt work with django and other libraries except my code and python source code. i mean i can see the source of os in "import os " but i cant see and go through the for example "from rest_framework import authentication".... the senior tell me maybe the place of the env file ....I do not know what to do? can anyone help me ? this is the location of my "venv" and "bime" is the name of the project place of env and project -
django admin The outermost 'atomic' block cannot use savepoint = False when autocommit is off
When I try to delete an item from a table generated by django admin, it throws this error Environment: Request Method: POST Request URL: http://127.0.0.1:8000/admin/sybase_app/packageweight/?q=493 Django Version: 1.8 Python Version: 3.6.9 Installed Applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', 'sybase_app') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware') Traceback: File "/home/pd/.local/lib/python3.6/site-packages/django/core/handlers/base.py" in get_response 132. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/pd/.local/lib/python3.6/site-packages/django/contrib/admin/options.py" in wrapper 616. return self.admin_site.admin_view(view)(*args, **kwargs) File "/home/pd/.local/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapped_view 110. response = view_func(request, *args, **kwargs) File "/home/pd/.local/lib/python3.6/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 57. response = view_func(request, *args, **kwargs) File "/home/pd/.local/lib/python3.6/site-packages/django/contrib/admin/sites.py" in inner 233. return view(request, *args, **kwargs) File "/home/pd/.local/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapper 34. return bound_func(*args, **kwargs) File "/home/pd/.local/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapped_view 110. response = view_func(request, *args, **kwargs) File "/home/pd/.local/lib/python3.6/site-packages/django/utils/decorators.py" in bound_func 30. return func.__get__(self, type(self))(*args2, **kwargs2) File "/home/pd/.local/lib/python3.6/site-packages/django/contrib/admin/options.py" in changelist_view 1590. response = self.response_action(request, queryset=cl.get_queryset(request)) File "/home/pd/.local/lib/python3.6/site-packages/django/contrib/admin/options.py" in response_action 1333. response = func(self, request, queryset) File "/home/pd/.local/lib/python3.6/site-packages/django/contrib/admin/actions.py" in delete_selected 49. queryset.delete() File "/home/pd/.local/lib/python3.6/site-packages/django/db/models/query.py" in delete 537. collector.delete() File "/home/pd/.local/lib/python3.6/site-packages/django/db/models/deletion.py" in delete 282. with transaction.atomic(using=self.using, savepoint=False): File "/home/pd/.local/lib/python3.6/site-packages/django/db/transaction.py" in __enter__ 164. "The outermost 'atomic' block cannot use " Exception Type: TransactionManagementError at /admin/sybase_app/packageweight/ Exception Value: The outermost 'atomic' block cannot use savepoint = False when autocommit is off. How can I … -
Rewrite website from PHP YII to Python Django [closed]
Good afternoon. We have a corporate website at work, with a lot of data for a couple of years. It is written in PHP YII, my task now is to rewrite it in Python Django. The database is PosgresSQL, it has data coming in automatically and is generally well designed, so I want to keep it. Bottom line: What's the best way to rewrite the site in python and keep the old database. It turns out I will need to rewrite the models suitable for this database. Maybe there is some methodology for this? -
How to create two docker compose containers on one server
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 8a58a0898843 repo.com/test_nginx_dev "..." 3 seconds ago Up 2 seconds 80/tcp, 0.0.0.0:9000->9000/tcp test_nginx_dev a1fzd92a1c9d repo.com/test_django_dev "..." 3 seconds ago Up 2 seconds 8080/tcp, 0.0.0.0:8100->8100/tcp test_django_dev CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 7516491ae772 repo.com/test2_nginx_dev "..." 7 seconds ago Up 5 seconds 0.0.0.0:80->80/tcp test2_nginx_dev 59a344089c51 repo.com/test2_django_dev "..." 7 seconds ago Up 6 seconds 8080/tcp test2_django_dev First, test2_nginx_dev and test2_django_dev were created with docker-compose. After that, if I create test_nginx_dev and test_django_dev with docker-compose test2_nginx_dev and test2_django_dev disappear. how do i solve it -
how solve Error when run django app on server of heroku?
i create django app and now i run it on heroku app my procfile and other thing are as follow. but when i build it on heroku then it succesfully uploaded but not run on website. this app is run in localhost is good but not at online hear is procfile web: waitress-server --port=$PORT todoapp.wsgi:application hear is last logs 2022-01-24T07:20:24.200304+00:00 app[api]: Deploy 5e0ae6c8 by user zeelmehta.zm31@gmail.com 2022-01-24T07:20:24.200304+00:00 app[api]: Release v10 created by user zeelmehta.zm31@gmail.com 2022-01-24T07:20:33.000000+00:00 app[api]: Build succeeded 2022-01-24T07:20:40.938065+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=todoapp-zeel.herokuapp.com request_id=81d8bb3e-5f6c-4f37-8be0-90508cebef10 fwd="157.32.119.168" dyno= connect= service= status=503 bytes= protocol=https 2022-01-24T07:20:41.630709+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=todoapp-zeel.herokuapp.com request_id=87aff06b-aff3-4846-9abc-95b1db51d632 fwd="157.32.119.168" dyno= connect= service= status=503 bytes= protocol=https 2022-01-24T07:20:55.134817+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=todoapp-zeel.herokuapp.com request_id=9a920057-d443-4404-badd-493951c0c196 fwd="157.32.119.168" dyno= connect= service= status=503 bytes= protocol=https 2022-01-24T07:20:55.760932+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=todoapp-zeel.herokuapp.com request_id=0f0b6bfc-2181-4eb0-b0af-8e444058b163 fwd="157.32.119.168" dyno= connect= service= status=503 bytes= protocol=https``` please help me to solve this error -
How to change the file name when uploading an image field in Django
When uploading an image field (media file) in Django, it asks about renaming the file. The page url to upload the image contains the pk of the foreign key. I want to rename the image file to {pk}.png when uploading an image. When the code below works, it is saved as none. What's the problem? [urls.py] app_name = 'dataroom' urlpatterns = [ path('det/<int:research_id>/', views.detData, name='DataDet'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) [models.py] import .utils import rename_imagefile_to_uuid class protocol_upload(models.Model): trial = models.ForeignKey(Research, on_delete=models.SET_NULL, blank=True, null=True) protocol_file = models.FileField(upload_to='protocol/', null=True, blank=True) clusion= models.ImageField(upload_to='criteria/clusion/', null=True, blank=True) reference = models.ImageField(upload_to=rename_imagefile_to_uuid, storage=OverwriteStorage(), null=True, blank=True) def image_save(self, *args, **kwargs): if self.id is None: saved_image = self.reference self.reference = None super(protocol_upload, self).save(*args, **kwargs) self.reference = saved_image super(protocol_upload, self).save(*args, **kwargs) def __str__(self): return str(self.trial) [utils.py] import os from uuid import uuid4 def rename_imagefile_to_uuid(instance, filename): upload_to = 'reference/' ext = filename.split('.')[-1] uuid = uuid4().hex if instance: filename = '{}.{}'.format(instance.id, ext) else: filename = '{}.{}'.format(uuid, ext) return os.path.join(upload_to, filename) [views.py] def detData(request, research_id): research = Research.objects.get(id=research_id) protocol = protocol_upload.objects.all() for reference in request.FILES.getlist('reference'): protocol = protocol_upload() protocol.research = research_id protocol.reference = reference protocol.save() context = { 'protocol': protocol, 'research': research, } return render(request, '/detail.html', context) [detai.html] <form method="POST" action="{% url 'dataroom:DataDet' research_id=research.id … -
What is the average cost of hosting a django app?
Due to current RBI guidelines on recurring payments for standing instructions I am unable to use Heroku which is great for small apps. Therefore I have to choose other platoforms. I have narrowed down my choice to two platforms aws and digital ocean. overview of my django website : The website which I made for my client is not that big. In this website a user registers, chooses some plan and then book an intructor to teach him/ her driving. A user after loging in has to accept an agreement and also has an udate plan page. Thats it on the user side. Now I use celery which uses redis, to send emails such as otp, registration successful, change password, contracts and updated contracts (the contracts' email are send both to the client and the user as per the clients demand). As you can see I have to use celery and redis because there is a lot email work that has to be done by the website. And the database i am using is Postgresql. Now comming to traffic, we cannot predict what will be the number of visitors on the site, but we accept maximum of 10 registrations per … -
Displaying the Custom model field in the Post method
I am facing some problems regarding Django-Rest-Framework, post method. There are two things I want to accomplish: Adding fields in the view of the Post method. --> Here instead of sending the data in Json format, I want to replace the filed names with the Custom model's fields And when using '@renderer_classes([BrowsableAPIRenderer])' decorator in a view, the view page shows '[No renderers were found]'. Here are snippets of my code and the screenshots of the errors I got... serializers.py class CreateTodoSerailizer(serializers.ModelSerializer): class Meta: model = Todos fields = ('title', 'user', 'desc', 'todo_date', 'is_completed',) def save(self): todo = Todos( title = self.validated_data['title'], user = self.validated_data['user'], desc = self.validated_data['desc'], todo_date = self.validated_data['todo_date'], is_completed = self.validated_data['is_completed'], ) todo .save() return todo models.py class Todos(models.Model): user = models.ForeignKey(Account, on_delete=models.CASCADE) title = models.CharField(max_length=30) slug = models.SlugField(max_length=50, blank=True) desc = models.TextField(blank=True) date_created = models.DateTimeField(auto_now_add=True) todo_date = models.DateField(default=date.today) is_completed = models.BooleanField(default=False) class Meta: verbose_name = _("Todos") verbose_name_plural = _("Todos") ordering = ['-date_created'] def __str__(self): return self.title def save(self, *args, **kwargs): self.slug = slugify(self.title) return super(Todos, self).save(*args, **kwargs) views.py @api_view(['POST']) def createTodo(request, format=None): if request.method == 'POST': serializer = CreateTodoSerailizer(data=request.data) data = {} if serializer.is_valid(): todo = serializer.save() data['response'] = 'Successfully added' data['title'] = todo.title data['username'] = todo.user … -
Creating a database using python and Django and populating that database from HubSpot API Data
I am trying to populate the database using HubSpot's Companies API data. I have created a table in models.py. In views.py file I have called API data, however I am not able to save that data in the Database. I do not understand if there an issue in my code or anything else? your help on this task would be really appreciated. views.py def index(request): url = "https://api.hubapi.com/companies/v2/companies?" headers = {} r = requests.get(url = url, headers ={'Authorization':'Bearer %s' %os.getenv('access_token')}) try: response_dict = json.loads(r.content) companies_list= response_dict['companies'] for company in companies_list: Company.update_or_create( companyID = company['companyId'], sourceID = company['sourceId'], portalID = company['portalId'], country = company['country'] ) except Exception as e: response_dict= "Data not found:" return render(request, 'Apihub/index.html', {'response_dict': response_dict} In models class: models.py class Company(models.Model): companyID = models.CharField(max_length=50, blank=True, null=True) sourceID = models.CharField(max_length=20, blank=True, null=True) portalID = models.IntegerField(default=0) country = models.CharField(max_length=50, blank=True, null=True) -
Django forms hidden field value assignation with a var after 'forms.is_valid()' doesn't save it
I have a form with an hidden input called social_color where I want nothing in, I need this input to assign a value after validating the form content to use one of the field content to do stuff and then assign the results to the hidden input. According to this answer: https://stackoverflow.com/a/813474/15352101 I can simply do : if form.is_valid(): form.cleaned_data['Email'] = GetEmailString() but for me using : form.cleaned_data["social_color"] = icon_main_color icon_main_color is the results of the stuff I had to do, it's a tuple containing 3 values but when I check the created object with the form, the value of social_color is still empty. -
Adding a variable in Django templates static tag {% %} enclosure
I have a project in Django Python. And, I am trying to figure out how to add a variable in a {% %} enclosure I'ved got variables set in this way: CP_ENV_SMALLAPPNAME_CAPITALIZE <-- meta title variable CP_ENV_FAVICON_PATH <-- favicon variable path <title>{{ CP_ENV_SMALLAPPNAME_CAPITALIZE }}</title> <-- this works <link rel="icon" type="image/png" sizes="16x16" href="{% static 'img/{{CP_ENV_FAVICON_PATH}}/favicon-16x16.png' %}"> <--- this doesnt work How can I insert CP_ENV_FAVICON_PATH into {% static %} enclosure in django ? -
storing large data into mongodb collection using python
I am working on a Django project where I have to create 10 years of data and store them in MongoDB retrieve it and display it on the HTML page. I am trying to divide 10 years of data into 1 year and then store it in MongoDB collection but whenever I try to do so only two documents get stored and this error is shown in pymongo. errors.DocumentTooLarge: BSON document too large (29948865 bytes) - the connected server supports BSON document sizes up to 16793598 bytes. my python code is now=start workdate=now.date() nowtime=now.time() endt=end ktime=start times=[] states=[] level=[] #generating random level of water in the tank while (now!=endt): # loop for creating data for given time ktime=ktime+relativedelta(months=5) print(current_level) def fill(): global df global now global workdate global nowtime global ktime global current_level global flag global times global states global level while x=='on' and current_level<=450: times.append(now) states.append(x) level.append(current_level) current_level+=filling current_level=round(current_level,2) now=now+timedelta(minutes=1) nowtime=now.time() workdate=now.date if now==ktime: times.append(now) states.append(x) level.append(current_level) print("true") flag='red' break def drain(): global df global now global workdate global nowtime global ktime global current_level global flag global times global states global level while x=='off' and current_level>50: times.append(now) states.append(x) level.append(current_level) print(current_level) current_level-=emptyrate current_level=round(current_level,4) now=now+timedelta(minutes=1) nowtime=now.time() workdate=now.date() if now==ktime: times.append(now) states.append(x) … -
How to send array of django model objects in post api?
class Product(models.Model): name = models.CharField(max_length=255) class Image(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) image = models.ImageField(upload_to="images") class ProductViewSet(ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer How can I make my serializer and views? My post api request payload will be: [{"name":"Laptop", "images":[array of image files]}, {"name":"Shoes", "images":[array of images]}] -
Telegram Oauth2 with Django
I am exploring ways to send telegram messages to the users using Telegram bot from my Django application. The bot should be able to initiate the conversation - these messages are more like alerts and updates but not conversations. From Telegram developer documentation I could not find a standard OAuth2 implementation with Telegram to get access tokens for sending messages to the users using REST APIs. Does anyone know Oauth flow implementation for Telegram if at all it exists Sending messages using API - I am not planning to run a bot server. The messages just need to be pushed to the user - more like push notifications. Appreciate your help.