Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting SMTPServerDisconnected Error when trying to send email in django
I am trying to send an email with gmail in Django but I am getting SMTPServerDisconnected error. I have tried everything from enabling lesssecuredapps to DisplayUnlockCaptcha but still getting the same error. Any help would be greatly appreciated! Here is the setting.py for email config Here is the send_mail in my views.py The error I've been getting -
The best way to extract a large zip file in the background regardless of the template changing (or other external issues occurring) in Django?
I want to upload a zip file that contains 1 GB or more image data. I have a function that renders a basic Django template that uploads the zip file in the server and then later extracts it using the zipfile module and stores these images. My only worry is that when the user suddenly moves around the site or a network error (or some other external issue) occurs, the function gets interrupted and the extraction, as well as the database storage progress, stops. In short, duplication occurs. If I try to re-run the function again, the 'already stored' images get stored again and later saved to the model. I am not sure how to proceed with the file extraction and storage once the python function gets interrupted. What should I do? This my code so far: def upload(path, id): try: with zipfile.ZipFile(path, mode='r', allowZip64=True) as file: document = Mymodel.objects.get(id=id) directory_to_extract = f"media/{document.path}" file.extractall(directory_to_extract) except zipfile.LargeZipFile: print("File size is too large.") return 0 #returns an error finally: file.close() os.remove(path) Note: The parameter 'path' is the temporary file path moved to the stored path in the directory. The parameter 'id' is the zip file id that gets stored in the model … -
Authentication & Authorization based on JWT Token in Django rest
I am just a newbie with Django, python. I try to build 1 simple API Collection include CRUD basic, and authentication, authorization. I have 1 simple Views like: @api_view(['GET']) @permission_classes([IsUser]) def get_test(request : Request): return JsonResponse({"message": "success"}, status = status.HTTP_200_OK) and IsUser is: class IsUser(IsAuthenticated): def has_permission(self, request : Request, view): token = request.query_params.get('token') if token: role = jwt.decode(token.split(" ").__getitem__(1), key="secret_key",algorithms="HS256").get('role') if role == 'User': return True else: return False return False My purpose wants to parse the JWT token and authorization based on that. I wonder don't know if my way is really correct? Can anyone give me some comments as well as documentation to better understand this issue? I don't use any other lib because I want to code by myself at first to understand the flow. Thanks for helping me. -
How to add Bar chart for my values in database using django
I have 4 columns in my database(userid,month,value1,value2).I need to add a bar graph to compare two values(value1 and value2) for the same month and retrieve it in a bar chart like shown below models.py from django.db import models from django.contrib.auth.models import User class graphinput(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE) Month = models.CharField(max_length=30) Value1 = models.IntegerField() Value2 = models.IntegerField() I need my graph to look like this like comparing two values(value1 and value2) for a same month.. -
Django translation resolution order
I have my base code strings written in Spanish. I want to use another lang as base lang, and sets it in LANGUAGE_CODE, for example, 'de'. I have de.po in locale. I set 'es' as user lang. I have es.po in locale with all empty msgstr values. translation.activate('es') In this case, Django loads the LANGUAGE_CODE value 'de' as default, and loads the 'de' msgstr values as user lang, not the base code strings. The django docs says: When an English variant is activated and English strings are missing, the fallback language will not be the LANGUAGE_CODE of the project, but the original strings. For example, an English user visiting a site with LANGUAGE_CODE set to Spanish and original strings written in Russian will see Russian text rather than Spanish. Maybe a bug? -
Django AJAX : submitting form to different url
Consider having a page url of (localhost:8000/tests). my form in the page submit the form data to url (localhost:8000/add/model) what I'm trying to do is to get the response and render the form template with success or fail message in same page (localhost:8000/tests). the submitting working fine but rendering the form back to the page (localhost:8000/tests) the response render to separate page on url (localhost:8000/add/model) and render form template only views.py: @login_required(login_url="/login/") def add_user(request): done = [] fail = [] context = {} crud = CRUDHandler() form = UserForm(request.POST or None) context['user_form'] = form if 'save' in request.POST: if form.is_valid(): new_user = crud.c_user( username = form.cleaned_data.get('username'), first_name = form.cleaned_data.get('first_name'), last_name = form.cleaned_data.get('last_name'), email = form.cleaned_data.get('email'), ) done.append("User | "+str(new_user.first_name)+" | added successfully!") #change to the right page else: fail.append("Somthing went wrong, new user can't be created!") #change to the right page context['done'] = done context['fail'] = fail return TemplateResponse(request,'components/forms/single_instance_form.html',context) Form_Handler.js $('#form').on('submit', function(event){ event.preventDefault(); var form_anchor = $(this).attr('id') console.log(form_anchor) submit_form(form_anchor); }); function submit_form(form_anchor) { $.ajax({ url : $(form_anchor).attr('action'), // the endpoint type : "POST", // http method // data sent with the post request data : { 'context': $(form_anchor).serialize(), 'csrfmiddlewaretoken': '{{ csrf_token }}', }, // handle a successful response success : … -
Nuxt Auth 'loginWith' function doesn't send data to DRF
I recently tried to combine Nuxt.js with Django. Nuxt.js has a module called Nuxt Auth (I use @nuxtjs/auth-next), which is pretty straightforward and simple to use. However, I ran into a problem when I tried to get the post data when using $auth.loginWith(...) in a Django APIView. When I print out request.POST, it returns an empty QueryDict. When I log in with the standard DRF forms, I get my token as expected (I use JWT for authentication). I first thought that I did something wrong in my Nuxt.js frontend, so I cloned some repos on GitHub to see how they have done it (tickstudiu, ammezie). I then tried to combine their frontend with my backend. I also watched a tutorial on YouTube. Still the same problem... That's why I think that it is a Nuxt + Django specific problem because otherwise, the other repos would work, right? Or maybe I just do something wrong every time... This is what I get when I log in with standard DRF form: HTTP 200 OK Allow: POST, OPTIONS Content-Type: application/json Vary: Accept { "username": "admin", "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiZW1haWwiOiJhbmRyZWFzLmdlcmFzaW1vdzEyQGdtYWlsLmNvbSIsImV4cCI6MTYyMjc5NjQ2N30.XQ58Fo0nOS2C44SRQG5A2vEDT0fOXJTIrHG8XNaxzBo" } Here is my Login API in Django: class LoginAPIView(GenericAPIView): serializer_class = LoginSerializer def post(self, request, … -
How to pull secrets from Kubernetes into GitHub action to run Django migrations for AKS deployment?
I have taken up the challenge of automating the deployment of my company's Django-based application that is done with AKS but I am very new to it. My initial idea is to accomplish it by upgrading the steps in a GitHub workflow that acts on the release of a new version. I have structured it with three jobs. build, migrate and deploy: build: Simply build the Docker image and push it to the container registry on DockerHub - this step is successfully done. migrate: Run the migrations in the production database from python manage.py migrate - here lies the problem. deploy: Deploy the image to the Kubernetes cluster - successfully done. Step 2 is the problem because we store the Postgres database credentials inside the Kubernetes cluster and to run the migrations I need those secrets to pass them as environment variables before I call the migrate command. So I am stuck on how I can pull those secrets from Kubernetes and use them to run a command in a step in GitHub action like this: migrate: needs: build runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Set up Python 3.8 uses: actions/setup-python@v2 with: python-version: 3.8 - name: psycopg2 prerequisites … -
Stripe "webhook" error with "custom user model" (Django)
I'm trying to configure Django Stripe Subscriptions. And now trying to setup webhook to create a new customer data by below code. views.py import stripe from django.conf import settings from django.contrib.auth.models import User from subscriptions.models import StripeCustomer ... # Get the user and create a new StripeCustomer user = User.objects.get(id=client_reference_id) StripeCustomer.objects.create( user=user, stripeCustomerId=stripe_customer_id, stripeSubscriptionId=stripe_subscription_id, ) print(user.username + ' just subscribed.') I'm getting error at user = User.objects.get(id=client_reference_id) because I'm using "custom user model". therefore I changed the above code to user = settings.AUTH_USER_MODEL.objects.get(id=client_reference_id) But still, it does not work. Is there any other way to write to get "user data"? I'm following this manual to create this app https://testdriven.io/blog/django-stripe-subscriptions/ Below is other codes. My models.py from django.conf import settings from django.db import models class StripeCustomer(models.Model): user = models.OneToOneField(to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE) stripeCustomerId = models.CharField(max_length=255) stripeSubscriptionId = models.CharField(max_length=255) def __str__(self): return self.user.username accounts/models.py from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): class Meta: verbose_name_plural = 'CustomUser' My settings.py #used for django-allauth AUTH_USER_MODEL = 'accounts.CustomUser' I just mentioned the above settings in this question but still if more code is required then tell me I'll update my question with that information. Thank you -
How not to go into infinite recursion with a Django signal and a Celery task
I'm working on billing Django app and should generate Pdf from budget on background task each time any value changes. models.py: class Budget(ChangesMixin, models.Model): pdf = models.FileField(verbose_name="PDF", max_length=200, upload_to='pdf/budgets', null=True, blank=True) tasks.py: @shared_task(name='generate_budget_pdf_task') def generate_budget_pdf_task(budget_id): budget = get_object_or_404(app_models.Budget, id=id) concepts = budget.concept_budget.all() try: file = app_pdf.PDF(None, budget, concepts) pdf_file = file.generate_budget() file_name = 'Pto_' + str(budget.brand.client.name) + '_' + str(budget.name) + '_' + str(budget.code) + ".pdf" budget.pdf.save(file_name, ContentFile(pdf_file), save=True) except Exception as e: print("Error generate_budget_pdf_task") print(e) print(type(e)) signals.py: def generate_budget_pdf_signal(sender, instance, created, **kwargs): if 'pdf' not in instance.changes(): app_tasks.generate_budget_pdf_task.delay(instance.id) post_save.connect(generate_budget_pdf_signal, sender=app_models.Budget) But the task update Any could help me please ? Thanks in advance. -
why am I getting undefined error while django migrations?
when I am doing a makemigrations(python manage.py makemigrations), I am getting below errors: File "/usr/local/lib/python3.6/dist-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "base_parameter" does not exist LINE 1: ...e_parameter"."key", "base_parameter"."value" FROM "base_para... ^ I have no idea where to start the troubleshoot. I have created a new database in PostgreSQL. I did go through couple of posts in Stackoverflow, but they are no good for me. I have tried below. - remove previous migrations files - create new DB Please suggest how to fix this. Thank you -
Why is my Django CORS headers not working properly
So I've added corsheaders to both my INSTALLED_APPS and MIDDLEWARE and set CORS_ORIGIN_ALLOW_ALL to True NSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'student', 'rest_framework', 'corsheaders' ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', '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', ] CORS_ORIGIN_ALLOW_ALL = True And I'm also using rest to build an api to use alongside my react app. I made my first API calls to http://localhost:8001/api/students/ to get all the students data and everything is working fine, until I tried to access them individually by changing the link to http://localhost:8001/api/students/1/, when I tried to make a call to that link it gave me this error why is this happening ? -
How to implement encryption decrypttion using cryptography in Django
I am trying generate the order and send to someone and i want to use encrypt and decrypt method using crypto library like bitcoin, Ethereum, but i don't know how can i implement this. -
No migrations to apply for Heroku
I've added a field in my clients model. Here's the model: class Client(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=20) mobile_number = models.CharField(max_length=12) email = models.EmailField(null=True, blank=True) position = models.CharField(max_length=30) organization = models.ForeignKey(UserProfile, null=True, blank=True, on_delete=models.CASCADE) agent = models.ForeignKey("Agent", related_name="clients", null=True, blank=True, on_delete=models.SET_NULL) category = models.ForeignKey("Category", related_name="clients", null=True, blank=True, default=6, on_delete=models.SET_NULL) company_name = models.CharField(max_length=50 , default=None) street_address = models.CharField(max_length=50 , default=None) baranggay = models.CharField(max_length=50 , default=None) city = models.CharField(max_length=50 , default=None) region = models.CharField(max_length=50 , default=None) date_added = models.DateTimeField(auto_now_add=True) phoned = models.BooleanField(default=False) special_files = models.FileField(blank=True , null=True) def __str__(self): return self.company_name Before I've added the position field the program runs smoothly. Now I've got: ProgrammingError: column clients_client.position does not exist At Heroku Bash, when I run python manage.py makemigrations, it detects the changes, but when I migrate it says, no migrations to apply. Please help. -
How to add several classes using django forms and widget?
I need to add two classes into a field in my page using django forms and widget. I can add one one class according to instructed in this link [http://www.learningaboutelectronics.com/Articles/How-to-add-a-class-or-id-attribute-to-a-Django-form-field.php#:~:text=and%20id%20attributes.-,In%20order%20to%20add%20a%20class%20or%20id%20attribute%20to,%3D%7B'class'%3A'some_class'%7D.] But when I add two classes technical_name = forms.CharField(widget=forms.TextInput( attrs={ 'class':'readonly_able', 'class':'tn' } )) I can see only the last class ('tn' in this case) in my web page. -
Why Django serves static files using the wrong MIME type?
On a new installation of windows 10, right after installing python v3.9.5, I do: >pip install django >django-admin startproject test1 >cd test1 >python manage.py migrate And then I edit test1/settings.py only to set the STATIC_ROOT and disable DEBUG mode settings.py import os ... DEBUG = False ALLOWED_HOSTS = ['127.0.0.1'] ... STATIC_ROOT = os.path.join(BASE_DIR, 'static') And then: >python manage.py collectstatic >python manage.py runserver And finally, I navigate to http://127.0.0.1:8000/admin/ and I see this: -
failed to start gunicorn daemon error in digital ocean
i am trying to deploy my django project on digital ocean, and this error stoping me from doing that first let me show my directory structure MY gunicorn.socket file [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target my gunicorn.service file [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=developer Group=www-data WorkingDirectory=/home/developer/myprojectdir ExecStart=/home/developer/myprojectdir/myprojectenv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ bharathwajan.wsgi:application [Install] WantedBy=multi-user.target when i try to check the status of gunicorn it throws me error like this -
DRF How to filter relational data?
In drf you can install djanog-filter and do url/?id=1&username=jack but in the following data what if I want to filter the dates. For example dates.title=interview. [{ "id": 1, "password": "pbkdf2_sha256$260000$xkkKjiHK3ddS1fbGwpt7bQ$EZOhxwywEWGL+0JfzSIEgWFXPPN/f8JelGX2RrjplQM=", "last_login": "2021-06-02T13:25:51Z", "username": "jack", "email": "x@x.com", "secon_email": "", "first_name": null, "last_name": null, "middle_name": null, "is_active": true, "is_staff": true, "is_superuser": true, "is_email_verified": true, "is_role_verified": true, "date_joined": "2021-06-02T13:24:36Z", "receive_newsletter": false, "birth_date": null, "city": null, "about_me": "", "phone_number": "", "second_phone_number": "", "imageUrl": null, "age": "", "address": null, "dates": [{ "id": 1, "deleted": null, "title": "apoentment", "description": "", "start": null, "end": null, "from_time": null, "to_time": null, "date_created": "2021-06-03T06:49:50.929466Z", "recurrence": [], "priority": "", "date_type": 1, "created_by": 1, "users": [1] }, { "id": 2, "deleted": null, "title": "interview", "description": "", "start": null, "end": null, "from_time": null, "to_time": null, "date_created": "2021-06-03T06:49:50.929466Z", "recurrence": [], "priority": "", "date_type": 2, "created_by": 1, "users": [1] } ] }] class UsersSerializer(DynamicSerializer): # dates is relational data ( it is another other model) class Meta: model = User fields = [*[x.name for x in User._meta.fields], 'dates'] depth = 1 -
Connecting django restframework with kivy
I have created Todo list api using django restframework. Now I want to connect api to mobile using kivy mobile framework for frontend. Can somebody tell me how we can connect django rest framework with kivy. Thankyou. -
Django. Add new property ForeignKey to User model existing model: OperationalError
I have existing model which was created before, and I would like to add ForeignKey property to User model, when I run migrations command, I take following errors (fragment of the errors): sqlite3.OperationalError: no such column: patientapp_patient.author_id django.db.utils.OperationalError: no such column: patientapp_patient.author_id The model: class Patient(models.Model): number = models.IntegerField() last_name = models.CharField(max_length=30) first_name = models.CharField(max_length=30) middle_name = models.CharField(max_length=30) birthday = models.DateField(default=datetime.date.today) age = models.IntegerField(null=True) fromdate = models.DateField(default=datetime.date.today) appdate = models.DateField(default=datetime.date.today) district = models.ForeignKey(District, on_delete = models.CASCADE) address = models.TextField(default='') gender = models.BooleanField(default=True) occupation = models.ForeignKey(Occupation, on_delete = models.CASCADE) # it is extra field for patient to prevent from deleting them status = models.BooleanField(default=True) author = models.ForeignKey( User, on_delete=models.CASCADE, ) In addition, in an another project, I have done the same action without facing any difficulties. -
How should I implement email verification using restframework-simple-JWT?
I have been working on custom API token logic, that would allow me to verify users using just their email, but not username and password. How I see it: One user send me credentials (just an email address); Django SMTP server sends an email with verification code; User sends its email address and verification code to the server and then gets access and refresh tokens; I read approximately the same question, but I did not find the answer concrete enough, so I would be glad to hear any suggestion how to solve it. -
Error 'You have not defined a default connection` while connecting multiple database using mongoengine connect()
I have two apps which connects to the same mongodb database using mongoengine. one of the Apps is working fine but when I open the second App it throws an error "A different connection with alias 'default' was already registered. Use disconnect() first". Then I changed the alias in the connect function of one Apps as connect(alias='default2', db='variome'). now it throws the error You have not defined a default connection Can someone please help to fix this -
Django Admin now showing model list in iframe — what changed?
I have built a Django application with a custom interface. It hasn't been changed in a couple of years. These (previous) servers are running Django 3.0.8. Recently I set up a new server, and the Django Admin interface now shows the model list in a scrolling iframe, and long tables on the right side are also scrolled independently of the page. This server is running Django 3.2.3. I don't like the new interface, but it more importantly it will require an extensive rewrite of our custom admin css. Can anyone point me to information about the change, or tell me if there is a setting to disable it? -
Do i really need to learn DJANGO?
I'm not an expert in python , But if i want to make an app all by myself , Do i really need to learn Django ? OR learning React is better for a beginner level project ? -
How to assign ranking on objects based on a value in a queryset
I have a queryset that returns a list of menus that and I want to assign each Menu a rank based on the number of votes accumulated is there a way I can achieve this using django Query Expressions? I'm also open to any other suggestions. The queryset is as follows: qs = Menu.objects.filter(Q(created_at__date__iexact=todays_date)).order_by('-votes') And the Menu class model is shown below: class Menu(models.Model): """Represents menu class model""" restaurant = models.ForeignKey(Restaurant,null=True,blank=True,on_delete=models.CASCADE) file = models.FileField(upload_to='menus/') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) uploaded_by = models.CharField(max_length=50, null=True, blank=True) votes = models.IntegerField(default=0) After serializing the queryset returns the following data: [ { "id": 10, "file": "https://res.cloudinary.com/dw9bllelz/raw/upload/v1/media/menus/index_ah660c.jpeg", "restaurant": "Burger King", "votes": 10, "created_at": "2021-06-03T09:33:05.505482+03:00" }, { "id": 9, "file": "https://res.cloudinary.com/dw9bllelz/raw/upload/v1/media/menus/index_ah660c.jpeg", "restaurant": "Texas Plates", "votes": 2, "created_at": "2021-06-03T09:33:05.505482+03:00" }, { "id": 8, "file": "https://res.cloudinary.com/dw9bllelz/raw/upload/v1/media/menus/index_ah660c.jpeg", "restaurant": "Carlito Dishes", "votes": 2, "created_at": "2021-06-03T09:33:05.505482+03:00" }, { "id": 7, "file": "https://res.cloudinary.com/dw9bllelz/raw/upload/v1/media/menus/index_ah660c.jpeg", "restaurant": "Kram Dishes", "votes": 1, "created_at": "2021-06-03T09:33:05.505482+03:00" }, ]