Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
How to get username in models.py?
models.py def upload_to(instance, filename): nowDate = datetime.now().strftime("%Y/%m/%d") return '/'.join(['verify', instance.user.username, nowDate, filename]) class UserVerifyImg(models.Model): username = models.ForeignKey( User, db_column='user_idx', on_delete=models.CASCADE ) business_type = models.CharField(max_length=255) image = models.ImageField(upload_to=upload_to) upload_date = models.DateTimeField(auto_now = True) class Meta: managed = False db_table = 'account_user_verify' I searched about instance.user.username but It is showed errer. AttributeError: 'UserVerifyImg' object has no attribute 'user' This is my error. -
Instance of djaform not updating
I have the next form in Django: class Medical(forms.ModelForm): worker= forms.ModelChoiceField( queryset=Worker.objects.none(), empty_label=None, widget=forms.Select(attrs={'class': 'form-control'}) ) description=forms.CharField( widget=forms.Textarea(attrs={'class': 'form-control'}) ) upload=forms.FileField( widget=forms.FileInput(attrs={'class': 'form-control'}) ) class Meta: model = Medical_Issue fields = ( 'worker', 'description', 'upload', ) def __init__(self, *args, **kwargs): user_id = kwargs.pop('user_id') method=kwargs.pop('method') super().__init__(*args, **kwargs) self.fields['worker'].queryset = Worker.objects.filter(user_id=user_id) def save(self, commit=True): m = super(Medical, self).save(commit=False) m.worker=self.cleaned_data['worker'] m.description=self.cleaned_data['description'] m.upload=self.cleaned_data['upload'] if commit: m.save() return m And following views: def medical_list(request): worker=Worker.objects.filter(user_id=request.user.id).get() issues=Medical_Issue.objects.filter(worker=worker.id).order_by('-created_at') return render(request,'medical_list.html', {'medical_issues':issues}) def medical_add(request): print(request.user.id) if request.method == "POST": form = Medical(request.POST,request.FILES,user_id=request.user, method= 'ADD') if form.is_valid(): form.save() return redirect('medical_list') else: form = Medical(user_id=request.user, method= 'ADD') return render(request, 'medical_add.html', {'method':'ADD','form': form}) def medical_edit(request,id_issue): worker=Worker.objects.get(user_id=request.user) issues=Medical_Issue.objects.filter(worker=worker).order_by('-created_at') issue= Medical_Issue.objects.get(id=id_issue) if request.method == 'GET': form = Medical(user_id=worker.user_id,instance=parte, method= 'EDIT') else: form = Medical(request.POST, request.FILES, user_id=worker.user_id, method= 'EDIT') if form.is_valid(): form.save() return redirect('medical_list') return render(request,'medical_add.html', {'method':'EDIT','form': form}) Main probles is when adding, it saves record just fine, but when editing, it is creating a new instance of the issue. I´m trying to make it modifying save method on form, but maybe it´s not the right approach? With thata said, I have tried to add an id field to the form, but same results from this Thanks -
Django Fatal Error Connection failed at local host
Django Fatal Error Connection failed at local host enter image description here -
Django - Many to Many Relationship with Workouts & Exercises
I'm currently stuck on how to do the following: I want to track workouts and see the progress being made with the exercises. Each workout has a name, body weight, date, and exercises. I want to select the exercises when adding the workouts(exercises are already pre-created with a name and some tags), however, each workout is different, meaning the reps, sets, and weight for the exercise is different every time. I'm not sure how to make a model for this. I've added an image of a simple design I made to show what I'm after Hope someone can help me, I'm pretty sure it's a simple solution however, my brain is stuck atm. Image Of Design -
'WSGIRequest' object has no attribute 'get' Django 3.2.9
When i click button "send email" i got this problem 'WSGIRequest' object has no attribute 'get', i have no idea what going on. When i change method to GET the problem still issuse. views.py def sender(request): sent = False if request.method == 'POST': # Formularz został wysłany. form = EmailForm(request) if form.is_valid(): # Weryfikacja pól formularza zakończyła się powodzeniem… cd = form.cleaned_data title = request.POST.get('title','') message = request.POST.get('message','') email = request.POST.get('email','') send_mail(title, message, email, 'admin@admin.pl', fail_silently=False ) sent = True else: form = EmailForm() return render(request, 'contact.html', {'form': form,'sent': sent}) ulr.py urlpatterns = [ path('kontakt', views.sender, name='kontakt'), path('oferta', views.oferta, name="oferta"), path('', views.PostListView.as_view(), name='core'), path('<slug:slug>', views.post_detail, name='post_detail'), ] contact.html {% extends "base.html" %} {% block title %}Wyślij email{% endblock %} {% block content %} {% if sent %} <h1>Wiadomość e-mail została wysłana</h1> <p> "Wysłanie emaila zakończyło się sukcesem. </p> {% else %} <h1> Wyslij wiadomośc poprzez e-mail</h1> <form action="" method="post"> {{ form.as_p }} {% csrf_token %} <input type="submit" value="Wyślij wiadomość e-mail"> </form> {% endif %} {% endblock %} Python ver 3.10.0 Django ver 3.2.9 -
Lit2.0 how to submit form data to backend
Am using Lit2.0, Material Web components, Django (backend). one reference: https://www.thinktecture.com/en/web-components/flaws/ I don't understand how to submit form data from Lit component to backend (Django) form.html contains Lit component (basic-form) <form id="id_demo" method="post" action=""> {% csrf_token %} <basic-form></basic-form> <button type="submit" class="mdc-button mdc-button--raised">Submit</button> </form> basic-form is a Lit component and it contains Material web components import {LitElement, html} from "lit"; // const template = document.createElement('template'); // template.innerHTML = ` // <slot></slot> // `; export class BasicForm extends LitElement { static properties = { form: '', }; constructor() { super(); // this.shadow = this.attachShadow({ mode: 'open' }); // this.shadow.appendChild(template.content.cloneNode(true)); } render() { return html` <mwc-textfield name="first_name"></mwc-textfield> `; } } customElements.define('basic-form', BasicForm); Could someone guide me to the right direction. -
How to pre format a string to show hyperlink in frontend using django
I have a model in which I accept string data in the char field. this is populated through Django admin field. Models.py class Test(models.Model): overview = models.CharField(max_length=10000, null=True, blank=False) views.py from .models import Test def testView(request): data = Test.objects.all() return render(request, 'abc.html', {'data': data}) my template which has html <p style="text-align: center; color: black">{{data.overview | linebreaks}}</p> this mock response of data: "with the great power comes the great responsibility. <a href="https://www.google.co.in/">connect</a>" from backend. how to show this as a link inside the paragraph in the front end. currently the whole anchor tag is displayed instead of link -
Running javascript code after Django backend Validation
this might be a stupid question but i cant seem to wrap my head around the problem here. I am trying to run a bit of code after a form has been submittet with no errors. The error handling is happening in a django backend. When the form is succesfully submittet, the user is redirected to another page. So i had an idea where i would listen to a page redirect then run the code that i want to but i am unsure if that is the best idea. There is really no code to show, does anyone have any idea. Also an idea where i would wrap my form as a promise and when the promise was fuffilled i would run the code but i am unsure of how to do that aswell. -
django: bootstrap modal not displaying
To test modal creations in python with django I created a test app named modalTestApp. Then I copied this html that I got off of the bootstrap website and pasted it into the main.html inside the app, without changing it. The webpage from the app loads fine but clicking the button to preview the modal does nothing. What am I doing wrong here? main/base.html: {% load static %} <!DOCTYPE html> <html> <head> <script src={% static "jquery/jquery-3.3.1.slim.min.js" %}></script> <script src={% static "jquery/jquery.min.js" %}></script> <script type="text/javascript" src={% static 'tablesorter-master/js/jquery.tablesorter.js' %}></script> <script src={% static "bootstrap-4.3.1-dist/js/popper.min.js" %}></script> <script src={% static "bootstrap-4.3.1-dist/js/bootstrap.min.js" %}></script> <style type="text/css"> .main { margin-top: 50px; padding: 10px 0px; } </style> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href={% static "bootstrap-4.3.1-dist/css/bootstrap.min.css" %}> <title>{% block title %} {% endblock title %}</title> </head> <body> <nav class="navbar navbar-dar bg-dark pb-0 pr-0"> <ul class="nav flex-row"> <p class="navbar-brand mb-0 pt-0" style="color: #eee">Weather Data</p> <a href="/", class="nav-link active">Home</a> {% if user.is_authenticated %} <a href="/stations", class="nav-link active">Stations</a> {% endif %} </ul> <ul class="nav justify-content-end"> {% if not user.is_authenticated %} <a href="/register", class="nav-link active">Register</a> <a href="/login", class="nav-link active">Login</a> {% else %} <a href="/logout", class="nav-link active">logout</a> <a href="/users/{{ user.username }}", class="nav-link active">Profile</a> {% endif %} </ul> </nav> {% block … -
How do you change the primary key sent to an update view in django?
I want to change the primary key being sent to the update view from the template. Let me explain. Here is my template: <a href="{% url 'new_url' model_instance.pk %}"> {{ model_instance.username }} </a> This model_instance is an instance in a for loop of the context variable model_instances in a list view. This primary key of the model_instance will then be sent to the following view: class UserUpdateView(generic.UpdateView): template_name = "leads/update.html" queryset = User.objects.all() context_object_name = "user" form_class = UserUpdateForm def get_success_url(self): return reverse("some-url") However, the problem is that the primary key I am sending to UserUpdateView is the primary key for the model_instance model, not the User model. Moreover, there is no link like one-to-one relationships between the the two models. However, there is a similarity. Both of the model_instance and user each have a username field that are the same. In other words, I need to first retrieve the model_instance.username, and then query the User model to find the user instance I want to update. At the moment, the UserUpdateView is simply receiving the primary key for a model_instance in the template, which is not what I want. I hope you guys can help me with this issue, and …