Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django cannot response json data
I create device function in views.py for return json data like this. views.py def device(request): responseData = { 'id': 4, 'name': 'Test Response', 'roles' : ['Admin','User'] } return JsonResponse(responseData) I set url path to views.device() in urls.py like this. urls.py urlpatterns = [ path('admin/', admin.site.urls), path('device/', views.device()), ] when I save project it show error like this. How to fix it? File "C:\Users\MAX\Django\test_project\test\test\urls.py", line 23, in <module> path('device/', views.device()), TypeError: device() missing 1 required positional argument: 'request' -
How to handle Firebase Cloud Messaging Notifications in Django?
I am managing to send FCM notifications to my app through Django. Here is my function for pushing notifications: import firebase_admin from firebase_admin import credentials, messaging cred = credentials.Certificate("service-key.json") firebase_admin.initialize_app(cred) def send_push(title, msg, registration_token, dataObject=None): try: message = messaging.MulticastMessage( notification=messaging.Notification( title=title, body=msg, ), data=dataObject, tokens=registration_token, ) response = messaging.send_multicast(message) except messaging.QuotaExceededError: raise f'Exceeding FCM notifications quota' Now, I'll be sending a Notification inside a view: class AdminChangeRole(viewsets.Viewset): serializer_class = SomeSerializer permission_classes = [IsAdminOnly] def post(self, request, *args, **kwargs): # code that will change the role of a user send_push("Role changed", f"You role was set to {self.role}", fcm_registration_token) # return Response Now, after posting some data inside a serializer and save it. I'm hoping to send a notification for a User. However, I want to know if I am handling this correctly, including the 2500 connections in parallel and 400 connections per minute. -
ConsumptionClient reservations_summaries.list error of MissingSubscription
Package Name: ConsumptionManagementClient Package Version: 9.0.0 Operating System: IOS Python Version: 3.7 Describe the bug After updating the creds for app registration as described here: https://docs.microsoft.com/en-us/azure/role-based-access-control/built-in-roles#cost-management-reader I am facing the same error: '(MissingSubscription) The request did not have a subscription or a valid tenant level resource provider. Code: MissingSubscription Message: The request did not have a subscription or a valid tenant level resource provider.' To Reproduce Steps to reproduce the behavior: from azure.mgmt.consumption import ConsumptionManagementClient credentials = retrieve_creds() subscription_id = 'XXXXXXXXXXXXXXX' consumption_client = ConsumptionManagementClient( credentials, subscription_id, 'https://management.azure.com' ) scope = subscription_id reservation_generator = consumption_client.reservations_summaries.list(scope=scope, grain='monthly') for reservation in reservation_generator: print(reservation) Expected behavior I expected that in subscription_id which has the required creds, I will be able to loop on the reservation summary result. but it failed in the loop. Additional context It is pretty hard to find good documentation for consumption_summary package. If I did something wrong in the code, please reference me to relevant resource. Just to mention that consumption_client.usage_details.list(scope, filter=date_filter) worked fine. -
django filter gte and lte on one property of one model
I have a User model with age property my models.py class User(models.Model): age = models.IntegerField() i need to output all users between 25 and 35 i can only make query which won't exclude others users first_query = User.objects.filter(age__gte=25) second_query = User.objects.filter(age__lte=35) can i output users between 25 and 35 and exclude others, in one query? -
Dockerfile not being found for Google cloud run
I've hit another bug. I'm now trying to set up continuous deployment for Google Cloud Run from my GitHub, and it's not finding my Dockerfile. I've tried various combinations with my file paths, but it still gives me the Already have image (with digest): gcr.io/cloud-builders/docker unable to prepare context: unable to evaluate symlinks in Dockerfile path: lstat /workspace/Dockerfile: no such file or directory error. This is my file structure from VSCode, and if I run the command from the first Exeplore folder, it finds the Dockerfile The source directory is public, so I just can't figure out why it's not finding the Dockerfile. https://github.com/Pierre-siddall/exeplore Any advice at all would be greatly appreciated, thank you! -
django eventstream / channels return HTML
I have a working application where I use django-eventstream to show info/error messages to users. All works well with send_event(): send_event("ok_message", "message_ok", msg) send_event("error_message", "message_error", msg) but what I actually want to do is send some html directly to the frontend. Is this possible? send_event("ok_message", "message_ok", {"html": "<h1>test</h1>"}) -
How to add item to cart after the user login ? #django
I'm completely new to Django and I tried to create a simple eCommerce web application. In my code, when the user is not logged, items are easily added to the cart and displayed to the web application but when the same user logged into the application and tries to add the item to the cart it is not displayed in the frontend but the item is added to user from backend. I tried the logic if user.is_authenticated but I was not able to succeed. from carts.models import Cart, CartItem def add_cart(request, product_id): product = Product.objects.get(id=product_id) try: cart = Cart.objects.get(cart_id=_cart_id(request)) except Cart.DoesNotExist: cart = Cart.objects.create( cart_id = _cart_id(request) ) cart.save() try: cart_item = CartItem.objects.get(product=product, cart=cart) cart_item.quantity += 1 cart_item.save() except CartItem.DoesNotExist: cart_item = CartItem.objects.create( product = product, quantity = 1, cart = cart, ) cart_item.save() return redirect('cart') This is Django code adding items to the cart before the user login. -
NEED TO SHOW PROGRESS BAR OF FILE SPLITER FUNCTON IN PYTHON
I have a web application that split large CSV into multiple CSV. But I need to show the progress of function processing to the user on front end. Can anyone help me with that, I am using python and Django -
How to extend multiple bases or conditional {% extends %} in one html page in django?
{% if request.user.profile.emp_desi in qa_list %} {% extends "qa_base.html" %} {% elif request.user.profile.emp_desi in mgr_list %} {% extends "manager_base.html" %} {% else %} {% extends "common_base.html" %} {% endif %} How can I solve this problem?? based on designation I want to extend different different bases. -
Why Django doesn't update an object?
I have a model Profile, which connects with User. For example I have Testuser. When I try to update his field 'money', nothing happens. I suppose it may be because I use User, instead of Profile in get_object. But if I change it to Profile, there is an error, that Profile doesn't have username field. How can I solve this problem? model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) money = models.IntegerField(default=0) form: class AddMoneyForm(forms.ModelForm): class Meta: model = Profile fields = ('money',) view: class AddMoneyView(UpdateView): model = Profile template_name = 'users/money.html' fields = ['money'] def get_object(self, queryset=None): return get_object_or_404(User, username=self.kwargs.get('username'), pk=self.request.user.pk) def get_success_url(self): return reverse('account', kwargs={'username': self.request.user.username}) url: path('account/<str:username>/money/', AddMoneyView.as_view(), name='money'), -
How to use the result of a graphene resolved field in another field
I have this use case: class ProjectType(graphene.objectType): tasks = graphene.List(TaskType) duration = graphene.Int() # days def resolve_tasks(): return self.tasks.all() def resolve_duration(): return get_duration_from_tasks(self.tasks.all()) A project can have many tasks, so self.tasks.all() can be an expensive db query to do twice. -
Is it necessary to do threading for sending emails in django
I am not sure that if it is necessary to use thraeding for sending emails in django or not ? If we need to do it so Can i just use the threading library instead of Celery or rabbitmq ? -
Django Form | Group Model | MultiSelect | getting only single value from the form by using MultiSelect widget
I am trying to get input from the user in a template, I am showing list of Groups in template available from the Group model in Django Auth Models and expecting multiple values. But it is only returning single value even selecting multiple options from django.contrib.auth.models import Group class MyForm(forms.ModelForm): the_choices = forms.ModelMultipleChoiceField(queryset=Group.objects.all(), required=False, widget=forms.CheckboxSelectMultiple) class Meta: model = Group exclude = ['name', 'permissions'] def __init__(self, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) image references below Template - Input Form Image Output in Console kindly refer to image 2, I expect 1 and 2 (group name preffered) in console but its returning only 2. -
JWT with Django Rest Framework not working in production
My application uses Django Rest Framework for the APIs and JWT for authenticating the users. Everything was working fine in my local machine. I started having problems after a deployed it to an EC2 instance. The only things that still work are the login, registration and tokens refresh. That is, when I try to log in, I receive the tokens back from the back-end, which are successfully stored in the local storage; when I try to sign up, the back-end creates the new user; and from time to time the tokens are also successfully updated. But all the other API calls fail. At the beginning, when I made an API call, I was getting back "401 Unauthorized". I believe the reason was because Apache wasn't forwarding the Authorization-Headers. So I added "WSGIPassAuthorization On" to the Apache configuration. Now I am getting "500 Internal Server Error" instead. As I already said, only API calls to login, tokens refresh and registration are working. For login and tokens refresh, I am using the default "TokenObtainPairView" and "TokenRefreshView". from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView urlpatterns = [ path('log-in/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('refresh-token/', TokenRefreshView.as_view(), name='token_refresh'), ] For the registration, this is the view I am using: class … -
django - disable button in javascript based on text input
I've got problem to disable submit button conditionally. My js code is as follows: function disableButton() { var btnSubmit = document.getElementById('sub_butt'); if (document.getElementsByName('submitted').value == "yes") { btnSubmit.disabled = true; } else { btnSubmit.disabled = false; } } In django I have updateForm with formset and I would like to disable button based on value text field with name "submitted". I've tried the code above but nothing's changed. Field "submitted" is already filled out with value 'yes' -
ModelFormset in Django CreateView
I'm still new to Django & I would like to know how can allow user to add more than 1 ReferrerMember on Registration form as I wanted to achieve similar to the image url below https://imgur.com/a/2HJug5G I applied modelformset but so far it's giving me an error where "membership_id" violates not-null constraint the moment I submitted the form. I've searched almost everywhere to find how to implement this properly especially on class-based view instead of function based view but still no luck. If possible please help me point out on any mistakes I did or any useful resources I can refer to models.py class RegisterMember(models.Model): name = models.CharField(max_length=128) email = models.EmailField() class ReferrerMember(models.Model): contact_name = models.CharField(max_length=100) company_name = models.CharField(max_length=100) membership = models.ForeignKey(RegisterMember, on_delete=models.CASCADE) forms.py class RegisterMemberForm(ModelForm): class Meta: model = RegisterMember fields = ['name', 'email', ] class ReferrerForm(ModelForm): class Meta: model = ReferrerMember fields = ['contact_name ', 'company_name ', ] ReferrerMemberFormset = modelformset_factory(ReferrerMember, form=RegisterMemberForm, fields=['contact_name ', 'company_name ', ], max_num=2, validate_max=True, extra=2) views.py class RegisterMemberView(CreateView): form_class = RegisterMemberForm template_name = 'register.html' def post(self, request, *args, **kwargs): member_formset = ReferrerMemberFormset (request.POST, queryset=ReferrerMember.objects.none()) if member_formset .is_valid(): return self.form_valid(member_formset ) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['member_formset'] = ReferrerMember(queryset=ReferrerMember.objects.none()) return context register.html <form … -
How store csv file details into a django model
how solve this? how to store the csv file details(not csv file data) like file name,uploaded name,No. of rows into a another django table or model. -
how do i see data by using django listview at chrome
I used listview and confirmed that there was a query set in the terminal. I want to see that data on the Internet. However, even though there is data, row of the table is not added. What should I do? It's so frustrating. I couldn't do anything for five hours because of this. plz heeeeelp me...! # html {% extends 'branches/package-create.html' %} {% block nav %} <form method="get" enctype="multipart/form-data"> {% csrf_token %} {% for i in ps %} <tr class="content-tr"> <td class="td1">{{ i.package_recommandation_date }}</td> <td class="td2">{{ i.package_payment_date }}</td> ... </tr> {% endfor %} </form> {% endblock %} # MODELS.PY class PayHistory(models.Model): branch = models.ForeignKey(Branch, on_delete=models.CASCADE, null=True) package_recommandation_date = models.DateField(null=True) package_payment_date = models.DateField(null=True) ... # views.py class PackageListView(ListView): template_name = 'branches/package-get.html' model = PayHistory def get_queryset(self): p=PayHistory.objects.all() print(p) return p # TERMINAL <QuerySet [<PayHistory: PayHistory object (1)>, <PayHistory: PayHistory object (2)>]> -
dajango AttributeError at / 'WSGIRequest' object has no attribute 'get'
This is my views.py from django.shortcuts import render import requests # Create your views here. def mainfun(requests): city="London" url=f"http://api.weatherapi.com/v1/current.json?key=69528a98f894438b88982548221507&q={city}&aqi=no" data= requests.get(url) return render(requests,"index.html",{'d':data}) This is my settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'weatherapp', ] MIDDLEWARE = [ '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', ] ROOT_URLCONF = 'weather.urls' requests is not working when try to get data from the api.. How to solve this problem..? -
Django selenium: StaticLiveServerTestCase => 'admin' user can not login
I try to use StaticLiveServerTestCase and fixtures. I have created 7 users using fixture and one of them, 'admin' is_superuser=True. My tests pass for all of users except admin that failed to login. I've checked password of admin at the begining of the test method, and I don't know how but (1) password do not correspond to the password set in fixture and (2) password change every runs. That explain failed in login but why only this user has such a behavior? If I try to connect in my dev environnement, using database containing fixtures datas, it works... I try to change is_superuser to false, or 'admin' username with 'myadmin' if there could be a side effect but none works... tests.py class L_access_menu_creation_patient_TestCase(StaticLiveServerTestCase): fixtures = ['dumpdata.json'] @classmethod def setUpClass(cls): super().setUpClass() cls.selenium = WebDriver() cls.selenium.implicitly_wait(1) cls.selenium.maximize_window() cls.date_saisie = timezone.now() cls.selenium.get(cls.live_server_url) # le menu "Ajouter un patient" est disponible (id=menucreate) def test_menu_create_available_admin(self): # ----------------------------------------- connexion ------------------------------- self.admin = User.objects.get(username='admin') print('admin',self.admin.username,self.admin.password) # envoie de données d'identification username_input = self.selenium.find_element_by_name("username") username_input.send_keys('admin') password_input = self.selenium.find_element_by_name("password") password_input.send_keys('admin') fixture dumpdata.json ... { "model": "auth.user", "fields": { "password": "pbkdf2_sha256$150000$qe1v2XJKkik8$jF6iFZ+4GpK1JzBdHzRG0H3XsYY+YphYpxc9Cbgg+7Y=", "last_login": null, "is_superuser": true, "username": "admin", "first_name": "", "last_name": "", "email": "", "is_staff": true, "is_active": true, "date_joined": "2022-03-15T08:32:13.528Z", "groups": … -
Django Mnagement Command conditional command
I am trying to give the command like this, I could not successfully implemmented this bold text condition. (if blacklist == true and active is = false ) (else: no action) 'from django.core.management import BaseCommand from wm_data_collection.models import roses class Command(BaseCommand): help = "Blacklist_TRUE then Active_FALSE." def handle(self, *args, **options): roses.objects.filter(active=False).update(blacklist=True)' -
I am using a service now API for fetching the incident details, but the service now is SSO enabled and my Django request is failing
I am using a service now API for fetching the incident details, but the service now is SSO enabled and my request is failing. Please let me know how to authenticate the APIs -
Django modelform clean_password2
Stumbled this def clean_password2 ModelForm. My question is does every time this we run this view. Does it will automatically run clean_password2 to check the password or do we need to explicitly call it? Form.py class RegisterForm(forms.ModelForm): """A form for creating new users. Includes all the required fields, plus a repeated password.""" password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) class Meta: model = User fields = ('full_name', 'email',) #'full_name',) def clean_password2(self): # Check that the two password entries match password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords don't match") return password2 def save(self, commit=True): # Save the provided password in hashed format user = super(RegisterForm, self).save(commit=False) user.set_password(self.cleaned_data["password1"]) user.is_active = False # send confirmation email via signals # obj = EmailActivation.objects.create(user=user) # obj.send_activation_email() if commit: user.save() return user https://docs.djangoproject.com/en/4.0/topics/auth/customizing/#a-full-example -
How do i efficiently use redux in react making request to backend server?
I am new to using react and also new to redux, I am working on a project which uses Django for Back-end and React for Front-end. I want to use redux for data state management but i can not seem to be doing it right. Here is my action transaction.js function: import axios from "axios"; export const CREATE_TRANSACTION = "CREATE_TRANSACTION"; export const VIEW_TRANSACTION = "VIEW_TRANSACTION"; export const UPDATE_TRANSACTION = "UPDATE_TRANSACTION"; export const LIST_TRANSACTIONS = "LIST_TRANSACTIONS"; export const DELETE_TRANSACTION = "DELETE+TRANSACTION"; export const GET_TRANSACTIONLIST_DATA = "GET_TRANSACTIONLIST_DATA"; const ROOT_URL = "http://127.0.0.1:8000/api/"; export const getTransactionList = () => (dispatch) => { axios .get(`${ROOT_URL}transactions/`, { headers: { "Content-Type": "application/json", }, }) .then((response) => { dispatch({ type: LIST_TRANSACTIONS, payload: response.data }); console.log(response.data); }); }; Here is my reducer transactions.js function: import { LIST_TRANSACTIONS } from "../actions/transaction"; export function TransactionReducer(state = {}, action) { switch (action.type) { case LIST_TRANSACTIONS: return action.payload; default: return state; } } My store.js: import { createStore, applyMiddleware, compose } from "redux"; import thunk from "redux-thunk"; import rootReducer from "./reducers"; const initialState = {}; const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({ latency: 0 }) : compose; const store = createStore( rootReducer, initialState, composeEnhancers(applyMiddleware(thunk)) ); export default store; Trying to display data using useSelector() … -
Python/Django - Input radiobutton to autosend email
I'm trying to set up a radiobutton input that let's you choose to send email automatically. What I want is a form that gives input: manual or auto. This will the one row I have in the sqlite3 database for this: class AutoSendMail(models.Model): auto = models.BooleanField(default=False) manual = models.BooleanField(default=True) send_type = ( ('manual', 'MANUAL'), ('auto', 'AUTO') ) type = models.CharField(max_length=6, choices=send_type, default="manual") So eventually what I want is that in AutoSendMail the type is set to manual or auto, depending on the radiobutton input. I got as far as this: mailindex.html <form action="." method="post" class="card"> {% csrf_token %} <div class="card-body"> <div class="form-group text-right"> <label class="form-label">Send E-mail Automatically</label> <!--<input type="email" class="form-control" placeholder="reply to" value="{{mail.replyTo}}" name="replyTo">--> <input type="radio" name="sendauto" value="On"> Manual <input type="radio" name="sendauto" value="Off"> Auto {{ form.type }} </div> <div class="card-footer text-right"> <input type="submit" value="Submit" name="autoapprove" class="btn btn-primary" /> </div> </div> </form> urls.py path('mailbox/auto_send/', login_required(views.AutoSendView.as_view()), name='auto_send'), forms.py class SendMailSetting(ModelForm): class Meta: model = AutoSendMail fields = ['auto', 'manual', 'type'] widgets = { "manual": DjangoToggleSwitchWidget(klass="django-toggle-switch-dark-primary"), "auto": DjangoToggleSwitchWidget(round=True, klass="django-toggle-switch-success"), 'type': forms.RadioSelect() } models.py class AutoSendMail(models.Model): auto = models.BooleanField(default=False) manual = models.BooleanField(default=True) send_type = ( ('manual', 'MANUAL'), ('auto', 'AUTO') ) type = models.CharField(max_length=6, choices=send_type, default="manual") views.py class AutoSendView(generic.TemplateView): form_class = SendMailSetting model = AutoSendMail …