Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i load all fixtures inside particular directory While writing TestCases in Djnago using Pytest
I have multiple fixtures(json files) inside admin folder and i need to load all the fixtures of that directory without mannuallly writing all fixtures location. I have tried below code but but it's not working @pytest.fixture(scope='session') def load_admin_data(django_db_setup, django_db_blocker): fixtures = [ 'fixtures_for_tests/admin/*.json' ] with django_db_blocker.unblock(): call_command('loaddata', *fixtures) I need to give each and every fixture's location like shown below: @pytest.fixture(scope='session') def load_admin_data(django_db_setup, django_db_blocker): fixtures = [ 'fixtures_for_tests/admin/data1.json', 'fixtures_for_tests/admin/data2.json', ] with django_db_blocker.unblock(): call_command('loaddata', *fixtures) Note: One approch which i figure out is get all fixture location using some script is there any other way to give fixture location using some regex pattern while loaddata? I'm expecting that i'm able to give dyanamic path or regex pattern of fixture location -
Uncaught TypeError: $.ajax is not a function in Django
I have a function that works in the following manner: function ajax_display_schema_helper(schema_name){ $.ajax({ ... ... ... }); }; ajax_display_schema_helper('example schema'); But when I call the function above as following: $('.dropdown-item').click(function() { ajax_display_schema_helper(schema_name); }); I get the "$.ajax is not a function" error. What is the reason that it doesn't work when the function is called in the second way? -
Django allauth google login with Google identity
The google sign in javascript library is being deprecated: Warning: The Google Sign-In JavaScript platform library for Web is deprecated, and unavailable for download after March 31, 2023. The solutions in this guide are based on this library and therefore also deprecated. Use instead the new Google Identity Services for Web solution to quickly and easily sign users into your app using their Google accounts. By default, new client IDs are now blocked from using the older platform library; existing client IDs are unaffected. New client IDs created before July 29th, 2022 may set the plugin_name to enable use of the legacy Google platform library. The existing oauth implementation from django-allauth requires the users to either use server-based redirect with the Oauth2.0 code or send in both the access_token and id_token for processing the login, The implementation by google now only gives us the id_token and all the required data like name, profile picture etc. is included in the JWT token. Thus, the login fails as I am unable to send in both the access token and the id token. There are two approaches that come to my mind for solving this: I either override the social login view and … -
Why getting g++ not recognized as a command while running subprocess in python?
I have an online ide which takes code and language from the user and upon submitting the server has to execute the file. I have g++ installed on my system still upon execution I get the following error in subprocess module: 'g++' is not recognized as an internal or external command, operable program or batch file. '.' is not recognized as an internal or external command, operable program or batch file. The function for file execution is : def execute_file(file_name,language): if(language=="cpp"): #g++ xyz.cpp subprocess.call(["g++","code/" + file_name],shell=True) #this only compiles the code subprocess.call(["./a.out"],shell=True) #this executes the compiled file. my code file is there in the /code directory. The directory structure is : -
django.db.utils.ProgrammingError: column tickets_ticket.track_code does not exist
I used postgresql and I want add a new field to my model: track_code = models.CharField(max_length=32, verbose_name=_('کد رهگیری'), default=generate_rrr_unique_trackcode) but after migrate i received this error: django.db.utils.ProgrammingError: column tickets_ticket.track_code does not exist LINE 1: SELECT (1) AS "a" FROM "tickets_ticket" WHERE "tickets_ticke... I used the command: python3 manage.py migrate app_name 0001 and delete the last migration file and then try again but not working... -
How to import csv or json file into the model & create taboe for that data
I've a csv/json file. I need to include the file as a database for the django app. & I need to show the data as a table in frontend. So can't understand where I should insert the file so that it create table for me. I've create a django web application. With a app. Just trying to import file intothe model but in dbsqlite there is no change. -
drf Writable nested serializers "This field is required."
Here is the code: Models.py class Question(models.Model): lesson = models.ForeignKey(Lesson, on_delete=models.CASCADE, related_name='questions') question = models.CharField('lesson name', max_length=120) class Option(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='options') option = models.CharField('test option', max_length=100) correct = models.BooleanField(default=False) Views.py class QuestionAPIView(generics.CreateAPIView): queryset = Question.objects.all() serializer_class = QuestionSerializer Serializers.py class OptionSerializer(serializers.ModelSerializer): class Meta: model = Option fields = ('option', 'correct') class QuestionSerializer(serializers.ModelSerializer): options = OptionSerializer(many=True) class Meta: model = Question fields = ('lesson', 'question', 'options') def create(self, validated_data): options_data = validated_data.pop('options') question = Question.objects.create(**validated_data) for option_data in options_data: Option.objects.create(question=question, **option_data) return question I'm try create test question with few option of answers like this: data = { "lesson": 2, "question": "This is our first question?", "options": [ { "option": "Option 1", "correct": True }, { "option": "Option 2 ", "correct": False }, { "option": "Option 3", "correct": True } ] } But in postman and in the TestCase I've got: { "options": [ "This field is required." ] } What is the problem of validation? Documentation here https://www.django-rest-framework.org/api-guide/relations/#writable-nested-serializers Thanks. -
How to return a value from javascript function to django template in the same view?
I am just getting a value from an input tag by javascript. But Now I need to pass this value to the Django template on the same page to do my required task. <!DOCTYPE HTML> <HTML> <body> <h1>In Django Template</h1> <input type="text" id="agency_id" name="fname" value="1"> <select class="select" name="delivery_agent" id="DeliveryAgent"> <option class="form-control" value="{{ agent.id }}" {% if agent.id == delivery_agency_id %} selected="selected" {% endif %}>{{ agent.name }} </option> {% endfor %} </select> <script> var delivery_agency_id = document.getElementById("agency_id").value; alert(delivery_agency_id ) </script> Here, I am getting the agency_id by script. Now I need to pass it to the if condition as above code. Please help me to solve it. -
Reset Avatar ImageField to Default when User Clear Avatar Through DRF or Django Admin
I have django model ImageField called avatar. I want to enable user clear their avatar, so Blank = True. The problem is when user clear their avatar, the ImageField path is now empty. What i want is, the ImageField back to default. models.py class Profile(models.Model): AVATAR_UPLOAD_TO = "account_avatar/" DEFAULT_AVATAR = "default.jpg" user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) avatar = sorl.thumbnail.ImageField(upload_to=AVATAR_UPLOAD_TO, default=AVATAR_UPLOAD_TO+DEFAULT_AVATAR, blank=True, null=True) I see some related questions Django ImageField overwrites existing path when empty. But the behaviour is not exactly what i want. This answer required the user to upload new avatar, so user couldn't clear their avatar. Another related questions Django - How to reset model fields to their default value?. But i can't implement the save() method on my models I have tried to implement save() method on Profile model, but it don't work as expected def save(self, *args, **kwargs): if not self.avatar.name: setattr(self, 'avatar.name', self.avatar.field.default) super().save(*args, **kwargs) # Call the "real" save() method. I am new to Django and Django Rest Framework. Please help me, i stuck with this problem from a few days ago. Could you please help with my problems. Thanks in advance! -
Share env across GitHub Actions workflows
I have a GitHub Action (test-python.yml) intended to test a Django application. It utilizes the env tag like so towards the top of the file: env: SECRET_KEY: test DEBUG: False ... I want to make another workflow - not a job in the same workflow - that is reliant on the same variables. I could obviously just make another file for said workflow and copy the env however this seems slightly flaky, I'd rather somehow share the env variables across numerous workflows so I only have to keep it up to date in one place. Is there a way to do this? Thank you in advance! -
I am developing ecommerce website from django. While integrating payment on the project and running the server I got page not found error (404)
The error I got while I enter the customer detail and click on checkout: This is my views.py of payment. Here I have imported stripe module using stripe api and created checkout session: from django.shortcuts import render, redirect, reverse, get_object_or_404 from decimal import Decimal import stripe from django.conf import settings from orders.models import Order # Create your views here. stripe.api_key = settings.STRIPE_SECRET_KEY stripe.api_version = settings.STRIPE_API_VERSION def payment_process(request): order_id = request.session.get('order_id', None) order = get_object_or_404(Order, id=order_id) if request.method == 'POST': success_url = request.build_absolute_uri(reverse('payment:completed')) cancel_url = request.build_absolute_uri(reverse('payment:canceled')) session_data = { 'mode': 'payment', 'client_reference_id': order_id, 'success_url': success_url, 'cancel_url': cancel_url, 'line_items': [] } for item in order.items.all(): session_data['line_items'].append({ 'price_data': { 'unit_amount': int(item.price * Decimal(100)), 'currency': 'usd', 'product_data': { 'name': item.product.name, }, }, 'quantity': item.quantity, }) session = stripe.checkout.Session.create(**session_data) return redirect(session.url, code=303) else: return render(request, 'payment/process.html', locals()) def payment_completed(request): return render(request, 'payment/completed.html') def payment_canceled(request): return render(request, 'payment/canceled.html') This is urls.py of payment where I have created URL patterns for process where the order summary is displayed, stripe checkout session. completed for the successfull payment and canceled for payment cancelation. : from django.urls import path from . import views app_name = 'payment' urlpatterns = [ path('canceled/', views.payment_canceled, name='canceled'), path('completed/', views.payment_completed, name='completed'), path('process/', views.payment_process, name='process'), ] This … -
How to run external python file and show data in front end of django in the form of table
Hi Guys I want to run my external py scipt and the output will be on json I want to show the data in form of rows and table in front end, the data is dynamic regression testing data. how to I show that using django -
What is the best way to parse this request.data in drf, when the request is form-data?
I have this form which sends an image along with some other data. I am using django-rest-framework in the back end. I need to take out couple of fields from this form input and do some operations and use the remaining fields to send to my ModelSerializer for posting the form data. What is the best way to achieve this? <QueryDict: {'areaName': ['Mall-24F'], 'devices': ['[\n {\n "name": "device_001",\n "coordinates": [\n 23,\n 56\n ],\n },\n {\n "name": "device_002",\n "coordinates": [\n 24,\n 57\n ],\n },\n {\n "name": "device_003",\n "coordinates": [\n 25,\n 58\n ],\n }\n]'], 'floorMap': [<InMemoryUploadedFile: 1653650801973.png (image/png)>]}> This is how request.data looks like. What I have tried doing is context = request.data context["name"] = context.pop("areaName")[0] context["floor_map"] = context.pop("floorMap")[0] Basically I only want "name" and "floor_map" to be sent to ModelSerializer. I have read that request.data is immutable, but here it is mutable. I think I am missing something. -
Heroku: python version problems
I am trying to deploy a Django app on Heroku, but I am having compatibility issues with the requirements.txt file, it specifies "python-3.11.1". According to Heroku's documentation, Heroku stack 22 supports Python 3.11.1. But each time I try to deploy using the Heroku CLI, I get an error message. -----> Building on the Heroku-22 stack -----> Using buildpack: heroku/python -----> Python app detected -----> Using Python version specified in runtime.txt Traceback (most recent call last): File "/tmp/codon/tmp/buildpacks/0f40890b54a617ec2334fac0439a123c6a0c1136/vendor/runtime-fixer", line 8, in <module> r = f.read().strip() File "/usr/lib/python3.10/codecs.py", line 322, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte /tmp/codon/tmp/buildpacks/0f40890b54a617ec2334fac0439a123c6a0c1136/bin/steps/python: line 9: warning: command substitution: ignored null byte in input ! Requested runtime '��python-3.11.1 ! For supported versions, see: https://devcenter.heroku.com/articles/python-support ! Push rejected, failed to compile Python app. ! Push failed I tried git push heroku master I have followed the buildpack checking tutorial in the documentation: heroku buildpacks heroku buildpacks:clear heroku buildpacks:add heroku/python -
My Paginator not working at the last page button
when click next and previous button is working, but the last page not working model.py class VenueForm(ModelForm): class Meta: model = Venue fields = ( 'name', 'address', 'zip_code', 'phone', 'web', 'email_address' ) labels = { 'name': '', 'address': '', 'zip_code': '', 'phone': '', 'web': '', 'email_address': '', } widgets = { 'name': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Venue Name'}), 'address': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Address'}), 'zip_code': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Zip Code'}), 'phone': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Phone'}), 'web': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Web'}), 'email_address': forms.EmailInput( attrs={'class': 'form-control', 'placeholder': 'Email'}), } view.py from .models import Event, Venue from django.core.paginator import Paginator def list_venues(request): venue_list = Venue.objects.all() p = Paginator(Venue.objects.all(), 3) page = request.GET.get('page') venues = p.get_page(page) nums = "a" * venues.paginator.num_pages return render(request, 'events/venue.html', { 'venue_list': venue_list, 'venues': venues, 'nums': nums}) events/venue.html <nav aria-label="Page navigation example"> <ul class="pagination justify-content-center"> {% if venues.has_previous %} <li class="page-item"> <a class="page-link" href="?page=1">&laquo; First</a> </li> <li class="page-item"> <a class="page-link" href="?page={{ venues.previous_page_number }}">Previous</a> </li> {% endif %} {% for i in nums %} <li class="page-item"> <a class="page-link" href="?page={{ forloop.counter }}">{{ forloop.counter }} </a> </li> {% endfor %} {% if venues.has_next %} <li class="page-item"> <a class="page-link" href="?page={{ venues.next_page_number }}">Next</a> </li> <li class="page-item"> <a class="page-link" href="?page={{ venues.paginator.num_pages ))">Last &raquo;</a> … -
Force login not working with fixtures (Django TestCase)
I'm populating my test db via a fixture, and everything loads fine. However, I'm unable to get either login or force_login to work. User is also in the fixture. When I try to test the first view, it redirects to the login page. class TestUnauthUser(TestCase): fixtures = ['project.json'] @classmethod def setUpTestData(cls): cls.client = Client() # Get User and Login cls.unauth_user = User.objects.get(username='unauth_user') print(cls.unauth_user.pk) #cls.login = cls.client.login(username=cls.unauth_user.username, password=cls.unauth_user.password) cls.client.force_login(cls.unauth_user) # Get Project cls.project = Project.objects.get(slug='test-project') cls.slug_dict = {'slug': cls.project.slug} # Get Task cls.task = Task.objects.get(slug='test-task') def test_login(self): self.assertTrue(self.unauth_user.login) def test_project_view(self): # Project Main response = self.client.get(reverse('customerportal:project', kwargs=self.slug_dict)) self.assertEqual(response.status_code, 403) I'm able to verify that I have the correct user object with: print(cls.unauth_user.pk). So the User exists and is being obtained. But, it's still not logging-in successfully. -
Is there a way to do {% url 'blog' blog[i].slug %} in Django?
I want to make this type of loops: {% for i in length %} where lenth = range(len(blogs)) in views.py. And then into that loop I want to do: <a href="{% url 'single_blog' blogs[i].slug %}"> blogs go from views.py too: blogs = Blog.objects.all() But it shows an error, it says it can't use [i] in this construction. Please let me know, how can I use blogs[i] in Django HTML? Thanks. -
Preserve and display Django form inputs on POST submission
--PROBLEM-- I have created a basic calculator using Django. The app takes some basic form inputs before executing some calculations and returning the outcomes to the user, however I want the user's inputs to remain visible in the form on submission. At present the followin experience occurs. User enters values into form and submits using 'Calculate' button. Results are returned as expected but form and values are no longer present. User can press 'Calculate' button to return to start of process and blank form. --DESIRED OUTCOME-- --CODE-- forms.py from django import forms class InvestmentForm(forms.Form): starting_amount = forms.FloatField() number_of_years = forms.FloatField() return_rate = forms.FloatField() annual_additional_contribution = forms.FloatField() views.py from django.shortcuts import render from django.views import View from .forms import InvestmentForm class Index(View): def get(self, request): form = InvestmentForm() return render(request, 'loancalculator/index.html', {'form': form}) def post(self, request): form = InvestmentForm(request.POST) if form.is_valid(): total_result = form.cleaned_data['starting_amount'] total_interest = 0 yearly_results = {} for i in range(1, int(form.cleaned_data['number_of_years'] +1)): yearly_results[i] = {} # CALCULATE THE INTEREST interest = total_result * (form.cleaned_data['return_rate'] / 100) total_result += interest total_interest += interest # ADDITIONAL CONTRIBUTION total_result += form.cleaned_data['annual_additional_contribution'] # SET YEARLY RESULTS yearly_results[i]['interest'] = round(total_interest, 2) yearly_results[i]['total'] = round(total_result,2) # CREATE CONTEXT context = { 'total_result': round(total_result,2), … -
With a Django QuerySet, how to get a list of the included columns?
In the application context, we have a dynamic QuerySet that may return variable number of columns, e.g. date_of_birth in type Date, and/or postalcode in type Text, etc. We wonder how to get a list of the columns included in the QuerySet, including: the column's name the datatype of the column corresponding to the serializer fields of serializers.IntegerField, serializers.DateTimeField, etc. We appreciate hints and suggestions. -
TypeError: unhashable type: 'dict' in Django
I',m working on django rest project and i'm getting an err, i'm getting an error can anyone help, below is my code & d err msg def get(self, request, reference): transaction = walletTransaction.objects.get( paystack_payment_reference=reference, wallet__user=request.user) reference = transaction.paystack_payment_reference url = 'https://api.paystack.co/transaction/verify/{}'.format(reference) headers = { {"authorization": f"Bearer {settings.PAYSTACK_SECRET_KEY}"} } r = requests.get(url, headers=headers) err message File "/home/olaneat/Desktop/files/project/django/jobConnect/job-connect/wallet/serializers.py", line 59, in save headers = { TypeError: unhashable type: 'dict' can anyone help pls -
crispy_forms is not working : ModuleNotFoundError: No module named 'crispy_forms'
Steps that I followed pip install django-crispy-forms add inside setting.py INSTALLED_APPS = [ ... 'crispy_forms', ... ] and CRISPY_TEMPLATE_PACK = 'uni_form' press the run icon of pycharm (top right) I tried to install pip install -e git+git://github.com/maraujop/django-crispy-forms.git#egg=django-crispy-forms I tried to make a migration but same error. I tried to install with pipenv install django-crispy-forms. I don't have the error if I do : "python3 manage.py runserver" but crispy-forms doesn't work ERROR : ... File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2544.0_x64__qbz5n2kfra8p0\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'crispy_forms' -
Django simplejwt validate token
I am implementing authentication with Django simpleJwt, and have a question. I want to create something with Client's jwt token. I use methods provided from simpleJwt to validate and decode jwt token. class AccountBookAPIView(APIView): def post(self, request): jwt_authenticator = JWTAuthentication() raw_access_token = request.META.get('access_token') validated_token = jwt_authenticator.get_validated_token(raw_access_token) user = jwt_authenticator.get_user(validated_token) However, I doubt that some methods really validate token. So I checked the method's implementation. Below is the code for question. def get_validated_token(self, raw_token): """ Validates an encoded JSON web token and returns a validated token wrapper object. """ messages = [] for AuthToken in api_settings.AUTH_TOKEN_CLASSES: try: return AuthToken(raw_token) except TokenError as e: messages.append( { "token_class": AuthToken.__name__, "token_type": AuthToken.token_type, "message": e.args[0], } ) raise InvalidToken( { "detail": _("Given token not valid for any token type"), "messages": messages, } ) # this class is AuthToken in my opinion. class AccessToken(Token): token_type = "access" lifetime = api_settings.ACCESS_TOKEN_LIFETIME I can't find the point that validate token from Database. It looks like just construction of token for me. Don't I need to check token in the Database(blacklist and outstanding tokens)? Plz help me. Any answer is welcome. Below is my settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # my apps 'members', 'account_books', … -
WSGI django ModuleNotFoundError: No module named 'django'
I have been trying forever to get my django api to deploy via apache. I have installed mod_wsgi for python 3.7 and my venv is using python 3.7.15. Trying to go to my django app url I am getting a 500 error. Error log shows: [Tue Dec 20 21:31:30.690951 2022] [:error] [pid 19216] /usr [Tue Dec 20 21:31:30.691287 2022] [:error] [pid 19216] mod_wsgi (pid=19216): Target WSGI script '.../project/project/wsgi.py' cannot be loaded as Python module. [Tue Dec 20 21:31:30.691323 2022] [:error] [pid 19216] mod_wsgi (pid=19216): Exception occurred processing WSGI script '.../project/project/wsgi.py'. [Tue Dec 20 21:31:30.691393 2022] [:error] [pid 19216] Traceback (most recent call last): [Tue Dec 20 21:31:30.691423 2022] [:error] [pid 19216] File ".../project/project/wsgi.py", line 19, in <module> [Tue Dec 20 21:31:30.691428 2022] [:error] [pid 19216] from django.core.wsgi import get_wsgi_application [Tue Dec 20 21:31:30.691444 2022] [:error] [pid 19216] ModuleNotFoundError: No module named 'django' [Tue Dec 20 21:31:51.190670 2022] [:error] [pid 19217] 3.7.15 (default, Oct 31 2022, 22:44:31) [Tue Dec 20 21:31:51.190707 2022] [:error] [pid 19217] [GCC 7.3.1 20180712 (Red Hat 7.3.1-15)] apache conf file: <VirtualHost *:80> ServerName api.project.com DocumentRoot path/to/project/root WSGIScriptAlias / /path/to/wsgi.py WSGIDaemonProcess project-name processes=4 threads=1 display-name=%{GROUP} python-path=path/to/lib/python3.7/site-packages:/path/to/project/root WSGIProcessGroup project-group <Directory "/path/to/project/root"> Require all granted </Directory> #SSL stuff... </VirtualHost> wsgi.py: … -
django redirect to subdomain with exact same url
I have a Django website accessible at codewithbishal.com. This is basically a django blog website and all the blog articles are accessible at codewithbishal.com/example/<path> But now I want to completely restructure the website{such that it is accessible at blog.codewithbishal.com/<path>} and I do no want to lose the current SEO therefore I want to configure django redirect such that when someone launches codewithbishal.com/example/<path> through google search search result or directly through link, they are redirected to blog.codewithbishal.com/<path> instead of a 404 page and eventually google will start showing the new links instead of old once. -
Creating a simple multiple users app in Django
So I've created 3 different users: admins, developers, and project managers. When I use the individual signup forms for each of these users and log out, it works, but then I when try to use the login form, it seems to me that it's acting like the signup form. Because when I input the same user details as the one I just created into the login form, it throws up the built-in error message, 'A user with that user name already exists' I'm not sure how to proceed from here. Here's what I have so far. models.py class CustomUser(AbstractUser): ACCOUNT_TYPE_CHOICES = ( ('admin', 'Admin'), ('developer', 'Developer'), ('project_manager', 'Project Manager') ) account_type = models.CharField(max_length=20, choices=ACCOUNT_TYPE_CHOICES) login and signupviews class LoginView(View): def get(self, request): # Render the login form form = LoginForm() return render(request, 'users/login.html', {'form': form}) def post(self, request): # Get the form data from the request form = LoginForm(request.POST) # Validate the form data if form.is_valid(): # Get the username and password from the form username = form.cleaned_data['username'] password = form.cleaned_data['password'] # Authenticate the user user = authenticate(request, username=username, password=password) # If the user is authenticated, log them in and redirect to the homepage if user is not None: login(request, …