Django and Python "Questions and answers", page 1622

11.08.2021
Celery auto reload Django

I am following ChillarAnand's example on how to reload Celery on change in my Django project, however it doesn't seem to close the previous Celery worker. On reload Celery raises the following error: [2021-08-11 10:42:30,216: WARNING/MainProcess] /Users/someuser/Documents/dev/backoffice/venv/lib/python3.8/site-packages/kombu/pidbox.py:72: UserWarning: A …

11.08.2021
Django class based view, save in another model after CreateView

I have a create view (Loan_assetCreateView(generic.CreateView)) where I save if an asset is going to be loaned and when it will be returened in a model called Loan_asset(models.Model). Then I have the asset in a diffrent model Asset(model.Model). I would …

11.08.2021
How to extract only day from timestamp in Django

I want to get a specific date like "8" out of (2021-8-3) but it's showing like this image how can I extract the specific date? usertime = User.objects.filter(groups__name = 'patient').values('date_joined').annotate(date_only=Cast('date_joined', DateField()))

11.08.2021
Whats the best websocket solution without too much overhead?

I'm fairly new to real-time databases with WebSockets so I'm facing probably the most important question when it comes to starting, which database and approach within the backend are the fastest and most reliable to set up and scale. I'm …

11.08.2021
Django REST массовая загрузка файлов

Какие есть наиболее оптимальные варианты загрузки файлов для множества объектов? Например надо загрузить по API 1500 изображений и 3000 документов для 500 товаров. Пока есть варианты преобразовывать в base64 строку и передавать как свойство объекта загружать отдельно через DRF …

11.08.2021
How can I save messages from my facebook webhook to a textfile using python and django. The code is attached below

If 'message' in message: # Print the message to the terminal print(message) # Assuming the sender only sends text. Non-text messages like stickers, audio, pictures # are sent as attachments and must be handled accordingly. print(message['message']['text']) respondinging = …

11.08.2021
Integrating a javascript pipeline to Django

I am trying this tutorial to integrate a modern JavaScript pipeline into a Django application. Javascript code is supposed to write a "Hello webpack" into the page, but it does not. Since I already have an existing …

11.08.2021
How to set new unicode codepoints to my language in django settings to support

I'm trying to add my language (kurdish) which is not existing in languages list in django , but i dont know where to find unicode codepoints from django.conf import global_settings import django.conf.locale from django.utils.translation import gettext_lazy as _ LANGUAGE_CODE = …

11.08.2021
Make form look like an excel table

