Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
LookupError: No installed app with label 'salesforce'. Did you mean 'salesforce_db'?
After upgrading from Django 2.2 to 3.2 the django-salesforce APP is throwing this error when trying to run my django app Traceback (most recent call last): File "...lib/python3.7/site-packages/django/apps/registry.py", line 156, in get_app_config return self.app_configs[app_label] KeyError: 'salesforce' . . . During handling of the above exception, another exception occurred: Traceback (most recent call last): File "./manage.py", line 14, in <module> execute_from_command_line(sys.argv) File "...lib/python3.7/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "...lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "...lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File ".../lib/python3.7/site-packages/django/apps/registry.py", line 122, in populate app_config.ready() File ".../audit/apps.py", line 18, in ready self.init_auditlog() File ".../audit/apps.py", line 47, in init_auditlog auto_register(all_apps) File ".../audit/utilities.py", line 30, in auto_register app_models = apps.get_app_config(app_name).models File "...lib/python3.7/site-packages/django/apps/registry.py", line 167, in get_app_config raise LookupError(message) LookupError: No installed app with label 'salesforce'. Did you mean 'salesforce_db'? The django-salesforce version is 3.2 salesforce is in INSTALLED_APP, double and triple checked. No syntax errors in model files. -
Best Possible Ways to Translate the language Native to English
I have a website in Django which is in my native language so I want to translate the whole website content in English. I want to know what will be the best possible way to translate the whole website. I will be glad if anyone give me the idea or can share any useful link to make it happen. Thanks much I tried to find out the useful video links and blogs But didn't clear about the best possible ways -
Django Template strange behavior of layout
I have a function which generate a pdf.file and send it by email. And it works perfect. And I have a Table on my frontend like above. In my Django Model - Point 1 set by default as False, by condition if Point 1 is False - Cell 2 is empty, else - marked as Done. When I changing Table via Django form it works fine as well (frontend marked as Done). The problem is when I trying to change this via function which generate a pdf. I have added below lines of code in my pdf.generate Function: def generatePdf(request, pk): point = get_object_or_404(MyObj.objects.select_related('related'), pk=pk) ... email.send(fail_silently=False) point.one = True print(point.one) messages.success(request, 'Success') return HttpResponseRedirect.... at the terminal I got the message that value changed properly from False to True but for some reason Cell 2 in my Table on the frontend still is empty... Part of frontend code: {% for item in object_list %} ... <td> {% if item.one %} <span><i class="fa fa-solid fa-check"></i></span> {% else %} <span></span> {% endif %} </td> ... {% endfor %} Summarizing the above said - why frontend condition working properly if I change via Django form (function) and not if I trying to … -
Django unittests mock.patch will not work if I import the function on top of the file
Hello currently found a problem which I could not find solution to it. I have a django application which communicates with external services in order to write unittests i must patch the functions which call the external services with mock.patch #api_views.py from examplemodule import examplefunction # just example class GetSomeInfoFromExternalService(ApiView): def get(self, *args, **kwargs): if example_function(attrs) == somevalue: return Response({'detail':'OK'}) return Response({'detail':'Not ok'}) here is my other file #tests.py from unittests import mock from django.test import TestCase class MyTestCase(TestCase): @mock.pach('examplemodule.examplefunction') def test_1(self): examplefunction.return_value=123 Like that the patch method will not work, but if I import the examplefunction inside the ApiView.get method is overriding and the mock works. #api_views.py class GetSomeInfoFromExternalService(ApiView): def get(self, *args, **kwargs): from examplemodule import examplefunction # If the import is here the override is working properly if example_function(attrs) == somevalue: return Response({'detail':'OK'}) return Response({'detail':'Not ok'}) -
Django storages is creating folder in s3 bucket when uploading file
I have the following code that i use in django model to upload files to s3 bucket original = S3FileField(storage=S3Boto3Storage(bucket_name='videos-sftp',default_acl=None,region_name='us-east-1',location=''),upload_to='', blank=False, null=False) What is happening is files are being uploaded to following path: https://videos-sftp.s3.amazonaws.com/videos-sftp/ instead of: https://videos-sftp.s3.amazonaws.com/ How do I solve? or is it the package i'm using? -
how to save multiple objects to the database in django rest framework views
so what i'm trying to do is add a new product to my data base using django's restapi but a product may contain multiple categories which are related throught a third many to many model and extra pictures which are ForeignKeyed to the product this is my models.py class Products(models.Model): product_id = models.AutoField(primary_key=True) name = models.CharField(max_length=35, null=False, unique=True) description = models.CharField(max_length=255) price = models.DecimalField(max_digits=10, decimal_places=2, default=0.) main_image = models.FileField(upload_to='shop/images') created_on = models.DateTimeField(blank=True, default=datetime.now) class Category(models.Model): category_id = models.AutoField(primary_key=True) category = models.CharField(max_length=20, null=True, blank=True) created_on = models.DateTimeField(blank=True, default=datetime.now) class Meta: db_table = 'Category' class ProductsCategory(models.Model): productscategory_id = models.AutoField(primary_key=True) category = models.ForeignKey(to=Category, on_delete=models.CASCADE) product = models.ForeignKey(to=Products, on_delete=models.CASCADE) created_on = models.DateTimeField(blank=True, default=datetime.now) class Meta: db_table = 'ProductsCategory' class Pictures(models.Model): picture_id = models.AutoField(primary_key=True) image = models.FileField(upload_to='shop/images') product = models.ForeignKey(to=Products, on_delete=models.CASCADE) created_on = models.DateTimeField(blank=True, default=datetime.now) class Meta: db_table = 'Pictures' and heres what i've tryed: @api_view(['POST']) @permission_classes([IsModerator]) def create_product(request): product_details = ProductsSerializer(request.POST, request.FILES) pictures = PicturesSerializer(request.POST, request.FILES, many=True) category_list = request.POST.getlist("category") if product_details.is_valid() and validate_file_extension(request.FILES.get("main_image")): try: product = product_details.save() if len(category_list) > 0: for i in category_list: if check_category(i): category = Category.objects.get(category=i) ProductsCategory.objects.create(category=category, product=product) else: category = Category.objects.create(category=i) ProductsCategory.objects.create(category=category, product=product) if pictures: for image in request.FILES.getlist("image"): if validate_file_extension(image): Pictures.objects.create(image=image, product=product) else: error = {"error": "invalid … -
Django shell can't see apps(directories with files) that are in the current working directory
I'm fairly new, trying to learn Django. I'm not sure when this issue started, or what caused it, since I used Django shell before and everything worked fine. I've tried different approaches, one of which I saw several times - open Django project from the project folder, not from the outer folder. I did it, and it still doesn't work(pic related) (https://i.stack.imgur.com/swM1J.png) I want to be able to import 'news' app within Django shell since it contains my models, so I can populate my db -
query to loop over records by date in django
I am trying to find a better way to loop over orders for the next seven days including today, what I have already: unfilled_orders_0 = Model.objects.filter(delivery_on__date=timezone.now() + timezone.timedelta(0)) context['todays_orders'] = unfilld_orders_0.aggregate(field_1_sum=Sum('field_1'), field_2_sum=Sum('field_2'),field_3_sum=Sum('field_3'), field_4_sum=Sum('field_4'),field_5_sum=Sum('field_5')) I'm wondering if I can somehow avoid having to do this seven times--one for each day. I assume there is a more efficient way to do this. -
How to create a valid temporary image using PIL for django pytest?
I am having issue on posting PIL created image on pytest. Serializer is not allowing to post that created image. It shows submitted file is empty as well as it shows I/O operation on closed file. Here is my PIL function:- def generate_test_image(): image = Image.new('RGB', (100, 100)) tmp_file = NamedTemporaryFile(suffix='.jpg') image.save(tmp_file) tmp_file.seek(0) return tmp_file def test_update_avatar_success(self, user, authenticated_client): # given photo = generate_test_image() photo.seek(0) # request_body = {"avatar": SimpleUploadedFile("test_avatar.jpg", b"dummy_data", content_type="image/jpeg")} request_body = {'avatar': photo} response = authenticated_client.put(self.url, request_body, format="multipart") # then pytest.set_trace() assert response.status_code == status.HTTP_200_OK data = json.loads(response.content) -
Starting my first Django project on Ubuntu VPS
I have been thinking long and hard about making this post and after hours of Google searches I couldn't come up with any good sources so thought I'd ask here. I am relatively new to coding, started early this year and started a software programming degree so I am super keen to learn. I have managed to make a fully working project that works on shared hosting but doesn't allow me to use latest packages and modules that is why I upgraded to a VPS. But editing my project on cPanel on a shared hosting was alot less scary than what I'm attempting now. I've recently purchased a VPS to host my first django project I'm building for my father, the project is basically a gallery that allows him to upload a blog and images. I had a standard shared hosting plan which was fine but I couldn't use latest python and django on it. So what I want to ask is; what is the common practice for starting off with building a project on ubuntu? In my head it was building it on VSCode and just transferring it to ubuntu, linking it to my domain and BAM. I've found … -
Django ORM LEFT JOIN SQL
Good afternoon) Please tell me, there is a foreign key in django models in the Foreign Key, when creating a connection, it creates a cell in the _id database by which it subsequently performs JOIN queries, tell me how to specify your own cell by which to do JOIN, I can't create tables in an already created database I need a banal simple LEFT JOIN without connection with _id. -
Django Admin - 404 only for a particular model list view
Given these models: class Collection(models.Model): name = models.CharField(max_length=255, blank=False, null=False) user = models.ForeignKey(User, related_name="collections", on_delete=models.CASCADE) class Item(models.Model): name = models.CharField(max_length=255, blank=False, null=False) url = models.URLField(blank=True, null=True) collection = models.ForeignKey(Collection, related_name="items", on_delete=models.CASCADE) and this admin.py class CollectionAdmin(admin.ModelAdmin): pass admin.site.register(Collection, CollectionAdmin) class ItemAdmin(admin.ModelAdmin): pass admin.site.register(Item, ItemAdmin) Does anyone know why I can't see the Collection List in admin? I see it in the sidebar, but when I click on it I get a 404. I should mention that if I type the address for the change view it works, it's just the list view that doesn't work. My patterns: urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('allauth.urls')), path('profile/', TemplateView.as_view(template_name="accounts/profile.html"), name="profile", ), path('collections/add/', CreateCollectionView.as_view(), name="create_collection" ), path('collections/<int:collection_id>/', CollectionDetailView.as_view(), name="collection_detail" ) ] I created and ran all my migrations. What is even weirder is that I see the Collection list in the ForeignKey field when editing an Item. -
Serializer class cannot have additional method?
I have a requirement where I need to get some product data from a CSV file, validate it, and persist it to DB. I have my main classes and logic as follows: class CampaignProductCSVUploadSerializer(serializers.ModelSerializer): _campaign_ids: List[int] = [] _TYPES = ["cellphone", "tablet", "computer"] _different_campaigns = set() _campaign_to_be_inactivated: int = None class Meta: model = CampaignProduct list_serializer_class = CampignProductListSerializer fields = ("code", "name", "type", "campaign",) def __init__(self, *args, **kwargs): data = kwargs.pop("data", None) if data is not None: new_data = self._map_type_to_enum(data) kwargs["data"] = new_data super().__init__(*args, **kwargs) def validate(self, attrs): self._different_campaigns.add(attrs["campaign"].id) if len(self._different_campaigns) > 1: raise ValidationError(_("Single CSV file can only contain one campaign.")) return super().validate(attrs) def _map_type_to_enum(self, data: dict) -> Dict[str, Any]: return_data = copy(data) for item in return_data: item_type = item.get("type") if item_type and item_type.lower() in self._TYPES: item["type"] = item_type.lower() else: item["type"] = "sku" return return_data def return_previous_campaign_id(self) -> int: """ Returns the ID of previous campaign, to be used for inactivating related campaign products. """ return self._different_campaigns.pop() Here, as you can see the method def _map_type_to_enum(self, data: dict) -> Dict[str, Any]: will be used to return the campaign id from _campaign_to_be_inactivated set. However, I cannot use this method. when debugger comes to the highlighted line, I get this error … -
How to send user's full name and email to database with django
When I try to send the full name and email, it returns a value like this <bound method AbstractUser.get_full_name of <User: keremedeler>> To send the e-mail, I added a function like this to the models.py file of the user class, and it sent a response like this: <bound method AbstractUser.get_email of <User: keremedeler>> def get_email(self): email = self.email -
How to lock post_delete method of Child model when delete Parent model using CASCADE in django?
models.py class Parent(models.Model): name = models.CharField(max_length=50) class Child(models.Model): parent = models.ForeignKey(Parent, on_delete=models.CASCADE) name = models.CharField(max_length=50) signals.py @receiver(signals.post_delete, sender=Parent) def delete_parent(sender, instance, **kwargs): # something @receiver(signals.post_delete, sender=Child) def delete_child(sender, instance, **kwargs): # something When delete_parent() signal works, delete_child() signal should not work. How to do this? I tried this, @receiver(signals.post_delete, sender=Child) def delete_child(sender, instance, **kwargs): try: parent = instance.parent # something except: return But don't work. -
sending email in django
I want to send details of the employee via email according to 'task_employee' def meeting_detail_mail(get_task, get_meeting): for i in get_task: data = { "get_task": get_task, "title": get_meeting } html_content = render_to_string( 'app/meeting_mail.html', data ) text_content = strip_tags(html_content) email = EmailMultiAlternatives( 'Minutes of Meeting',text_content, settings.EMAIL_HOST_USER, i['task_employee'].split(",")) email.attach_alternative(html_content, 'text/html') email.send() tried the above code but it sends data to all the participants [{'id': 17, 'task_title': 'working on cfo', 'task_employee': 'rajesh.gupta@atmstech.in', 'task_thread_id': 11, 'task_start_date': datetime.datetime(2022, 12, 12, 13, 38, 57, 165301, tzinfo=<UTC>), 'task_due_date': datetime.datetime(2022, 12, 12, 13, 38, tzinfo=<UTC>), 'task_status': 'Pending', 'task_attendance': False}, {'id': 18, 'task_title': 'lunch', 'task_employee': 'shubham.khaire@atmstech.in', 'task_thread_id': 11, 'task_start_date': datetime.datetime(2022, 12, 12, 13, 39, 9, 182983, tzinfo=<UTC>), 'task_due_date': datetime.datetime(2022, 12, 12, 13, 39, tzinfo=<UTC>), 'task_status': 'Pending', 'task_attendance': False}] In the for loop of i I'm getting the above output -
python for android - Django error when deployed on android device
I am currently using Python for android (p4a) to deploy static react files to a Django backend which spawns the server on the android gadget itself - and hosts the web app on a localhost webview. This is my build.sh I am using to build the application: export ANDROIDSDK="/Users/xxx/Library/Android/sdk" export ANDROIDNDK="/Users/xxx/Library/Android/sdk/ndk/25.1.8937393" export ANDROIDAPI="30" # Target API version of your application export NDKAPI="21" # Minimum supported API version of your application p4a apk --private . \ --package=xyz.ann.test \ --name "TestAppName" \ --version 0.1 \ --bootstrap=webview \ --requirements=python3,hostpython3,django,asgiref,sqlparse,pytz \ --permission INTERNET --permission WRITE_EXTERNAL_STORAGE \ --port=8000 --icon icon.png \ --arch=armeabi-v7a --arch=arm64-v8a \ When I deploy the app on the phone, it currently crashes on start. On running adb logcat, here's the error I see: 12-13 01:27:57.851 19433 19511 I python : django.core.exceptions.ImproperlyConfigured: 'django.db.backends.sqlite3' isn't an available database backend or couldn't be imported. Check the above exception. To use one of the built-in backends, use 'django.db.backends.XXX', where XXX is one of: 12-13 01:27:57.851 19433 19511 I python : 'mysql', 'oracle', 'postgresql' 12-13 01:27:57.851 19433 19511 I python : Python for android ended. I have tried multiple solutions including downgrading Django, trying different python versions, etc. but have hit a roadblock. Any help would be … -
Django: While keeping debug=True APIs are running faster
I have observed that our production environment is slow while keeping debug=False We need to wait 20s or 15 sec for one API response. The same API's are performing in milliseconds, only we changed debug=True -
"error": "invalid_client" while using Django OAuth toolkit
I was following the steps mentioned in the documentation for django rest framework. I'm not able to proceed from step 4. As mentioned in the documentation, curl -X POST -d "grant_type=password&username=<user_name>&password=<password>" -u"<client_id>:<client_secret>" http://localhost:8000/o/token/ I have changed the above variables with my values. curl -X POST -d "grant_type=password&username=admin&password=admin123" -u "5hKeHNtF3EKy3uCpJqaAe3mU2bGZTgJhsKKxIuAQ:pbkdf2_sha256$390000$VFcCOjIZkBFObellddDgKA$DXovC1UiuxRQ0KN/lARIdQmXcj8dnoJofkznmkkqsZY=" http://localhost:8000/o/token/ I tried to import the curl on postman and Im getting this error Then I tried running the curl on Insomnia testing tool, and I got the request configured as in the screenshot. Then I click send and I got an error SO i changed 'Content-Type' to 'Form URL Encoded' Now I'm geting an error { "error": "invalid_client" } I'm stuck with this and don't know how to proceed with this. Please lend me a hand. Thanks in advance... -
ValueError at / Field 'id' expected a number but got 'srednje'
I have django application. I want user to type url with name of certain article in browser and then they will see all products linked to this article. My models look like this: class Article(models.Model): slug = models.SlugField(unique=True, null=True) title = models.CharField(max_length=20, null=True) def __str__(self): return self.title class Product(models.Model): name = models.CharField(max_length=20) # price = models.IntegerField() description = models.CharField(max_length=400) a_article = models.ForeignKey(Article, on_delete=models.CASCADE, null=True) And I try to get this work in my view: def product(request, pk): product = models.Product.objects.filter(a_article=pk) return render(request, 'product.html') Since I passed pk in my function I put it in urls as well: path('<str:pk>/', views.product, name='product'), When I run this and get on url: http://127.0.0.1:8000/srednje/ I get an error: ValueError at /srednje/ Field 'id' expected a number but got 'srednje'. I think this is probably somehow linked to primary key or foreign key but how and how can I change this to work? -
when deploying Django project to Linux server (Getting static files errors)
Hi Team please find the below settings file. i am trying to deploy the django project to linux server but getting below error: Bad Request (400) from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'admin_interface', 'colorfield', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'employee', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] # Database # https://docs.djangoproject.com/en/4.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': str(BASE_DIR / 'db.sqlite3'), } } # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.1/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' #Please advise if we need to change the below _DIRS STATICFILES_DIRS = (os.path.join('employee/static') Error: Found another file with the destination path 'css/mystyle.css'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path. Please advise if any changes are required. -
Django bulk_create using a list of random fields without a hardcoded query
I am trying to create new instances in my Django model using bulk_create(). My models are: Class Emotion(models.Model): emotion_grp_id = models.AutoField(primary_key=True, ... emotion_group = models.CharField(max_length=55, ... Class EmotionSubGroup(models.Model): emotion_sub_grp_id = models.AutoField(primary_key=True, ... emotion_grp = models.ForeignKey(EmotionGroup, on_delete=models.CASCADE, ... emotion_sub_group = models.CharField(max_length=55, ... views.py The relevant portion of the function that I am using looks like this: def DataUpload (request): # ... # ... df_rawdata = pd.read_csv(csv_file, sep=''). # Dataframe from source (.csv) file row_iter = df_rawdata.iterrows() data = [ EmotionSubGroup( emotion_grp_id=row['emotion_grp'], emotion_sub_group=row['emotion_sub_group'], ) for index, row in row_iter ] EmotionSubGroup.objects.bulk_create(data) Is it possible to create a general data structure instead of hardcoding the field names, for example: data = `list_of_target_fields = rows_from_external_source` to be equivalent of what I am using currently and carry out the upload. -
TypeError: cannot pickle '_io.BufferedReader' object when sending e-mail with Django-mailer and Djoser
The problem I'm trying to send a Djoser user's activation email using django-mailer. However, I receive the following error: TL;DR: TypeError: cannot pickle '_io.BufferedReader' object FULL: Traceback (most recent call last): File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/rest_framework/viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/rest_framework/mixins.py", line 19, in create self.perform_create(serializer) File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/djoser/views.py", line 144, in perform_create settings.EMAIL.activation(self.request, context).send(to) File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/templated_mail/mail.py", line 78, in send super(BaseEmailMessage, self).send(*args, **kwargs) File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/django/core/mail/message.py", line 298, in send return self.get_connection(fail_silently).send_messages([self]) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/mailer/backend.py", line 15, in send_messages messages = Message.objects.bulk_create([ ^ File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/mailer/backend.py", line 16, in <listcomp> Message(email=email) for email in email_messages ^^^^^^^^^^^^^^^^^^^^ File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/django/db/models/base.py", line 554, in __init__ _setattr(self, prop, value) File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/mailer/models.py", line 150, in _set_email self.message_data = email_to_db(val) ^^^^^^^^^^^^^^^^ File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/mailer/models.py", line 94, in email_to_db return base64_encode(pickle.dumps(email)).decode('ascii') ^^^^^^^^^^^^^^^^^^^ TypeError: cannot pickle '_io.BufferedReader' object Internal … -
Django request.POST returning NONE
I have been working on a Django REST API and one of the views is as follows : @api_view(['POST']) def create(request): key = request.POST.get('key') name = request.POST.get("name") email = request.POST.get("email") password = request.POST.get("password") print(key) if(key=='0'): user = Users(name=name,email=email,password=password) user.save() return Response("User Created Successfully") else: return Response("Invalid Key") When I send a POST request with all the proper parameters I get the key printed as NONE, but I tried replacing POST with GET every where as below and then sending a GET request actually works normally, but POST request isn't working : @api_view(['GET']) def create(request): key = request.GET.get('key') name = request.GET.get("name") email = request.GET.get("email") password = request.GET.get("password") print(key) if(key=='0'): user = Users(name=name,email=email,password=password) user.save() return Response("User Created Successfully") else: return Response("Invalid Key") Thanks in advance !! Tried GET instead of POST and that works, but since this is a method to enter value in the DB so this should be POST request. -
ModuleNotFoundError: No module named 'celery'
I'm sure that I have installed celery using pip install celery. I am running my Django application on Docker. When I run the command docker compose up, it shows the error. File "<frozen importlib._bootstrap>", line 1206, in _gcd_import batch_email-web-1 | File "<frozen importlib._bootstrap>", line 1178, in _find_and_load batch_email-web-1 | File "<frozen importlib._bootstrap>", line 1128, in _find_and_load_unlocked batch_email-web-1 | File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed batch_email-web-1 | File "<frozen importlib._bootstrap>", line 1206, in _gcd_import batch_email-web-1 | File "<frozen importlib._bootstrap>", line 1178, in _find_and_load batch_email-web-1 | File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked batch_email-web-1 | File "<frozen importlib._bootstrap>", line 690, in _load_unlocked batch_email-web-1 | File "<frozen importlib._bootstrap_external>", line 940, in exec_module batch_email-web-1 | File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed batch_email-web-1 | File "/Batch_Email/Batch_Email/__init__.py", line 1, in <module> batch_email-web-1 | from .celery import app as celery_app batch_email-web-1 | File "/Batch_Email/Batch_Email/celery.py", line 4, in <module> batch_email-web-1 | from celery import Celery batch_email-web-1 | ModuleNotFoundError: No module named 'celery' Before installing celery the command docker compose up would run the Django server. I have installed Redis for using celery. Why am I getting this error and how can I fix it?