Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django -- use some production data in test database
My project is using Django's test database framework (w/ and w/o Selenium) and it's been working well for several years, with a few read-only tests on the production database (mostly integrity tests that our DB can't enforce) but with the vast majority being R/W on the test database. We have one model/table on the production database that provides important metadata for the site which is getting too big to code into the fixtures, and which we would like to see current values for in our tests. I would love our setUp() code to be able to do something like: def setUp(self): with self.activate_production_database(): metadata_info = MetadataTable.objects.values_list( 'title', flat=True) # back to test_database MetadataTable.objects.bulk_create([MetadataTable(title=t) for t in metadata_info]) I'm wondering what, if anything, exists that is like the with self.activate_production_database() line? -
How to implement models of product in relation with order and orderitem
I am creating a multivendor ecommerce website in django i want when a person make an order he can add multiple items that belong to multiple vendors so when the order get proceded each vendor will have the items from the order that are specific to him and he can call the person who ordered then (wanna make it simple) am encountering the issue im my modelisation i don't know how to set the model for the order (who should have a list of ordered items each item is linked to the product specific to that item along with the quantity that the person is ordering so the order item class is linked with onetoone relation with product and the order is linked to order item with ontomany relationship when i create it i get this error : ERRORS: Store.OrderItem.product: (fields.E300) Field defines a relation with model 'Product', which is either not installed, or is abstract. Store.OrderItem.product: (fields.E307) The field Store.OrderItem.product was declared with a lazy reference to 'Store.product', but app 'Store' doesn't provide model 'product'. here is my code class OrderItem(models.Model): product = models.OneToOneField('Product', on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) # Assuming quantity cannot be negative class Order(models.Model) : name=models.CharField(max_length = … -
Django load template tags with if else conditions
The problem seems very simple, yet I can't fix it. Look at below two examples. Both give me TemplateSyntaxError.(separately) While only one should give an error. Why is that? (there is no template tag called aa) You can check this by putting one at a time into the template. it seems Django load template tag runs wherever it was put(except comment tag) . {% if "4" == "3" %} {% else %} {% load aa %} {% endif %} {% if "4" == "3" %} {% load aa %} {% else %} {% endif %} -
Articles matching query does not exist
I have just started working in Django. My problem in addressing with slug I get an error when sending a request to Slug It is my error: Articles matching query does not exist. And I get an error when migrate It is my error: django.db.utils.OperationalError: table "bloges_category" already exists -
What is the django-method of fetching the instance in a OneToOneField, accesed from a ManyToManyRelatedManager?
I was wondering what is the most django correct way of fetching the instance in an OneToOneField, when the instance I'm fetching from is accessed through a ManyToManyRelatedManager? Specifically, I have a CustomGroup model that has a OneToOneField to auth.Group. Then I want to fetch each CustomGroup instance from the user instance, through the groups manager. These are my models: from django.contrib.auth.models import AbstractUser, Group from django.db import models class CustomGroup(models.Model): group = models.OneToOneField(Group, on_delete=models.CASCADE, related_name="custom_group") class CustomUser(AbstractUser): # my custom fields I would like to have a get_custom_groups method on the CustomUser model that returns a RelatedManager with the base queryset as all the CustomGroup that this user is related to (much like user.groups, but only with CustomGroup as the model). What I have usually done is something like this: def get_custom_groups(self): custom_group_ids = self.groups.all().values_list("custom_group", flat=True) return CustromGroup.objects.filter(id__in=custom_group_ids) Is this the best way of doing this, or is there another, smarter way? -
Django (daphne, channels_redis) websocket disconnecting due to group_expiry after 24 hours
I'm currently doing a django project where I need to be constantly connected to websockets. For the websockets I am using daphne server and channels_redis (with redis server). I'm having the problem that after 24 hours clients disconnect from the websockets due to group_expiry. Is there any way to set this group_expiry parameter of channels_redis to infinity, that would prevent the deletion of groups? Or is there some mechanism to restore the group (channel layers) connection? Thank you in advance for the answer I tried setting the group_expiry parameter to -1, which for daphne meant infinity for websocket_timeout. Unfortunately, this doesn't help -
my django mysql filter not woking am getting error message
am getting this error below accountyp = Customer.objects.values('accountyp').get(custid=cusid) accouncode = Accountype.objects.values('accounttypecode').get(accountypename=accountyp) am getting this error message Accountype matching query does not exist. def generateacct(request,cusid): cusid=cusid accountyp = Customer.objects.values('accountyp').get(custid=cusid) accouncode= Accountype.objects.values('accounttypecode').get(accountypename=accountyp) return render(request,'generateacctno.html',accountyp) -
I can find environment variables in my path
C:\\Users\\Desktop\>pip install virtualenv Defaulting to user installation because normal site-packages is not writeable Collecting virtualenv Downloading virtualenv-20.25.0-py3-none-any.whl.metadata (4.5 kB) Requirement already satisfied: distlib\<1,\>=0.3.7 in c:\\users\\appdata\\local\\packages\\pythonsoftwarefoundation.python.3.12_qbz5n2kfra8p0\\localcache\\local-packages\\python312\\site-packages (from virtualenv) (0.3.8) Requirement already satisfied: filelock\<4,\>=3.12.2 in c:\\users\\appdata\\local\\packages\\pythonsoftwarefoundation.python.3.12_qbz5n2kfra8p0\\localcache\\local-packages\\python312\\site-packages (from virtualenv) (3.13.1) Requirement already satisfied: platformdirs\<5,\>=3.9.1 in c:\\users\\appdata\\local\\packages\\pythonsoftwarefoundation.python.3.12_qbz5n2kfra8p0\\localcache\\local-packages\\python312\\site-packages (from virtualenv) (4.1.0) Downloading virtualenv-20.25.0-py3-none-any.whl (3.8 MB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 3.8/3.8 MB 2.5 MB/s eta 0:00:00 Installing collected packages: virtualenv WARNING: The script virtualenv.exe is installed in 'C:\\Users\\AppData\\Local\\Packages\\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\\LocalCache\\local-packages\\Python312\\Scripts' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. Successfully installed virtualenv-20.25.0 C:\\Users\\Desktop\>virtualenv env 'virtualenv' is not recognized as an internal or external command, operable program or batch file. Installed it correctly. but it doesn't create virtualenv env -
How to fix 502 error when deploying django project as a zip file using elastic beanstalk
I am trying to deploy a django project as a zip file using elasticbeanstalk. But I don't know what I am doing wrong. It is a very simple django project. My file/directory structure for the project is this: [![filestructure][1]][1] The files that are included in the zip file I upload are all the directories/files in MEMBERS/forening. django.config contains: option_settings: aws:elasticbeanstalk:container:python: WSGIPath: forening.wsgi:application requirements.txt contains the output of the command python3 -m pip freeze which is: asgiref==3.7.2 Django==4.2.8 sqlparse==0.4.4 typing-extensions==4.9.0 The IAM role I use has permission to AWSElasticBeanstalkMulticontainerDocker, AWSElasticBeanstalkWebTier and AWSElasticBeanstalkWorkerTier. Below is my web-stdout.log: Jan 1 14:28:39 ip-172-31-0-168 web[2082]: [2024-01-01 14:28:39 +0000] [2082] [INFO] Starting gunicorn 21.2.0 Jan 1 14:28:39 ip-172-31-0-168 web[2082]: [2024-01-01 14:28:39 +0000] [2082] [INFO] Listening at: http://127.0.0.1:8000 (2082) Jan 1 14:28:39 ip-172-31-0-168 web[2082]: [2024-01-01 14:28:39 +0000] [2082] [INFO] Using worker: gthread Jan 1 14:28:39 ip-172-31-0-168 web[2090]: [2024-01-01 14:28:39 +0000] [2090] [INFO] Booting worker with pid: 2090 Jan 1 14:28:39 ip-172-31-0-168 web[2090]: [2024-01-01 14:28:39 +0000] [2090] [ERROR] Exception in worker process Jan 1 14:28:39 ip-172-31-0-168 web[2090]: Traceback (most recent call last): Jan 1 14:28:39 ip-172-31-0-168 web[2090]: File "/var/app/venv/staging-LQM1lest/lib64/python3.9/site-packages/gunicorn/arbiter.py", line 609, in spawn_worker Jan 1 14:28:39 ip-172-31-0-168 web[2090]: worker.init_process() Jan 1 14:28:39 ip-172-31-0-168 web[2090]: File "/var/app/venv/staging-LQM1lest/lib64/python3.9/site-packages/gunicorn/workers/gthread.py", line 95, … -
Where should I store a bunch of strings I intend on using in a single feature (for a short amount of time)?
I have a (relatively) big and complex (Django) app with multiple database tables. Now, I'm building the landing page of a new feature that includes a section where are displayed 3 random sentences from a collection of 10 predefined strings. I want to be able to update and change these strings without having to rebuild and redeploy the app each time. Should I create another table in the database just to store this data or are there other ways to do it (properly)? -
NoReverseMatch when adding comments section in Django
I'm trying to add comments to my blog, but I have this error and I cannot figure out why. Error: NoReverseMatch at /2024/01/01/lesson-1/ Reverse for 'post_comment' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<year>[0-9]+)/(?P<month>[0-9]+)/(?P<day>[0-9]+)/(?P<lesson>[-a-zA-Z0-9_]+)/comment/\\Z'] url.py urlpatterns = [ ... path('<int:year>/<int:month>/<int:day>/<slug:lesson>/', views.lesson_detail, name='lesson_detail'), path('<int:year>/<int:month>/<int:day>/<slug:lesson>/comment/', views.post_comment, name='post_comment'), ...] forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['name', 'email', 'body'] models.py class Comment(models.Model): post = models.ForeignKey(Lesson, on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) class Meta: ordering = ['created'] indexes = [ models.Index(fields=['created']), ] def __str__(self): return f'Comment by {self.name} on {self.post}' views.py @require_POST def post_comment(request, post_id): post = get_object_or_404(Lesson, id=post_id, status=Lesson.Status.PUBLISHED) comment = None # A comment was posted form = CommentForm(data=request.POST) if form.is_valid(): # Create a Comment object without saving it to the database comment = form.save(commit=False) # Assign the post to the comment comment.post = post # Save the comment to the database comment.save() return render(request, 'lessons/comment.html', {'post': post, 'form': form, 'comment': comment}) comment_form.html <h2>Add a new comment</h2> <form action="{% url 'lang_learning_app:post_comment' post.id %}" method="post"> {{ form.as_p }} {% csrf_token %} <p><input type="submit" value="Add comment"></p> </form> lesson_detail.html {% with comments.count as total_comments %} <h2> {{ … -
How can I receive email to a smtp server with django framework?
The company mail that I have been using so far is an IMAP Mail Server, and in the account settings when I reach through ThunderBird, there is also an Outgoing SMTP server. I am unaware of the web development and am currently trying to receive an e-mail to this IMAP server. The project is a Django project. I have tried django-imap-backend to no avail. I cannot simply receive an image whatever I have tried. I tried with my gmail account as well but it didn't work either. I am not sure what I have been missing, I tried every stack-overflow questions related to the issue but couldn't send the e-mail neither with imap-backend nor with my personal gmail account. at the end of settings.py from mysite(main web app) looks like this one EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = 'my google email' EMAIL_HOST_PASSWORD = 'password' urls.py from the main app: (form is in contact_page app) urlpatterns = [ path("", include("index.urls")), path("about/", include("about_page.urls")), path("polls/", include("polls.urls")), path("contact/", include("contact_page.urls")), path("about/products", include("products_page.urls")), path("admin/", admin.site.urls), path("products/", include("products_page.urls") ), path("careers/", include("careers.urls")), path("events/", include("newsnevents_page.urls")), ] views.py from the contact_page: from django.shortcuts import render from django.http import HttpResponse from django.template import loader from django.http … -
Migrating Django Project with reversion Library to Golang (Gin) - Implementation Query
We are presently in the midst of migrating a Python (Django) project to Golang (Gin). Within our application, we utilize the reversion library. How to implement this functionality during migration to Golang? @reversion.register() class DocumentRecommendationMedia(models.Model): document = models.ForeignKey("Document.Document", on_delete=models.CASCADE) file = models.FileField(upload_to=settings.DOCUMENT_RECOMMENDATION_PATH) file_name = models.CharField(max_length=100) class Meta: db_table = "document_recommendation_media" @reversion.register(fields=("recommendation", "date", "media_files")) class DocumentRecommendation(ArchivableModel): document = models.ForeignKey("Document.Document", on_delete=models.CASCADE) recommendation = models.TextField(null=True, blank=True) date = models.DateTimeField(default=timezone.now) media_files = models.ManyToManyField(DocumentRecommendationMedia, blank=True) class Meta: db_table = "document_recommendation" How to implement reversion in Golang? -
Coning an element raises error: Uncaught TypeError: $(...).find(...).select2 is not a function
I am using Django and in a template page, user can add multiple rows dynamically to enter values: <div class="mb-4 row"> <div class="col-md-4"> <select name="product_id[]" required class="form-select select2"> <option value="" disabled selected>Product</option> {% for product in products %} <option value="{{ product.id }}">{{ product.title }}</option> {% endfor %} </select> {% if form.type.errors %} <small class="text-danger">{{ form.type.errors.0 }}</small> {% endif %} </div> <div class="col-md-4"> <input type="number" name="quantity[]" placeholder="Qty" class="form-control" required> {% if form.quantity.errors %} <small class="text-danger">{{ form.quantity.errors.0 }}</small> {% endif %} </div> <div class="col-md-4"> <input type="number" name="unit_price[]" class="form-control" placeholder="Unit Price" required> </div> </div> There is a select, uses select2 library to let user search on list items. Also add button lets user to add a new row with this script: function add_new_row() { var formsetContainer = document.getElementById("formset-container"); // Clone the last invoice item row var lastRow = formsetContainer.lastElementChild; var newRow = lastRow.cloneNode(true); // Update IDs and clear values in the cloned row var prefix = "form-" + formsetContainer.childElementCount; // Assuming 1-based index updateRow(newRow, prefix); // Append the new row to the formset container formsetContainer.appendChild(newRow); // Reinitialize Select2 on the cloned select element $(newRow).find('select[name="product_id[]"]').select2(); } function updateRow(row, prefix) { // Update IDs and clear values in the cloned row row.querySelectorAll("[name]").forEach(function (element) { // … -
I Am Trying to Send Email In django With Production Level But Django Not responding
hello Everyone I Am Try Using Django Email Send Project on Production Level in Windows Server 2019 but i am Getting Error TimeoutError at /send_email [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond Email Configuration EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'Email' EMAIL_HOST_PASSWORD = 'Password' Views.py from django.contrib.sites.shortcuts import get_current_site from .forms import EmailSendForm from django.core.mail import send_mail from django.template.loader import render_to_string from django.utils.html import strip_tags from django.shortcuts import render, redirect from django.http import HttpResponse from .models import Email def home(request): if request.method == 'POST': form = EmailSendForm(request.POST) if form.is_valid(): email = form.cleaned_data['email'] subject = form.cleaned_data['subject'] message = form.cleaned_data['message'] # Render HTML content from the template current_site = get_current_site(request) domain = current_site.domain html_message = render_to_string('email_template.html', {'subject': subject, 'message': message, 'domain': domain}) # Send both HTML and plain text versions of the email send_mail( subject, strip_tags(html_message), # Plain text version 'ttech.helpdeskindia@gmail.com', [email], html_message=html_message, # HTML version fail_silently=False, ) form.save() return redirect('emailsent') # Redirect to a success page else: form = EmailSendForm() current_site = get_current_site(request) domain = current_site.domain context = { 'form': … -
Seeking Guidance on Migrating Django Project to Golang and Finding Equivalent to reversion Library
We are currently migrating a project from Python (Django) to Golang (Gin). In our application, we use the reversion library. Is there an equivalent in Golang? If not, how can we implement the migration of this functionality in Golang? Perhaps someone has encountered this and can give me advice. @reversion.register() class DocumentRecommendationMedia(models.Model): document = models.ForeignKey("Document.Document", on_delete=models.CASCADE) file = models.FileField(upload_to=settings.DOCUMENT_RECOMMENDATION_PATH) file_name = models.CharField(max_length=100) class Meta: db_table = "document_recommendation_media" @reversion.register(fields=("recommendation", "date", "media_files")) class DocumentRecommendation(ArchivableModel): document = models.ForeignKey("Document.Document", on_delete=models.CASCADE) recommendation = models.TextField(null=True, blank=True) date = models.DateTimeField(default=timezone.now) media_files = models.ManyToManyField(DocumentRecommendationMedia, blank=True) class Meta: db_table = "document_recommendation" I am seeking possible implementation options for reversion in Golang. -
Get object by id of OneToOne related object in DRF
I have Progress model wich relates with Deck model by OneToOne relation. I want to get Progress object from API by passing deck_id to 'http://localhost/api/v1/progress/deck_id/' endpoint. How I can do this? Or may be should I consider other implementations of retrieving Progress object? Also I want all CRUD functions with this model. class Deck(models.Model): name = models.CharField(max_length=70) owner = models.ForeignKey( CustomUser, on_delete=models.CASCADE, related_name='decks', ) class Progress(models.Model): deck = models.OneToOneField(Deck) progress = models.JSONField( null=True ) class ProgressViewSet(viewsets.ModelViewSet): queryset = Progress.objects.all() serializer_class = ProgressSerializer permission_classes = (OwnerOrAdminProgress,) lookup_field = 'id' http_method_names = ['get', 'post', 'patch', 'delete'] class ProgressSerializer(serializers.ModelSerializer): progress = serializers.JSONField() class Meta: model = Progress fields = ('id', 'deck', 'progress') router_v1 = routers.DefaultRouter() router_v1.register('v1/decks', DeckViewSet, basename='decks') router_v1.register('v1/progress', ProgressViewSet, basename='progress') urlpatterns = [ path('', include(router_v1.urls)), ] -
attribute error in Django while making a urls.py file under my app
while i'm trying to create my first project and my first app i'm getting this error: of course when i removed the url of my app view.py it works perfectly (the home screen) .... File "C:\Users\pegasus\barakcapitalcom\buildtradeapp\urls.py", line 5, in <module> path('buildtradeapp/', views.index, name='index') ^^^^^^^^^^^ AttributeError: module 'buildtradeapp.views' has no attribute 'index' this is my app urls.py: from django.urls import path from . import views urlpatterns = [ path('buildtradeapp/', views.index, name='index') ] this is my app views.py: from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse("Hello world!") this is my main project urls.py: from django.contrib import admin from django.urls import path, include from buildtradeapp import views urlpatterns = [ path('buildtradeapp/', include('buildtradeapp.urls')), path('admin/', admin.site.urls), ] what did i do wrong? i'm trying to create my first app and first project, printing hello world using django -
Passing Django Usernames to Streamlit
I'm working on a project using Django for user authentication and Streamlit for the front end. I'm struggling to fetch the authenticated user's information from Django and pass it to my Streamlit app. How can I efficiently retrieve user data from Django and securely transfer it to Streamlit? Any guidance or code examples for this integration would be appreciated. Thanks! Attempted to establish communication between Django and Streamlit by creating an endpoint in Django to fetch user information. I expected to retrieve the authenticated user's data from Django and then use an HTTP request in Streamlit to fetch this data from the Django endpoint. However, I encountered difficulties in properly implementing this communication and handling the data transfer securely between the two platforms. Also Tried to Use Javascript To Fetch On Screen Infomration -
getting values from the url
url: urlpatterns = [ path('', views.ProductListView.as_view(), name='product-list'), path('cat/<cat>/',views.ProductListView.as_view(),name='product-categories-list'), path('cat/<cat>/tag/<tag>/', views.ProductListView.as_view(), name='product-tag-list'), # path('<str:slug>', views.ProductDetailView.as_view(), name='product-detail'), ] views: def Product_tags_component(request:HttpRequest): category_name = request.GET.get('cat) product_tags = ProductTag.objects.filter(category__url_title__iexact=category_name,is_active=True) context = { 'product_tags':product_tags } return render(request,'product_module/components/Product_tags_component.html',context) I need to get the value of the cat through the url, I used request.GET.get('cat) and none is returned. I printed the request.GET command and returned <QueryDict: {}>. I gave the value of cat to the function like this def Product_tags_component(request:HttpRequest,cat) He said this: Product_tags_component() missing 1 required positional argument: 'cat' How can I get the values through the url, there shouldn't be any problem, thank you very much for your help. by the way i'm using the function with render_partial for another classview -
How can I avoid this Numpy ArrayMemoryError when using scikit-learn's DictVectorizer on my data?
I'm getting a numpy.core._exceptions._ArrayMemoryError when I try to use scikit-learn's DictVectorizer on my data. I'm using Python 3.9 in PyCharm on Windows 10, and my system has 64 GB of RAM. I'm pre-processing text data for training a Keras POS-tagger. The data starts in this format, with lists of tokens for each sentence: sentences = [['Eorum', 'fines', 'Nervii', 'attingebant'], ['ait', 'enim'], ['scriptum', 'est', 'enim', 'in', 'lege', 'Mosi'], ...] I then use the following function to extract useful features from the dataset: def get_word_features(words, word_index): """Return a dictionary of important word features for an individual word in the context of its sentence""" word = words[word_index] return { 'word': word, 'sent_len': len(words), 'word_len': len(word), 'first_word': word_index == 0, 'last_word': word_index == len(words) - 1, 'start_letter': word[0], 'start_letters-2': word[:2], 'start_letters-3': word[:3], 'end_letter': word[-1], 'end_letters-2': word[-2:], 'end_letters-3': word[-3:], 'previous_word': '' if word_index == 0 else words[word_index - 1], 'following_word': '' if word_index == len(words) - 1 else words[word_index + 1] } word_dicts = list() for sentence in sentences: for index, token in enumerate(sentence): word_dicts.append(get_word_features(sentence, index)) In this format the data isn't very large. It seems to only be about 3.3 MB. Next I setup DictVectorizer, fit it to the data, and try to transform … -
my site is showing me integrity error something regarding POST
[[enter image description here](https://i.stack.imgur.com/aICfo.png)](https://i.stack.imgur.com/5Kday.png) i am facing this error and i am currently new to django and don't know how to overcome it i have pasted the error page and the page of my contact form i wanted to save the information that i get by filling the form to be saved in my data base/admin -
How to really completely completely remove pgadmin4 web version from ubuntu (nothing works)
I have tried this: sudo apt -y remove pgadmin4 sudo apt -y autoremove pgadmin4* It does not work I have tried this: pip3 uninstall pgadmin4 it does not work while it says "successfully removed" it is not! The problem is that I have forgotten the password so uninstalling and installing does not help because it does not give me a chance to reenter the new data: So I have gone to env/lib/python3.10/site-packages/pgadmin4/config_local.py LOG_FILE = '/var/log/pgadmin4/pgadmin4.log' SQLITE_PATH = '/var/lib/pgadmin4/pgadmin4.db' SESSION_DB_PATH = '/var/lib/pgadmin4/sessions' STORAGE_DIR = '/var/lib/pgadmin4/storage' SERVER_MODE = True and removed the stored sessions, the config_loca.py file and still does not work because when I run this: python3 venv/lib/python3.10/site-packages/pgadmin4/setup.py it does not pop me up to enter email and password like the first time I installed it but it just reads: pgadmin4 application initialisation I am going insane about it. I cannot use the reset password because I still don't have the SMTP mail thing installed on my web. -
Want to use Django as a full stack framework for my to-do web application project
I want to make a to-do web application project using only Django for both frontend and backend,suggest me how to do it , I'm beginner student. I want to do it using only Django beacusecurrently I'm learning python so this project will help me to learn things more accurately about Django and backend also frontend . -
Authentication issue when sending emails with Gmail API in Django using Django Rest Framework
class SendEmailView(APIView): serializer_class=SendEmailSerializer permission_classes = [IsAuthenticated] def post(self, request): user = request.user if not user.gmail_credentials: return Response({"error": "Gmail not linked"}, status=status.HTTP_400_BAD_REQUEST) creds = Credentials.from_authorized_user_info(json.loads(user.gmail_credentials)) if creds.expired: creds.refresh(Request()) service = build('gmail', 'v1', credentials=creds) to_email = request.data.get("to") subject = request.data.get("subject") message_text = request.data.get("message") if not all([to_email, subject, message_text]): return Response({"error": "Missing fields"}, status=status.HTTP_400_BAD_REQUEST) try: message = MIMEText(message_text) message['to'] = to_email message['from'] = user.email # Replace with your sender address message['subject'] = subject raw_message = base64.urlsafe_b64encode(message.as_string().encode("utf-8")).decode("utf-8") message_body = {'raw': raw_message} sent_message = service.users().messages().send(userId='me', body=message_body).execute() return Response({"message_id": sent_message['id']}, status=status.HTTP_200_OK) except Exception as e: return Response({"error": str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) { "error": { "code": 401, "message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.", "errors": [ { "message": "Login Required.", "domain": "global", "reason": "required", "location": "Authorization", "locationType": "header" } ], "status": "UNAUTHENTICATED", "details": [ { "@type": "type.googleapis.com/google.rpc.ErrorInfo", "reason": "CREDENTIALS_MISSING", "domain": "googleapis.com", "metadata": { "method": "caribou.api.proto.MailboxService.GetMessage", "service": "gmail.googleapis.com" } } ] } } im trying to send the email thrugh django, but i keep getting the same error.