I made this form: the form: AgregatsFormset = inlineformset_factory(Canva, Bilan, fields=('agregat', 'SCF', 'mois1', 'mois2', 'ecart1', 'evolution1', 'finmois1', 'finmois2', 'ecart2', 'evolution2'), can_delete=False, max_num=5) html: {% for bilan_form in form.forms %} {% for fidden_field in bilan_form.hidden_fields %} {{ hidden_field.errors }} {% endfor …

11.08.2021
Implement Django REST TokenAuthentication for Multiple User Model

I need to implement TokenAuthentication using Custom user model Consumer & Merchant (The default User model still exists and is used for admin login). I've been looking on official DRF documentation and days looking on google, but I can't find …

11.08.2021
Add SECRET_KEY to Heroku

When I type heroku config:set SECRET_KEY='MySecretKey' on my Powershell I got this error: 'SomeOfMyCharacterOnMySecretKey' was unexpected at this time. Please tell me if you know how to solve this. Thank you

11.08.2021
Django: how can i change models variable value through template

I want to add function to change is_shown value when the button is pressed. It should be in view but I don't know where exactly. MODEL class Coupon(models.Model): name = models.CharField(max_length=255) price = models.PositiveIntegerField() is_shown = models.BooleanField(default=False) is_used = models.BooleanField(default=False) …

11.08.2021
DRF serializer doesn't save instance to the db

Views class AuthDataViewSet(ModelViewSet): queryset = AuthData.objects.all() serializer_class = AuthDataSerializer def create(self, request, *args, **kwargs): serializer_data, headers = create_auth_data(self, request.data, {'request': request}) # returning response with the data create_auth_data function def create_response_data(view, data: dict = None, …

11.08.2021
Make virtual payment in django

Hello thanks for your visiting i have to develop my Django web app and I went to make a virtual payments between acount like point exchange my question is it secure if i do it using method Post and forms …

11.08.2021
Django customed user model createsuperuser error

I'm newb to python django. I am making a small web page. Here is a piece of code i'm running. I want to make cumtom user model and use it to resigter with music genre, instrumet and nickname. But with …

11.08.2021
How to add image with the specific user with different API in django rest framework

How to add image with the specific user in django rest framework Pass user's id and image as a parameter in API

11.08.2021
Dynamically populated dropdowns in table with Django

I have developed a small interface to list the projects with Django. Each project has multiple versions. I would like to create a table and in each row I would like to have the following items. Project Name Project …

11.08.2021
How to activate a user when user verify his/her phone number using Twilio in Django? If user is not verified how to deactivate a user?

How to activate a user when the user verifies his/her phone number using Twilio in Django? If the user is not verified how to deactivate a user? Here is My code. in forms.py file class CreateUserForm(UserCreationForm): email = forms.EmailField() phone …

11.08.2021
How to get value of ForeignKey in views.py?

I have below models.py and views.py in Django. How can i print the value of ForeignKey in views.py? models.py class student(models.Model): name = models.CharField(max_length=50) desc = models.CharField(max_length=100, blank=True, null=True) phone_number = models.ForeignKey(tell,on_delete=models.SET_NULL, null = True,blank=True) def __str__(self): return self.name class …

11.08.2021
Most Efficient Way to Convert Panda Rows to a Django Model

I'm currently trying to take multiple pandas dataframes and convert them into django model objects. My current code looks something like this: for index, row in df.iterrows(): defaults = {} name = row[('Unnamed: 0_level_0', 'Player')] defaults['player'] = Player.objects.get_or_create(name=row[('Unnamed: 0_level_0', …

11.08.2021
Categorizing Posts in Django?

I am having a problem in categorize Posts. I have categories in Post Model, Please help me solve this issue! MODELS.PY html= "html" css= "css" python= "python" javascript = "javascript" Lang=( (html,"HTML"), (css,"CSS"), (python,"PYTHON"), (javascript,"JAVASCRIPT") ) Broilerplate = "Broilerplate" Simple_Tags …

11.08.2021
How to list multiple uploaded files in html template

I successfully made a form that takes and uploads multiple files. When I check the request.FILES I can see that they have the following files listed. <MultiValueDict: {'files': [<InMemoryUploadedFile: example.txt (text/plain)>, <InMemoryUploadedFile: test.txt (text/plain)>]}> I want to list the …

11.08.2021
Django delete objects with no relations

I have been trying to find a function/sample code that would delete from table all objects with no relations to different objects (I use many-to-many relationship). Documentation and google were not helpful. Anyone can help?

11.08.2021
How to increase or decrease FloatField by 1000 with it's default button?

I have a FloatField in my models. The increase and decrease buttons on the right side of this area normally increase or decrease by 1 each. Is it possible to do this 1000 by 1000? How can I do that? …

11.08.2021
How to assert in django pytest when matching query does not exists

How to assert in django pytest when matching query does not exists @pytest.mark.django_db def test_abc_pending_response(sent_xyz): #Test count is 1 rider_pending_response() sent_orders.refresh_from_db() #Test count is 0 or matching query does not exists assert XYZ.ObjectDoesNotExist #(This assert is not working)

11.08.2021
Why is the reponse of my website slow? django heroku TTFB

I have a website performance issue at heroku with django. The problem I have is that every time I call the website, the website responds quite slowly. I have researched and optimized the images. I also tested that my data …

11.08.2021
How can I delete in one View OLD model OBJECT and create NEW with COPIED fields?Django

I have a model Book: models.py class Book(core.BaseModel): MAX_TAG_NUMBER = 99999 class Statuses(models.IntegerChoices): AVAILABLE = 1, 'Available' NOT_AVAILABLE = 2, 'Not Available' author = models.ForeignKey( Author, models.PROTECT, verbose_name='Author', related_name='author_name', ) tag_number = models.PositiveIntegerField('Tag number', validators=[ MinValueValidator(1), MaxValueValidator(MAX_TAG_NUMBER), ]) year = …

11.08.2021
How to upload multiple image django DRF from Flutter

I have models Car and CarImage and serializers: class Car(models.Model): title = models.CharField('title',max_length=200) def __str__(self): return self.title class CarImage(models.Model): car = models.ForeignKey(Car,on_delete=models.CASCADE,related_name='car_image',related_query_name='car_image') image = models.ImageField(upload_to='test_media/',null=True,blank=True,) def __str__(self): return f'{self.id} Image' class Car_Image_Serializer(serializers.ModelSerializer): class Meta: model = models.CarImage fields = ('id','image') …

11.08.2021
Device_detail() missing 1 required positional argument: 'pk'

Im currently stuck on a error: device_detail() missing 1 required positional argument: 'pk' I cant seem to get past this error My codes: urls.py path('device/<int:pk>/', DeviceDetailView.as_view(), name='device-detail'), path('device/device_detail/', views.device_detail, name='device-detail'), views.py class DeviceDetailView(DetailView): model = Device template_name = 'interface/device_detail.html' …

11.08.2021
Django - Is it possible to create a event/trigger based scheduler?

Normally what we do is a time-based scheduler, which may repeat after certain period of time. But for some reason, I want to create a trigger-based scheduler. If I have n rows in a table_1 then I need to create …

11.08.2021
Removing pycache files from Django project

Recently I have tried cloning my production code to a different pc. Then I have connected my project to a blank DB and run the command python manage.py makemigrations and after that, I can see that my migrations folder was …

11.08.2021
How to add a text editor and compiler in a django page

I am currently working on a project ,where I have to add a text editor and a compiler into my page.I have to also give a functionality, for the user to execute the code and display it on the html …

11.08.2021
How to delete image using image_id with image_id pass as a parameter in django rest framework

How to delete image using image_id with image_id pass as a parameter in django rest framework

11.08.2021
Python module schedule not working as expected in cloud foundry

I am using the python schedule module in my cloud foundry application. when tested on the local system, it worked perfectly. when deployed the same application in cloud foundry, I am getting timeout cf error log: 2021-08-11T11:41:25.34+0530 [APP/PROC/WEB/0] ERR …

11.08.2021
Can CalDav be used with my own django calendar app?

I have been reading about CalDav recently but I don't get how it exactly works. I have implemented a calendar app with django rest framework and react js and I want to sync calendars in my own database with my …

11.08.2021
Insert into Django JsonField without pulling the content into memory

Have a Django model class Employee(models.Model): data = models.JSONField(default=dict, blank=True) This JSONField contains two year of data, like a ton of data. class DataQUery: def __init__(self, **kwargs): super(DataQUery, self).__init__() self.data = kwargs['data'] #is pulling the data in …

11.08.2021
I want to show a random images from a directory (Images) and show in Template in Django

I take the help of This git link but i am still not getting what to do next This is my Setting.py """ Django settings for randomfiles project. Generated by 'django-admin startproject' using Django 3.2.6. For more …

11.08.2021
Django prints error when PermissionDenied exception raises

In our project, we have used django SessionMiddleware to handle users sessions and it's working fine. The only problem here is when PermissionDenied exceptions happens, an error and its traceback will be printed out in the console! However as expected, …

11.08.2021
Modify django model form field with widget

I want to modify some fields in model form, and i found two methods: First Method: class ProfileForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['bio'].widget.attrs.update({'placeholder': 'Enter your bio here'}) class Meta: model = Profile fields = ['bio'] Second Method: …

11.08.2021
How can I fix "Command errored out with exit status 1" when installing requirements.txt through pip for a django project?

I'm having trouble installing this requirements.txt file for a django project. My project directory looks like this: decker-cms ├── decker_cms │ ├── account │ ├── beanstream │ ├── blog │ ├── [...project stuff] ├── decker │ ├── [...env stuff] …