Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Integration of Django-PayPal subscription based payment system
I am trying to implement a Subscription-based payment method in Django with paypalrestsdk, and even the Django-Paylpal library. Integration with Django-Paypal Library. But with this, somehow it is not working for me. I am new to Django python and I am not able to integrate it so please help me with this. -
Flatten Nested QuerySet to a Pandas DataDrame
I am trying to fetch records of all devices with their related owners for the data as below Device ====== .Id .Name .owner_id Owner ===== .Id .Name How I try to get the data in django: data = Device.objects.select_related('owner').values() Now I would need the data of devices and their owner in a flattened pandas' DataFrame. e.g. a column like 'owner.name' is created in the dataframe. How can I do that? Tried 'from_records' didn't work. Tried 'json_normalize' but cannot convert queryset to json first. Thanks -
Folium Django popup with multiple lines
I have a code from map import test def create_popup(data1,data2,data3): popup = Popup(f" Location : {data1}" " Last Time : {data2}" " Last Status : {data3}", max_width=200) return popup But when i input let say popup1 = create_popup("X",test.data2,test.data3), it seems like my Popup only receive data 1 which is x and resulted Location : X Last Time : {data2} Last Status : {data3} test refer to test.py. Is there anyway to fix this code? Thanks, i am using PyCharm I would like to make a popup folium with 3 lines : Location : data1 Last Time : test.data2 Last Status : test.data3 -
Using ast and whitelists to make Django's definition sentences joined by periods safe?
I want to know how to define a sentences joined by period and also use a function in a HTML using an ast and a whitelist. In Django, sometimes files are defined in this way. "xxx.storage.LocalStore" Also, in a html, Django can define like below. {% is_something params %} So I would like to avoid these cases. Do you have any idea? -
How to apply aggregation to item in the QuerySet
There are a lot questions similar to this one but none of them worked for me. Let's assume that I have the following models: class Cafe(models.Model): name = models.CharField(max_length=150) def __str__(self): return self.name class Food(models.Model): class SoldStatus(models.TextChoices): SOLD_OUT = "SoldOut", "Sold out" NOT_SOLD_OUT = "NotSoldOut", "Not sold out" name = models.CharField(max_length=50) cafe = models.ForeignKey(Cafe, related_name="foods", on_delete=models.CASCADE) status = models.CharField(choices=SoldStatus.choices) def __str__(self): return self.name In my QuerySet, I want to retrieve all cafes with the following fields in each: 'cafe name', 'total number of foods', 'total number of not sold foods', and 'percentage of not sold foods' Is there any way to achieve the above result with Django ORM? -
Django Rest Framework adding import in settings.py causes 403 error
I have a Django Rest Framework application with custom render and parse classes, set in settings.py: REST_FRAMEWORK = { "DEFAULT_RENDERER_CLASSES": ( "djangorestframework_camel_case.render.CamelCaseJSONRenderer", "djangorestframework_camel_case.render.CamelCaseBrowsableAPIRenderer", ), "DEFAULT_PARSER_CLASSES": ( "djangorestframework_camel_case.parser.CamelCaseFormParser", "djangorestframework_camel_case.parser.CamelCaseMultiPartParser", "djangorestframework_camel_case.parser.CamelCaseJSONParser", ), } And at this point everything works fine. But if I add import statement in settings.py like this: from djangorestframework_camel_case.render import CamelCaseJSONRenderer REST_FRAMEWORK = { "DEFAULT_RENDERER_CLASSES": ( "djangorestframework_camel_case.render.CamelCaseJSONRenderer", "djangorestframework_camel_case.render.CamelCaseBrowsableAPIRenderer", ), "DEFAULT_PARSER_CLASSES": ( "djangorestframework_camel_case.parser.CamelCaseFormParser", "djangorestframework_camel_case.parser.CamelCaseMultiPartParser", "djangorestframework_camel_case.parser.CamelCaseJSONParser", ), } I start to get 403 error. Why is that? How may I fix it? Just in case it somehow matters my installed apps: INSTALLED_APPS = [ "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.postgres", "django.contrib.sessions", "django.contrib.staticfiles", "corsheaders", "django_filters", "rest_framework", "my_porject.my_app", ] -
SQLalchemy LIKE queries for encrypted database
My MySql and Postgres databases have some columns which been encrypted by some custom encryption function. How it works? I have implemented get_prep_value and from_db_value methods for encryption and decryption using custom field in Django orm. I have also flask application which access to the databases, so in flask I have created new custom type and implemented process_bind_param and process_reuslt_value methods for encryption and decryption. The result - I didn't need to change anything in my codebase and everything should works as regular and before the encryption. But I have an issue which I don't know how it can be solved in this situation when my DB is encrypted and this is all LIKE queries in my code base, when I'm using __contains and __icontains - it is not works as before. How can be the DB encrypted also for fields which I need to access them by LIKE queries? At the moment since I don't have any idea how to solve it, I have decrypted my DB for these fields I lookup with LIKE queries so the code will work as expected and as before. I'm actually expect to encrypt these fields and in spite of encryption, be able … -
ImportError: cannot import name 'url' from 'django.conf.urls' after using from django.urls import re_path as url
In my program i am getting (error cannot import name 'url' from 'django.conf.urls) despite of trying different methods which you have mentioned.my django is latest i am expecting that url can import and my program can run the server this is my code and below is error -
Delete django models object with duplicate field
I want delete django models object with duplicate field. for example: ProgrammingQuestionAnswer.objects.filter(accept=True, programming_question=programming_question) here, maybe a user has 2 accept in the question. I want to count those duplicates once thanks -
Django creates new record instead of updating existing record
I am new to Python and Django, trying to create an app that can create and update the Member (custom table in SQL Database). Create works fine but on update instead of updating the existing member it is creating new record every time I submit. Sorry because stackoverflow was not allowing me save 'VIEW.py single view class handled with URL parameter with ?id=idofrecord and &ed=T to show the Edit form' #LISTS VIEWS class NewMember(LoginRequiredMixin,TemplateView): def get(self, request, \*args, \*\*kwargs): memberId = request.GET.get('id') isEdit = request.GET.get('ed') print('NEW MEMBER VIEW TRIGGERED') print(memberId) print(isEdit) if isEdit == 'T': memberObject = Member.objects.get(id=memberId) form = MemberForm(instance=memberObject) print("EDIT TRIGGERED") return render(request, 'components/list/list-new-member.html', {'form':form, 'memberid':memberId}) elif memberId: form = MemberForm() context = Member.objects.get(id=memberId) print('VEIW MEMBER TRIGERRED') return render(request, 'components/list/list-view-member.html', {'context':context,'form':form}) else: #CREATE NEW MEMBER form = MemberForm() context = {'form':form} return render(request, 'components/list/list-new-member.html', context) def post(self, request, \*args, \*\*kwargs): print('REST POST PRINTED') form = MemberForm(request.POST, request.FILES) if form.is_valid(): retObj = form.save() print('RECORD UPDATED') return redirect('/app/list/member?id='+str(retObj.id)) else: print(request.POST) print(form.errors) print('REST PRINTING POST :form.is_valid() '+ str(form.is_valid())) if form.is_valid(): retObj = form.save() print(retObj.id) return redirect('/app/list/member?id='+str(retObj.id)) context = {'form':form} return render(request, 'components/list/list-new-member.html', context) It should update the existing record as form object has passed with Instance and Post object Model.py #MEMBER … -
How to connect Django web socket with the third-Party Web Sockets?
I want to connect my Django WebSocket with a third-party web socket. This program is one I wrote, and it functions properly. To avoid having to re-login with the third-party API, I have now added the code to check whether the same room is present in my database. if we use the same API KEY to re-connect to the third-party API. It gives the following error: {"event":"login","status":401,"message":"Connected from another location"} I want to see if the same cryptocurrency coin is already connected or not. We don't want to logon with the same API KEY once we're connected. I have two issues here: Don't send the login request to that web socket again. Don't send the subscribe request, if the same coin already exists. Let's say BTCUSD already connected and giving me the data. I want to just connect to the next user to same room and get the data on next request. import websocket import time import ssl from channels.generic.websocket import AsyncWebsocketConsumer from .models import Room login = { "event": "login", "data": { "apiKey": "API_KEY", }, } class CryptoConsumer(AsyncWebsocketConsumer): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ws = websocket.WebSocket(sslopt={"cert_reqs": ssl.CERT_NONE}) self.ws.connect("wss://crypto.financialmodelingprep.com") async def connect(self): self.room_name = self.scope["url_route"]["kwargs"]["room_name"] self.room_group_name = "crypto_%s" % … -
add onclick event radio buttons django forms
So i have a form i use django forms to render out and i have radio buttons that i have added the onclick function to using the code below. class Profile(forms.ModelForm): class Meta: model = User fields = [ "username", "email", "first_name", "last_name", "avatar", "staff_id", "matric_no", "library_id", "designation", "lib_user", ] widgets = { "designation": forms.RadioSelect(attrs={ "id":"label_68", "class":"form-radio validate[required]", "required":"", "name":"q68_typeA68", "onclick":"myFunction(0)", }), } whenever the form is rendered in html, it look like this <input type="radio" name="lib_user" value="" id="label_70_0" class="form-radio validate[required]" aria-describedby="label_70" name="q70_typeA70" onclick="myFunction1(0)"> <input type="radio" name="lib_user" value="Yes" id="label_70_1" class="form-radio validate[required]" aria-describedby="label_70" name="q70_typeA70" onclick="myFunction1(0)"> <input type="radio" name="lib_user" value="No" id="label_70_2" class="form-radio validate[required]" aria-describedby="label_70" name="q70_typeA70" onclick="myFunction1(0)"> what i want to achieve is this <input type="radio" name="lib_user" value="" id="label_70_0" class="form-radio validate[required]" aria-describedby="label_70" name="q70_typeA70" onclick="myFunction1(0)"> <input type="radio" name="lib_user" value="Yes" id="label_70_1" class="form-radio validate[required]" aria-describedby="label_70" name="q70_typeA70" onclick="myFunction1(1)"> <input type="radio" name="lib_user" value="No" id="label_70_2" class="form-radio validate[required]" aria-describedby="label_70" name="q70_typeA70" onclick="myFunction1(2)"> So how do i go about it is what i need help with. -
Django Form resubmit issue when press back button
Django Form submit and link to the main page but when press back button, it shows data and ready to submits again. Views.py is here def contact(request): if request.method == "POST": form = ContactsForm(request.POST, request.FILES) if form.is_valid(): form.save() form = ContactsForm() messages.success(request, 'Contact request submitted successfully.') return HttpResponseRedirect(request.path_info) else: messages.error(request, 'Invalid form submission.') else: form = ContactsForm() projects = Projects.objects.filter(status=1).order_by('-updated_at') return render(request,'main/contact.html',{'contact':'current','projects':projects,'form':form}) -
Django AttributeError: 'tuple' object has no attribute 'splitlines'
I'm trying to create an user registration with email confirmation and came up with this code in the models.py class UserRegister(SuccessMessageMixin, FormView): template_name = 'login/form_register.html' form_class = UserRegisterForm redirect_authenticated_user = True success_url = reverse_lazy('tasks') success_message = "User has been created, please login" def form_valid(self, form): user = form.save(commit=False) user.is_active = False # Deactivate account till it is confirmed user.save() current_site = get_current_site(self.request) subject = 'Activate Your Account' message = render_to_string('login/account_activation_email.html'), { 'user':user, 'domain':current_site.domain, 'uid':urlsafe_base64_encode(force_bytes(user.pk)), 'token':account_activation_token.make_token(user), } user.email_user(subject, message) messages.add_message( self.request, messages.SUCCESS, 'Check Your Email For Account Activation Link' ) if user is not None: login(self.request, user) return super(UserRegister, self).form_valid(form) def get(self, *args, **kwargs): if self.request.user.is_authenticated: return redirect('tasks') return super(UserRegister, self).get(*args, **kwargs) But I keep getting this error AttributeError: 'tuple' object has no attribute 'splitlines' This is the traceback Internal Server Error: /register/ Traceback (most recent call last): File "/home/ihzacordova/.local/share/virtualenvs/todo-list-KiFNCv1Z/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/ihzacordova/.local/share/virtualenvs/todo-list-KiFNCv1Z/lib/python3.8/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ihzacordova/.local/share/virtualenvs/todo-list-KiFNCv1Z/lib/python3.8/site-packages/django/views/generic/base.py", line 103, in view return self.dispatch(request, *args, **kwargs) File "/home/ihzacordova/.local/share/virtualenvs/todo-list-KiFNCv1Z/lib/python3.8/site-packages/django/views/generic/base.py", line 142, in dispatch return handler(request, *args, **kwargs) File "/home/ihzacordova/.local/share/virtualenvs/todo-list-KiFNCv1Z/lib/python3.8/site-packages/django/views/generic/edit.py", line 153, in post return self.form_valid(form) File "/home/ihzacordova/projects/todo-list/login/models.py", line 52, in form_valid user.email_user(subject, message) File "/home/ihzacordova/.local/share/virtualenvs/todo-list-KiFNCv1Z/lib/python3.8/site-packages/django/contrib/auth/models.py", line 402, in email_user send_mail(subject, … -
Django annotate(),Count()
i get the output like this using annotate() and Count() <QuerySet [{'pid': 11, 'status': 'Completed', 'status__count': 3}, {'pid': 11, 'status': 'Hold', 'status__count': 12}, {'pid': 11, 'status': 'InProgress', 'status__count': 2}, {'pid': 11, 'status': 'New', 'status__count': 3}, }] this is code i write to get like this ** view.py** tasks = Task.objects.values('pid','status').annotate(Count('status')).order_by('pid') Actuallt i want my output like this ** <QuerySet [{'pid': 11, 'Completed': 3, 'Hold': 12, 'InProgress': 2,'New': 3},}] ** How can i do? -
Serializer returning empty Strings in a Django Project while displayed in Json
I have a serializer and views.py in a django which I am trying to access from flutter app. But the issue is that in the json I can see the string available but when it is called it is not showing any results. Here is the serializer: class ActiveSessionSerializer(serializers.ModelSerializer): .................................. class Meta: model = ActiveSession fields = '__all__' def __init__(self, queryset, *args, **kwargs): print(f'queryset: {queryset}') self.queryset = queryset super(ActiveSessionSerializer, self).__init__(*args, **kwargs) def to_representation(self, instance): print(f'instance: {instance}') return super(ActiveSessionSerializer, self).to_representation(instance) Here is the json: [ { "session_workout": "Lower1Updated", "activated": false, } ] but in the views.py def getActiveSession(request, **kwargs): last_active_session = ActiveSession.objects.filter(user=user).latest('id') serializer = ActiveSessionSerializer(last_active_session, many=False) print(f"Serialized active session data: {serializer.data}") return Response(serializer.data) The result of the serializer.data is the following: Serialized active session data: {'activated': False, 'session_workout': ''} My question what is the reason for showing empty string in the serializer.data while in the json data there is data populated. How to fix this error ? -
Django allauth Access blocked: This app’s request is invalid
I'm using django allauth. Everything working fine, except when trying to signup using Google. I got this error: Access blocked: This app’s request is invalid. Is there any solution to this? -
Please, I do have a little problem. it is no bug, my program is just not functioning the way I want it to
I have a list of product with each products having a "pack" feature which can allow users to input any number and then multiplies the number by "food price" of the selected product. views.py def food_box_func(): my_food_box = Food.objects.all() append_list_item = [] for item in my_food_box: image = item.image food_item = item.food_item food_price = item.food_price food_slug = item.slug list_item = [image,food_item,food_price,food_slug] new_list_item = append_list_item.append(list_item) return append_list_item def food_box(request, slug): quantity = "" total_price = "" for item in food_box_func(): if request.method == "POST": try: quantity = int(request.POST.get("price in pack")) print(quantity) total_price = quantity*item[2] print(total_price) return render(request,'payments/pay.html',{'price':total_price,'slug':slug,'quantity':quantity,'total_price':total_price}) except ValueError: return render(request,'food_app/404.html') break return render(request,'food_app/food_box.html',{'item':food_box_func(),'price':total_price,'slug':item[3]}) Here is my food template which is connected to the view above: <body> <div class="container"> <br><br><h1><center>Food box page!</center></h1><br><br> </div> {% for message in messages %} <div class="alert alert-{{message.tags}} alert-dismissible fade show" role="alert"> <strong>Message:</strong> {{message}} <button type="button" class="close" data-dismissible="alert" aria-label="close"> <span aria-hidden="True">&times;</span> </button> </div> {% endfor %} {% comment %} Each for loop item takes its slug input and directs the user to its particular view on the payment page. {% endcomment %} {% if user.is_authenticated %} {% for item in item %} <div class="container"> <a href= "{% url 'payments:payment' price=item.2 slug=item.3 %}"><img src={{item.0.url}} class="img-fluid"></a><br><br> <h2>{{item.1|capfirst}}</h2> <h3>₦{{item.2}}</h3> <button … -
Redux toolkit fullfilled even there is an error and showing the error message from django showing in fullfilled case
Fullfilled and update the state perfectly. But When use wrong credential, the detailed error from django showing in the fullfilled "userInfo" state. If we catch the error through rejectWithValue, the message is just "code 401" userSlice.js import { createSlice, createAsyncThunk } from "@reduxjs/toolkit"; import axios from "axios"; export const login = createAsyncThunk( "USER_LOGIN_REQUEST", async (cred, thunkAPI) => { try { console.log("this is one thig"); console.log("username: ", cred.username, "password: ", cred.password); const config = { headers: { "Content-type": "application/json", }, }; const { data } = await axios.post( "/api/users/login/", { username: cred.username, password: cred.password }, config ); localStorage.setItem("userInfo", JSON.stringify(data)); return data; } catch (error) { return thunkAPI.rejectWithValue(error); } } ); const userInfoFromStorage = localStorage.getItem("userInfo") ? JSON.parse(localStorage.getItem("userInfo")) : null; const initialState = { userLogin: { userInfo: userInfoFromStorage }, }; const userSlice = createSlice({ name: "userRegister", initialState, reducers: {}, extraReducers: (builder) => { builder .addCase(login.pending, (state = {}, action) => { return { loading: true, userInfo: [] }; }) .addCase(login.fulfilled, (state = {}, action) => { return { loading: false, userInfo: action.payload }; }) .addCase(login.rejected, (state = {}, action) => { return { loading: false, error: action.payload.message }; }); }, }); export default userSlice.reducer; store.js const store = configureStore({ reducer: { userLogin: userLoginReducer, … -
django changeform_view extra_context
I'm trying to learn on model admin template customization. I need that custom template can read some data stored/passed in 'extra_context' admin.py from django.contrib import admin from .models import MailTemplate # Register your models here. class MailTemplateAdmin(admin.ModelAdmin): change_form_template = 'change_form_htmx.html' def changeform_view(self,request, object_id=None, form_url="", extra_context=None): extra_context = extra_context or {} extra_context['myvar']='this is myvar' return super(MailTemplateAdmin, self).changeform_view(request, object_id=object_id, form_url=form_url, extra_context=extra_context) admin.site.register(MailTemplate,MailTemplateAdmin) template 'change_form_htmx.html' {% extends "admin/base_site.html" %} {% load i18n admin_urls static admin_modify %} {% block extrahead %}{{ block.super }} <script src="{% url 'admin:jsi18n' %}"></script> {{ media }} {% endblock %} {% block extrastyle %}{{ block.super }}<link rel="stylesheet" href="{% static "admin/css/forms.css" %}">{% endblock %} {% block coltype %}colM{% endblock %} {% block bodyclass %}{{ block.super }} app-{{ opts.app_label }} model-{{ opts.model_name }} change-form{% endblock %} {% if not is_popup %} {% block breadcrumbs %} <div class="breadcrumbs"> <a href="{% url 'admin:index' %}">{% translate 'Home' %}</a> &rsaquo; <a href="{% url 'admin:app_list' app_label=opts.app_label %}">{{ opts.app_config.verbose_name }}</a> &rsaquo; {% if has_view_permission %}<a href="{% url opts|admin_urlname:'changelist' %}">{{ opts.verbose_name_plural|capfirst }}</a>{% else %}{{ opts.verbose_name_plural|capfirst }}{% endif %} &rsaquo; {% if add %}{% blocktranslate with name=opts.verbose_name %}Add {{ name }}{% endblocktranslate %}{% else %}{{ original|truncatewords:"18" }}{% endif %} </div> {% endblock %} {% endif %} {% block content %}<div … -
Using generic views with HTTP verbs
I am trying to mix HTTP verbs with Django's Built-in class-based generic views, i understand that is a good pattern (correct me if not) to keep Url's like app/pets/ and use HTTP's verbs to define what to do (GET, POST/create, PUT/update, DELETE/delete, etc) instead of something like app/pets/add or app/pets/delete as Django's documentation shows when using generic views with forms So i tried something like this: urls.py: path('login/', views.sign_in, name='login'), path('logout/', views.log_out, name='logout'), path('register/', views.register, name='register'), path('pets/', views.Pet.as_view(), name= "pets"), Views.py class Pet(LoginRequiredMixin, View): login_url= "/vet/login/" #handle Get Request class PetListView(ListView): model= models.Pet context_object_name= "pets" template_name= "vet/index.html" #Handle Put request class PetUpdateView(): pass but i am getting and error of 405 method not allowed (and i think is not a good practice do this). i also tried this (defining the PetListView same as above): class Pet(LoginRequiredMixin, View): login_url= "/vet/login/" def get(self, request): return HttpResponse(PetListView.as_view()) But this just print the object on the screen. I am new to Django and i do not know what is the better approach to accomplish this using Django generic's views since it reduce a lot code for CRUD operations -
How do I manage my models in Django, is there an equivalent to a database diagram in VS Code?
I'm learning Django and my models are getting complex. The FK and PK relationships are doing my head in. I'm used to create database diagrams with SSMS in MS SQL Server, is there anything equivalent to this in SQLite? I've tried a number of VS code extensions, such as ERD Editor, ERD Preview and even just simple diagram tools such as draw.io The problem with them is there is no integration with the DB so or the classes in models.py -
Subprocess Popen to call a tasks file python which cannot able to load models in Django
I have Django app ..we have several tasks file(stored into tasks folder). And we want to call those tasks file from views.py Now when we call p = Popen("python","./tasks/task1.py", "jobid", stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True) output_filename, err = p.communicate(b"input data that is passed to subprocess' stdin") now in task1.py from app.models import Job #its throwing error It cannot import Models into task1.py where I have sent job id -
What is best way to serialize
I am quite new to django rest framework and I would like to discuss what is the best way to implement an API endpoints I am aiming to have. I have following JSON example: [ { 'top_lvl_key1': { id: 1 'some_key1': "value" 'some_key2' : "value" } }, { 'top_lvl_key2': { id: 1 'some_key1': "value" 'some_key2' : "value" } }, { 'top_lvl_key3': { id: 1 'some_key1': "value" 'some_key2' : "value" } }, { 'top_lvl_key1': { id: 2 'some_key1': "value" 'some_key3' : "value" } }, ] and I want to have 3 endpoints [POST] /insert inserting and parsing the entire JSON to store it into models [GET] /detail/<top_lvl_key>/ Display all record for specfici top_lvl_key [GET] /detail//<top_lvl_key>/id/ Display a record for specific top_lvl_key and specific id (only 1 record) As you can see, I need to store each type of top_lvl_key to different model so I can retrieve for GET requests. However I am not sure how should I got about serializing the JSON, since the dictionaries of the top_lvl_keys can differ. For example top_lvl_key_1 can sometimes have some_key_1 and some_key_2, but sometimes some_key_1 and some_key_2. So far I have been implementing the models with blank=True, null=True, but I am not sure this … -
Django server crashes after clicking button
I currently have code that used to run and now it appears to crash the server I run the python manage.py runserver and I have a function in my views that outputs a dataframe after a trigger button is clicked. Something in this function is messing up the output, because as I click the button to output the html table the server crashes and I have to retype python manage.py runserver to launch it back to the home page. Does anyone have any idea on a potential solution?