Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError: academic() missing 1 required positional argument: 'request'
I can not pass request to views.py to serializers.py. Views.py def academic(request): is_superuser = request.user.is_superuser getdata = is_superuser return getdata serializers.py class SohanSerializer(serializers.ModelSerializer): is_name = True is_academic = views.academic //Here I call the academic fuction from views if is_academic: academic = Academic(many=True,read_only=True) else: academic = serializers.HiddenField(default=None) if is_name: pass else: name = serializers.HiddenField(default=None) class Meta: model = Student fields = ['name','studentID','email','image','phone','blood','address','academic'] is_academic = views.academic //Here I call the academic fuction from views Server is running but I can't get exact result. When I pass is_academic = views.academic() It's returned TypeError: academic() missing 1 required positional argument: 'request' I think I need to pass request inside the function as like is_academic = views.academic(request) but this not working. Please help me to pass the request inside the is_academic = views.academic(request) Or tell me any way to pass the request. -
Github Actions running 0 tests
I have three tests in my Django project which get executed running "python manage.py test appname" locally. However, Github Actions runs zero tests, returning no errors. How can I fix this? I would prefer not to use any more libraries if possible. I am using the default Django workflow. name: Django CI on: push: branches: [ main ] pull_request: branches: [ main ] jobs: build: runs-on: ubuntu-latest strategy: max-parallel: 4 matrix: python-version: [3.7, 3.8, 3.9] steps: - uses: actions/checkout@v2 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v2 with: python-version: ${{ matrix.python-version }} - name: Install Dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt - name: Run Tests run: | python manage.py test appname I tried using "python manage.py test" both with and without the appname, neither work. -
django.template.exceptions.TemplateDoesNotExist: documents/project_confirm_delete.html
I used Django 3.2.9 and used a class in order to delete a project. Here is my code. from django.views.generic.edit import CreateView, DeleteView, UpdateView class ProjectDeleteView(DeleteView): http_method_names = ['get'] model = Project pk_url_kwarg = "pk" def get_success_url(self): return reverse("documents:draftdocumentview") When I called it said like this; django.template.exceptions.TemplateDoesNotExist: documents/project_confirm_delete.html I am not sure about the project_confirm_delete.html. Should I make the html file? Or it is supported from Django Template? -
creating an email-defined user in django
I am creating a simple web app in django in which users are identified by their email and not a username. I've been following the guide: https://www.fomfus.com/articles/how-to-use-email-as-username-for-django-authentication-removing-the-username/ And it works fine! Yet, if I choose to have two other required fields the creation of the superuser fails, while the creation of a normal user does not. Can someone help me understand why? user app - models.py from django.contrib.auth.models import AbstractUser, BaseUserManager from django.db import models from django.utils.translation import ugettext_lazy as _ class UserManager(BaseUserManager): """Define a model manager for User model with no username field.""" use_in_migrations = True def _create_user(self, email, first_name, last_name, password, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user = self.model(first_name=first_name, **extra_fields) user = self.model(last_name=last_name, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, first_name, last_name, password=None, **extra_fields): """Create and save a regular User with the given email and password.""" extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, first_name, last_name, password, **extra_fields) def create_superuser(self, email, first_name, last_name, password, **extra_fields): """Create and save a SuperUser with the given email and password.""" extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: … -
Decode pako deflate, gzip in python
Encoded data should be sent from my front server to reduce data weight, I want to use pako deflate or gzip for this. const compressed = deflate(JSON.stringify({ project: projectId, title: screen.title, }, {to: "string"})); const res = await fetch( screensApiConfg.SCREENS_PATHS.create(), { credentials: "include", method: "POST", body: JSON.stringify(compressed), headers: { "Content-Type": "application/json", }, }, ); After coding, I get this: Uint8Array(43) [120, 156, 171, 86, 42, 40, 202, 207, 74, 77, 46, 81, 178, 50, 50, 212, 81, 42, 201, 44, 201, 73, 85, 178, 82, 114, 43, 74, 204, 77, 85, 176, 52, 52, 55, 84, 170, 5, 0, 205, 0, 10, 190, buffer: ArrayBuffer(43), byteLength: 43, byteOffset: 0, length: 43] I transfer this data to my django backend. How can I decode this data back, I tried using zlib.decompress but it didn't work for me. class CreateScreenApi(generics.CreateAPIView): serializer_class = ScreenSerializer def post(self, request, *args, **kwargs): print(request.data) data = list(request.data.values()) print(data) First, I get the data in the form of a dictionary and then translate it into a list. Dict: {'0': 120, '1': 156, '2': 171, '3': 86, '4': 42, '5': 40, '6': 202, '7': 207, '8': 74, '9': 77, '10': 46, '11': 81, '12': 178, '13': 50, '14': 50, … -
Django running port 8000 but image port is 80 in production
I have Serialized my model and it's working well except an issue This is my serializers.py class AuthorSerializer(serializers.ModelSerializer): class Meta: model = User fields = ("first_name", "last_name", "avatar",) this is what i am seeing in browser, Please have a look at this, the address bar port and image port are not same. It's working well, the issue occures when i run the project on Docker using nginx and gunicorn Here you go for my nginx config. server { listen 8000; location /static { alias /backend/staticfiles; } location /media { alias /backend/media; } location / { proxy_pass http://backend:8000; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } } and this is my docker-compose.yml version: '3.7' services: backend: build: context: . volumes: - static_data:/backend/staticfiles - "./dist/media:/backend/media" # map to local machine env_file: # if .env in root, we have to show .env here must - ./.env depends_on: - db proxy: build: context: ./proxy volumes: - static_data:/backend/staticfiles - "./dist/media:/backend/media" # map to local machine ports: - "8000:8000" env_file: # if .env in root, we have to show .env here must - ./.env depends_on: - backend - db db: image: postgres volumes: - database:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres ports: - "5432:5432" … -
django collectstatic picking files from wrong location
I am beginner in Python and Django. I am using Windows10 and I have installed Python 3.10.0 and pip 21.3.1. I installed Django using following commands pip install virtualenvwrapper-win mkvirtualenv firstdjango pip install django django-admin startproject demo then I created APP for just simple static HTML page and now I am trying to use static files. I created a folder having name "static" on root and placed all css, js etc files in it and in settings.py, I mentioned following. STATIC_URL = '/static/' STATICFILES_DIR = [ os.path.join(BASE_DIR, 'static') ] STATIC_ROOT = os.path.join(BASE_DIR,'assets') Now when I hit python manage.py collectstatic then it is not copying, what is in my static folder to assests folder. When I tried to check from where collectstatic is trying to copy using following command python manage.py findstatic -v 3 dummy then I got following C:\Users\dell\Envs\firstdjango\lib\site-packages\django\contrib\admin\static but my project location is E:\django\demo I am not getting, why collectstatic is not able to copy correct files and hence I do not get correct paths of my css, js and images in my web page. -
How to avoid that Django adds url link to every html element that follows the link
i would like to achieve something very basic in Django but can't find out what I am doing wrong. On my apps "index.html", I would like to add a button which redirects to another html template ("site.html") with other content. I added the following to "index.html" which is working: <body> <h2>foo</h2> {% block content %} <button><a href="{% url 'site' %}"/>Click</button> {% endblock %} <p>bar</p> </body> Clicking on the button gets me to "site.html", however all html items which I add on "index.html", for example the paragraph "bar" would also get rendered as hyperlink. I tried creating different Django blocks or making different html sections but that doesn't fix it. Thank you for your help. -
is it possible to use celery with sqs without django
I am following the celery tutorial, trying to have a local celery worker connect to an SQS queue that I have running on AWS (I am a complete noob on SQS/Celery). This is my task.py: from celery import Celery from kombu.utils.url import safequote # fake keys here and in the rest of the question, I am using actual valid creds aws_access_key = safequote("ABCDEFGFHIKJ:") aws_secret_key = safequote("abcdefgjk12345678/abcd/123/secretkey") broker_transport_options = {'region': 'us-west-2'} broker_url=f"sqs://{aws_access_key}:{aws_secret_key}@" app = Celery('tasks', broker=broker_url) @app.task def add(x, y): return x + y but according to the logs, it seems this is not trying to reach AWS at all: [2021-12-03 12:59:46,358: WARNING/MainProcess] No hostname was supplied. Reverting to default 'None' [2021-12-03 12:59:46,359: INFO/MainProcess] Connected to sqs://ABCDEFGHIJK:**@localhost// [2021-12-03 12:59:47,203: INFO/MainProcess] celery@ac78958533de ready. I tried specifying the hostname for the queue inside the broker url (I assumed this would work, but it doesn't) # setting the host after the @ without https fails broker_url=f"sqs://{aws_access_key}:{aws_secret_key}@"sqs.us-west-2.amazonaws.com/123456788/my-queue" # errors with Unrecoverable error: ClientError("An error occurred (SignatureDoesNotMatch) when calling the ListQueues operation: Credential should be scoped to a valid region, not 'us-east-1' Above error is kinda weird, because my queue lives in us-west-2 as I set in the broker_transport_options specifically to us-west-2. I also tried passing … -
django validate values for calculation
Hej! I need to do some simple calculations of filtered data in my django view. This works just fine when having values in the chosen filter. If the value is 0 or None I get an server error and the site collpases. Therefore I need a validator to make sure the given value is not 0 and not None. (my attempt is at the bottom) Currently if the validator is added it gives me the message that 'float' object is not callable, even before getting to the filter option/template. And: in my model is a m2m to the model where I get the values from. For each value can a unit be chosen and I only want to calculate if the units are identical, otherwise I want to get a warning. Does anyone knows how to achieve that? Or where to look? Any help is appreciated! :) # validators.py def validate_values(value): if value == 0: raise ValidationError(_('One of the given values is 0 or empty and the calculation therefore cannot be proceeded.'), code='notinrange') # views.py def process_mass_intensity(request): plants = Plant.objects.all() myFilter = PlantsNameFilter(request.GET, queryset=plants) plants = myFilter.qs total_m = plants.aggregate(Sum('used_in_plant__value'))['used_in_plant__value__sum'] product_m = plants.aggregate(product_mass=Sum('used_in_plant__value', filter=Q(used_in_plant__input_or_output='OUT')))['product_mass'](validators=[validate_values]) pmi = (total_m / product_m)(validators=[validate_values]) context … -
How to update django vairable inside javascript
Like we can access a variable in the JS part like "{{vaiable_name}}". How can we update the value of variable_name inside the javascript? -
time data 'Fri, 03 Dec 2021 11:43:35' does not match format '%a, %b %Y %H:%M:%S'
I have the following string:"Fri, 03 Dec 2021 11:43:55". I want to convert it to datetime with python.I am using strptime to convert it to datetime but it doesn't work. Here is my code from datetime import datetime dte_str = "Fri, 03 Dec 2021 11:43:55" dte = datetime.strptime(dte_str,"%a,%d %b %Y %H:%M:%S") time data 'Fri, 03 Dec 2021 11:43:35' does not match format '%a, %b %Y %H:%M:%S' How to solve the problem please! -
is there any way or package by which we can perform filters(searching) on custom raw sql query in django?
I read the below document : https://docs.djangoproject.com/en/3.2/topics/db/sql/ in model there are lots of filter lookup available like field__gt, field__lt, field__range, field__contains but i want to use these into raw sql like suppose query = SELECT * FROM customers WHERE customers.name like '%name%' and age < 30 and status IN ('active','pending') Here : customers.name like '%name%' name would be user input so i want to protect it from sql injection as well as filter it using % operator age < 30 30 would be user input, and want to perform < > = also IN ('active','pending') want to pass list of string using IN operator is there any proper way/package available by which we can run raw sql preventing sql injection as well as filtering data using %, IN, <, >, = operators. -
how to automatically redirect the user to a specific language in django
I have added new languages to my website and now it is available in English, French and Arabic Everything works fine, I couldn't figure out how to change the default language Currently when the user does not select any language, the site is displayed in English. Some users are complaining that English is not widely used in my country and the site should be in Arabic instead, so I want to do this: if the user does not select any language it will be redirected automatically to arabic. So when i visit my website like this: http://127.0.0.1:8000/ i will be automatically redirected to: http://127.0.0.1:8000/ar/ Is it possible to do something like this or do I have to change the default code for the whole website. i have this code in urls.py urlpatterns = [ path('admin/', admin.site.urls), path('',include('core.urls')), path('user/',include('users.urls')), path('dashboard/',include('dashboard.urls')), path('wallet/',include('wallet.urls')), path('administration/',include('administration.urls')), path('chaining/', include('smart_selects.urls')), path('__debug__/', include(debug_toolbar.urls)), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += i18n_patterns ( path('',include('core.urls')), path('user/',include('users.urls')), path('dashboard/',include('dashboard.urls')), path('wallet/',include('wallet.urls')), path('administration/',include('administration.urls')), ) and this is my settings from django.utils.translation import gettext_lazy as _ LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) LANGUAGE_CODE = 'en' LANGUAGES =( ('en', ('english')), ('ar', ('Arabic')), ('fr', ('french')) ) -
Django webpack loader vuejs+typescript Refused to execute script frombecause its MIME type ('text/html') is not executable
I am using Django as backend and Vue3 as frontend in my application. In development server i did not have problem but now in production i am having problems to render the page. I have followed all the documentations but cannot find a solution. I am using django-webpack-loader to render the bundle which I formed using webpack5. But now i am getting an error hence thinking that django is trying to render fallback page. Refused to execute script from 'https://medtourism.uk/app-a7abdc6b502c1335fd69.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. My webpack.config.js module.exports = { mode:'production', entry:{ app: path.resolve(__dirname, './src/main.ts'), }, output: { filename: '[name]-[hash].js', path: path.resolve(__dirname, './assets/dist'), clean: true, }, module: { rules: [ { test: /\.vue$/, use: 'vue-loader' }, { test: /\.ts$/, loader: 'ts-loader', options: { appendTsSuffixTo: [/\.vue$/], } }, { test: /\.css$/i, use: [ "style-loader", "css-loader"], }, { test: /\.(png|jpe?g|gif|svg|eot|ttf|woff|woff2)$/i, // More information here https://webpack.js.org/guides/asset-modules/ type: "asset", }, ] }, resolve: { extensions: ['.ts', '.js', '.vue', '.json'], alias: { 'vue': '@vue/runtime-dom', 'bulma': 'bulma/css/bulma.css', } }, plugins: [ new VueLoaderPlugin(), new BundleTracker({ filename: './webpack-stats.json', publicPath: '/' }) ] }; my typescript config: { "compilerOptions": { "allowJs": true, "allowSyntheticDefaultImports": true, "declaration": false, "esModuleInterop": true, … -
Time Difference in Django Model
I am making a Django Software for a flight school to be made. I am trying to work on time difference between Arrival Time and Departure time to give me an Actual Elapsed Time. I post the code here: Models class LogEntry(models.Model): aircraft = models.ForeignKey(Aircraft, on_delete=models.CASCADE) from_aerodrome = models.ForeignKey( Aerodrome, on_delete=models.PROTECT, related_name='from_aerodrome') to_aerodrome = models.ForeignKey( Aerodrome, on_delete=models.PROTECT, related_name='to_aerodrome') departure_time = models.TimeField() arrival_time = models.TimeField() pilot = models.ForeignKey( Pilot, on_delete=models.PROTECT, related_name='pilot') instructor = models.ForeignKey( Pilot, on_delete=models.PROTECT, related_name='instructor', blank=True, null=True) date = models.DateField(auto_now_add=True) remarks = models.CharField(max_length=1000, blank=True, null=True) eet = models.CharField(max_length=255) @property def get_eet(self): aet = self.arrival_time - self.departure_time return aet def save(self, *args, **kwargs): self.eet = self.get_eet super(LogEntry, self).save(*args, **kwargs) class Meta: ordering = ('-arrival_time',) verbose_name_plural = 'Log Entries' Views: def insert_flight(request): aircraft = Aircraft.objects.all() aerodrome = Aerodrome.objects.all() pilot = Pilot.objects.all() if request.method == 'POST': aircraft_id = request.POST.get('aircraft') from_aerodrome = request.POST.get('from_aerodrome') to_aerodrome = request.POST.get('to_aerodrome') departure_time = request.POST.get('departure_time') arrival_time = request.POST.get('arrival_time') pilot = request.POST.get('pilot') instructor = request.POST.get('instructor') log_entry = LogEntry(aircraft_id=aircraft_id, from_aerodrome_id=from_aerodrome, to_aerodrome_id=to_aerodrome, departure_time=departure_time, arrival_time=arrival_time, pilot_id=pilot, instructor_id=instructor) log_entry.save() context = { 'aircraft': aircraft, 'aerodrome': aerodrome, 'pilot': pilot, } return render(request, 'flight/insert_flight.html', context) The error I am getting is: Error: TypeError: unsupported operand type(s) for -: 'str' and 'str' What am I doing wrong? … -
Python unittest change mock patch value on fly
I'm having trouble while dealing with patching. I'm using mock from unittest library. While testing check_codes() view I would like to set another values to db.find_one() api.utils.py from pymongo import MongoClient import os def get_share_code_collection(): client = MongoClient(os.getenv("DB_HOST")) db_handle = client[os.getenv("DB_NAME")] return db_handle["share_codes"] views.py def check_codes(self, request): db = get_share_code_collection() data = db.find_one({"specialist_id": {"$exists": True}}) test_views.py from unittest import mock @mock.patch("api.utils.get_share_code_collection") def test_share_code_correct_no_share_types( self, mocked_collection, mocked_share_code, user_model ): mocked_collection().find_one.return_value = True ... @mock.patch("api.utils.get_share_code_collection") def test_share_code_no_start_time( self, mocked_collection, user_model ): mocked_collection().find_one.return_value = False ... The only workaround I found is setting mocked_collection().find_one.side_effect = [True,False] but once it is initialized I can't add values. How can I deal with the problem? -
How do I limit read permissions of django media files stored on digitalocean only to my frontend?
I have a django project with react.js frontend deployed to DigitalOcean where users can upload their files. I'm using S3Boto3Storage. I know I can make media files public by setting default_acl = "public-read", but I want to grant read access to these files only to the requests from my frontend domain name, while keeping them private from all others. How can I do that? -
Updating a field's attributes on ModelForm instance doesn't work in Django
I'm trying to add the id field "company-select" to the field of a ModelForm. However, when rendering the form, it doesn't apply the provided custom id. I applied the logic to my form according to the official docs. class CompanyForm(ModelForm): """ A form to render a select widget with companies associated to a user """ name = forms.ModelChoiceField(queryset=Company.objects.exclude(name='exclude-all'), required=True) class Meta: model = Company fields = ('name',) widgets = { 'name': Select(attrs={'id': 'company-select'}), } renders <select name="name" required="" id="id_name"> <option value="" selected="">---------</option> <option value="25">Test Company</option> ... </select> # forms.py def render_entities(request): """View to render the entities overview page""" # Get the logged in user instance user = User.objects.get(username=request.user.username) user_cashpool = Cashpool.objects.get(company__user=user) # Get the info for the site visited dashboard_site = 'entities' if request.method == 'GET': # Return the form and populate with user's company company = user.company # Query all entities associated to the cashpool companies = Company.objects.filter(cashpool=user_cashpool).order_by('name') # Pass the queryset to the Select Form CompanyForm.base_fields['name'] = forms.ModelChoiceField( queryset=companies) # Return the form form = CompanyForm() context = { 'company': company, 'companies': companies, 'dashboard_site': dashboard_site, 'form': form } return render(request, 'dashboard/dashboard_entities.html', context) -
Angular to Django, passing multiple parameters in a service call
I have some working code on Django, where i created a simple file uploader with a date picker that is passed through a view and then uploaded onto a database using a standalone python class that utilise sqlalchemy. However, I have been working on migrating the UI aspect onto an Angular Front End, but hit a road block and not sure where I am going wrong. The user needs to be able upload a excel binary file, input a date and hit upload. This should send a request to a view which then handles the request. The view it self works perfectly, when the file and dates are inputted from the Django HTML template. But I can't seem to make it work once the inputs come from Angular. At the moment I am getting a 'Unsupported Media Type" Error message. But my guess is i am not passing the file and date correctly to the service. Any help would be great Here is my code views.py @api_view(('POST',)) @csrf_exempt def uploader(request): if request.method == 'POST': try: instance= uploader(request.FILES['data'], request.POST['selectedDate']) _ = upload_instance.run_upload_process('data') upload_message = "Success" return Response(upload_message, status=status.HTTP_201_CREATED) except Exception as e: upload_message = 'Error: ' + str(e) return Response(upload_message, status=status.HTTP_400_BAD_REQUEST) … -
how we can implement this coniditon in django template
How i can implement this condition in django template with multiple and or statement in if? {% if ((email_setting.twitter_link is not None and email_setting.twitter_link != '') or (email_setting.instagram_link is not None and email_setting.instagram_link != '') or (email_setting.fb_link is not None and email_setting.fb_link!= '') ) %} Here my body {% endif %} this give me an error TemplateSyntaxError at /settings/emailView Could not parse the remainder: '((email_setting.twitter_link' from '((email_setting.twitter_link' -
Django Rest Framework Prefetch_Related Order_By api result not ordered
I am trying to order the results of an api query by a prefetched field but it returns the results in the order of item_id Models class ItemDetails(models.Model): item_id = models.BigIntegerField(blank=True, null=False, primary_key=True) name = models.TextField(blank=True, null=True) class ItemRatings(models.Model): id = models.BigIntegerField(blank=True, null=False, primary_key=True) item_id = models.ForeignKey('app.ItemDetails', on_delete=CASCADE, to_field='item_id ', related_name='ratings', db_column='item_id') rating= models.FloatField(blank=True, null=True) Views class ItemList(viewsets.ModelViewSet): def get_queryset(self): prefetch = Prefetch('ratings', queryset=ItemRatings.objects.order_by('rating')) return ItemDetails.objects.prefetch_related(prefetch) serializer_class = ItemListSerializer Serializers class ItemRatingsSerializer(serializers.ModelSerializer): class Meta: model = ItemRatings exclude = ('id', 'item_id') class ItemListSerializer(serializers.ModelSerializer): ratings = ItemRatingsSerializer(required=True, many=True) class Meta: model = ItemDetails fields = '__all__' Ive tried adding .all() after objects and at the end of the return statement in the get_queryset statement Any help is appreciated thank you -
Django Admin get_fieldsets kills User add form. Cannot add User
All hands, what I was trying to do is to filter UserChange fieldsets on the basis of user access. Just to remove some fields if user is not superuser And it worked. However later I discovered that I cannot create User as the start form with user name and two password fields is non existent anymore. So, Django keeps showing me red sign of mistakes as simply there are not required fields visible and I cannot fill them up. I removed all my code and found out that the simple fact of having this get_fieldsets function changes the add_form I tried to add specific user add form, I tried add_fieldsets - everything with no result until I have get_fieldsets() in my UserAdmin. Any ideas what I am doing wrong? -
How to get TLS/SSL information from request session in python?
I am working on updating django application services with TLS configuration to restrict the versions used as well as the ciphers in each version. For that purpose I am using HTTPAdapter and I mount the session with different ssl options. My question is that is there a way to get information of the mounted adapters in python? or anyway to check the tls/ssl settings in a created session? -
Django permission_required - how to detect if user has admin perm
I want to ask and know, how to detect with decorator befero view method if user is admin. Thanks.