Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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" }, ] -
How to set selected text from database into populated cascading dropdown List with JSON Data
I follow this tutorial with title Cascading Dropdown List using JSON Data - Learn Infinity https://www.youtube.com/watch?v=T79I5jOJlGU&t=11s I have 4 select tags ( -region -province -municipality -barangay ) First I populate the dropdown list from JSON DATA I achieve the first one that I have to select a specific region first before the province gets populate. What I want to achieve next is to set selected text from the database into cascading dropdown. HTML CODE: <form name="addressForm"> <select name="region" id="region"> <option value="">Select Region</option> </select> <select name="province" id="province"> <option value="">Select Province</option> </select> <select name="municipality" id="municipality"> <option value="">Select Municipality</option> </select> <select name="barangay" id="barangay"> <option value="">Select Barangay</option> </select> </form> JS CODE $(document).ready(function(e){ function get_json_data(code,region) { //alert("a " + code) var html_code = ""; $.getJSON('/templates/ph_API/CombineAddress.json', function(data){ ListName = code.substr(0, 1).toUpperCase() + code.substr(1); html_code += '<option value="">Select ' + ListName + '</option>'; $.each(data, function(key, value) { if(value.region == region) { html_code += '<option value="' + value.code + '">' + value.name + '</option>'; } }); $('#' + code).html(html_code); }); } get_json_data('region', 0); $(document).on('change', '#region', function() { var region_id = $(this).val(); if (region_id != '') { get_json_data('province', region_id); } else { $('#province').html('<option value="">Select Province</option>'); } $('#municipality').html('<option value="">Select Municipality</option>'); $('#barangay').html('<option value="">Select Barangay</option>'); }); $(document).on('change', '#province', function() { var province_id … -
django error: ValueError: invalid literal for int() with base 10: [closed]
I make a djagno project Why this code is error?? views.py def HomePageView(request): model = Post.objects.all() today = datetime.now(timezone('Asia/seoul')) yesterday = today - timedelta(days=1) today_post = Post.objects.filter(dt_created=today) yesterday_post = Post.objects.filter(dt_created=yesterday) context = { 'todayPost': today_post, 'yesteerdayPost': yesterday_post, 'model':model, } return render(request, 'math_note/home.html', context=context) error: ValueError: invalid literal for int() with base 10: b'02 08:59:09.459625' -
Django can send "reset password" mail but cannot use the "send_mail"
I want to send a "greetings" mail, when people sign up for my webpage. I can send a "reset password" email using the built in auth_views.PasswordResetView but when I try use the django.core.mail.send_mail I get an Username and Password not accepted. My settings.py . . #Email config EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_PORT = 587 DEFAULT_FROM_EMAIL = "My Name <no-reply@my_site.com>" EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_PASSWORD = app_cred EMAIL_HOST_USER = app_email and views.py def register(request): if request.method=="POST": #post request form = UserRegisterForm(request.POST) agree_form = AgreeForm(request.POST) if form.is_valid() and agree_form.is_valid(): user = form.save(commit=False) user.email = form.cleaned_data["email"] user.save() send_mail(subject = "Welcome to my-site.com", message = "Welcome!", from_email = None, recipient_list = [user.email]) return redirect("login") else: form = UserRegisterForm() agree_form = AgreeForm() return render(request,"users/register.html",context= {"form":form,"agree_form":agree_form}) As far as I understand, Django uses the credentials specified in the settings, so I wonder why I can send a password-reset mail but cannot use the send_mail method using the same credentials? -
Python program to check Date of birth is greater then 18 or not?
What should I use here to check if a person inputs the dob is greater than 18 or not please try to solve this problem, so please try to find out the solution of this DOB problem? views.py def register(request): if request.method == "POST": # Get the post parameters username = request.POST['username'] email = request.POST['email'] First_name = request.POST['First_name'] Last_name = request.POST['Last_name'] dob = request.POST['dob'] pass1 = request.POST['pass1'] pass2 = request.POST['pass2'] # check for errorneous input if User.objects.filter(username=username).exists(): messages.error(request, 'This Aadhaar is Already Used') return redirect('home') if User.objects.filter(email=email).exists(): messages.error(request, 'This Email is already Used') return redirect('home') if (pass1 != pass2): messages.error(request, " Passwords do not match") return redirect('home') # Create the user myuser = User.objects.create_user(username, email, pass1) myuser.first_name = First_name myuser.last_name = Last_name myuser.save() extendedregister = Registration(user=myuser, First_name=First_name, Last_name=Last_name, dob=dob) extendedregister.save() messages.success(request, "You are successfully registered") return redirect('home') else: return HttpResponse("404 - Not found") -
Heroku No migrations to apply
I'm having trouble with my database at Heroku: I've added some models for my App and whenever I run makemigrations it detects those changes. However when I run migrate it only says no migrations to apply. Please help! -
AttributeError: 'tuple' object has no attribute 'product'
When I go to the url:http://127.0.0.1:8000/addToCart/1/ , it should add the product to the Cart. But it is showing >AttributeError: 'tuple' object has no attribute 'product' Maybe I've made a mistake. models.py: class Cart(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) session_key = models.CharField(max_length=200, blank=True) product = models.ManyToManyField(Product, related_name='product_items') views.py: @api_view(['GET']) def addToCart(request, pk): product = Product.objects.get(id=pk) if request.user.is_authenticated: #user is authenticated mycart = Cart.objects.get_or_create(user=request.user) mycart.product.add(product) # <--- here is the problem else: print(request.session.session_key) return Response({'response':'ok'}) urls.py: path('addToCart/<str:pk>/', views.addToCart, name='addToCart'), What I need to change to add the product to the cart?