Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to get new data at run time from django?
I am working on a Django project with ReactJs frontend. I have to built a simple chat application in that project where users can communicate with each other. in django views I have following function to read messages Views.py class MessagesListAPI(GenericAPIView, ListModelMixin ): def get_queryset(self): condition1 = Q(sender=15) & Q(receiver=11) condition2 = Q(sender=11) & Q(receiver=15) return Messages.objects.filter(condition1 | condition2) serializer_class = MessagesSerializer permission_classes = (AllowAny,) def get(self, request , *args, **kwargs): return self.list(request, *args, **kwargs) this gives me all the messages between user 11 and user 15. on frontend I am getting these messages from rest Api by calling above function frontend const chatApi = axios.create({ baseURL: 'http://localhost:8000/chat/' }) const getMessages = async() => { let data = await chatApi.get(`MessageRead/`).then(({data})=>data); setMessages(data); } I am calling this function in an onClick event of button. and displaying the messages by maping messages array. problem is that at the time when these messages are open to the user. at that time if a new message(data) is added in database. I have to press that button again and call getMessages function again to display that message. Is there a way to automatically get that new message(record) without calling this function again by pressing a … -
how can we add sqlformat.exe in path and django-admin.exe in path?
Installing collected packages: sqlparse, pytz, asgiref, django WARNING: The script sqlformat.exe is installed in 'C:\Users\Slug\AppData\Roaming\Python\Python310\Scripts' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. WARNING: The script django-admin.exe is installed in 'C:\Users\Slug\AppData\Roaming\Python\Python310\Scripts' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. -
Fail to serve static files in deployed Django app (Docker, gunicorn, whitenoise, Heroku)
I have built a Django REST API which serves JSON responses only. My problem is, in production (deployed on Heroku with debug=False) the app does not seem to serve relevant static files needed for the proper styling of the admin interface (only use case for static files). Note, in development (localhost with debug=True) the admin interface is properly styled. Going to the admin route at the deployed (Heroku) address, the content is delivered but without any styling. The browser developer tools indicate that style sheets could not be loaded due to a 500 error code. Django logging output reveals the below detail. django.request ERROR Internal Server Error: /static/admin/css/base.1f418065fc2c.css Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/app/secure_my_spot/custom_middleware/request_logging.py", line 30, in __call__ print(f"Content: {response.content}") File "/usr/local/lib/python3.8/site-packages/django/http/response.py", line 407, in content raise AttributeError( AttributeError: This WhiteNoiseFileResponse instance has no `content` attribute. Use `streaming_content` instead. I have gone into the Heroku dyno and verified that the static files, which cause the 500 error, are in fact in the static_root as per Django's settings.py. I have been spending a significant amount of time scouring the internet for clues as to what might cause the files to not … -
Multiple models in a queryset and/or multiple serializers for one View?
Say I have a Foo model and a Bar model: # models.py class Foo(models.Model): foo_title = CharField() class Bar(models.Model): bar_title = CharField() # serializers.py class FooSerializer(serializers.ModelSerializer): class Meta: model = Foo fields = ["foo_title"] class BarSerializer(serializers.ModelSerializer): foo = FooSerializer() class Meta: model = Bar fields = ["bar_title"] If I want to return a Foo and a Bar model, I have to set up and call two views: # urls.py path("foo/<pk>/", FooView.as_view()) path("bar/<pk>/", BarView.as_view()) # views.py class FooView(generics.RetrieveAPIView): serializer_class = FooSerializer lookup_field = pk class BarView(generics.RetrieveAPIView): serializer_class = BarSerializer lookup_field = pk And then combine the two data results on my front-end. Is it possible to create one View that has multiple models in the queryset and/or multiple serializers? How can I make only one call to my API backend to return the data of different serializers with different models? e.g. Something like # urls.py path("foobar/<foo_pk>/<bar_pk>", FoobarView.as_view()) # views.py class FoobarView(generics.ListAPIView): pass -
How to horizontally align buttons in different elements
I have 3 buttons in different divs with different content. I would like all the divs to be the same height and to horizontally align the 3 buttons. Below is an image that shows the current page, and the desired page with the styling I'd like to achieve. But I just added margins manually in the dev console, so it's not using best practice (see the below image to see how it looks on an Ipad, not very good). And here is what it looks like on ipad (because i just manually added margin-top to each div). Does anyone know the proper way to achieve this? Below is the code: <html> <head> <meta content="width=device-width, initial-scale=1" name="viewport" /> <style> @import url(https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css); @import url(https://fonts.googleapis.com/css?family=Raleway:400,500,800); @import url(https://fonts.googleapis.com/css?family=Montserrat:800); .snip1214 { font-family: 'Raleway', Arial, sans-serif; color: #000000; text-align: center; font-size: 16px; width: 100%; max-width: 1000px; margin: 40px 0 40px 0; } /* MOBILE CUSTOMIZATIONS */ @media screen and (max-width: 767px) { .snip1214 .plan { width: 90%; margin: 0 auto; margin-bottom: 90px; background-color: #ffffff; } } @media screen and (min-width: 768px) { .snip1214 .plan { min-height: 350px; max-height: 350px; margin: 0; width: 33%; float: left; background-color: #ffffff; border: 1px solid rgba(0, 0, 0, 0.1); } .plan-select … -
the value 0.01 not retrieving in python django
model.py class Memopayment(models.Model): tp = models.DecimalField(max_digits=5, decimal_places=3) example.html <td>{{ m.tp|floatformat:3 }}</td> I have entered 0.01 in entry.html but the value retrieved is 0.000 instead of 0.010 Please help me in solving the issue. -
Django - Support query parameter list
I am in the process of migrating a NodeJS backend to a Django backend (DRF). There are some legacy API's I have to support for older app versions. One of them involves reading a list in the query params. "/questions/?questionIds[]=abc&questionIds[]=xyz" I know this is not the way Django handles list in query params but I still have to support it for legacy reasons. When I try to read this using request.query_params["questionIds"] it gives me an error django.utils.datastructures.MultiValueDictKeyError: 'questionIds' Is there any way in which I could support this or is it not possible using Django? -
Django Select from a Subquery
I want to query with window function and then do some group by aggregation on the subquery. But I couldn't make it with ORM method. It will return aggregate function calls cannot contain window function calls Is there any way to make a query like SQL below without using .raw() SELECT a.part_id, AVG(a.max_count) FROM ( SELECT part_id, MAX(count) OVER (PARTITION BY part_id ORDER BY part_id) AS max_count FROM table_one ) a GROUP BY a.part_id -
AttributeError: 'AnonymousUser' object has no attribute '_meta' Django channels
I am trying to login users in django channels and its throwing AttributeError: 'AnonymousUser' object has no attribute '_meta' My Consumer class LoginConsumer(AsyncJsonWebsocketConsumer): async def connect(self): self.room_name = "login_room" self.room_group_name = "login_group" await self.channel_layer.group_add(self.room_group_name, self.channel_name) await self.accept() await self.send(json.dumps({"message": "connected to login socket"})) async def receive(self, text_data): self.json_data = json.loads(text_data) await login(self.scope, await self.query()) await database_sync_to_async(self.scope["session"].save)() async def query(self): await self.get_user_from_db() @database_sync_to_async def get_user_from_db(self): user = User.objects.get(username=self.json_data["username"]) return user async def disconnect(self, code): print("disconnected") await super().disconnect(code) My login view def login_user(request): if request.user.is_anonymous: if request.method == "POST": username = request.POST.get("username") password = request.POST.get("password") user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect("index") else: messages.error(request, "invalid username or password") return redirect("login") return render(request, "login.html") else: return redirect("index") My js file const username = document.querySelector(".username"); const password = document.querySelector(".password"); const socket = new WebSocket("ws://localhost:8000/ws/auth/login"); const button = document.querySelector("button"); button.addEventListener("click", (e) => { if (password.value !== "" && username.value !== "") { socket.send( JSON.stringify({ username: username.value, password: password.value, }) ); } }); Full Traceback: Exception inside application: 'AnonymousUser' object has no attribute '_meta' Traceback (most recent call last): File "/home/__neeraj__/.local/lib/python3.9/site-packages/channels/staticfiles.py", line 44, in __call__ return await self.application(scope, receive, send) File "/home/__neeraj__/.local/lib/python3.9/site-packages/channels/routing.py", line 71, in __call__ return await application(scope, receive, … -
Where are the Django and python files?
I'm new to Django and Python, i'm coming from Laravel. I'm working on a Windowsmachine. My Laravel project has tons of folders (vendor etc.) and is >100 MB my Django project is <50kB. In the end i want to upload my Django project to a webserver. But i'm curios where the Djangofiles on my computer are located, and how deployment works. (what are the essential parts/files compared to laravel (Project Folder + DATABASE) which i've to transfer) Is the DjangoFramework similar like a Javascript file, which i can put i my project folder or get it via linking? -
Django Rest framework, violates not-null constraint DETAIL
I have a question about my serializers. I have the following structure, summarizing. Consists of 3 models and a CreateAPIView view B contains OneToOneField = A C contains ForeingKey = B (many = True) [{List Image}] I don't understand much, how to perform create method in nested serializer. class A (serializer.ModelSerializer): class Meta: model = A class B (serializer.ModelSerializer): A = CreateASerializer () # OneToOneField to A C = CreateBSerializer (many = True) # ForeingKey to B List [{}] class Meta: model = B class C (serializer.ModelSerializer): class Meta: model = C #Can I separately create the Create method for each serializer? # For instance: class A (serializer.ModelSerializer): class Meta: model = A def create (self, validated_data): return models.A.create (** validated_data) class B (serializer.ModelSerializer): A = CreateASerializer () # OneToOneField C = CreateBSerializer (many = True) # ForeingKey List [{image}] class Meta: model = B fields = ('A', 'detail', 'C') def create (self, validated_data): A_data = validated_data.pop ('A') C_data = validated_data.pop ('C') date1 = models.B.objects.create (**validated_data) date2 = models.C.objects.create (**validated_data) for f in A_data: models.A.objects.create (date1=date1, **f) for nu in C_data: models.C.objects.create (date2=date2, **nu) return ? class C (serializer.ModelSerializer): class Meta: model = C def create (self, validated_data): C_data = … -
How to implement pagination in Django
I would like to implement pagination in my custom jsonresponse function. But I have no idea on how would i implement this. This is the code of my function. Any inputs will be a great help. Thank you. def json_response(data = {}, message = 'successful!', status = 'success', code = 200): data_set = {} status = 'success' if code == 200 else 'error' if status == 'success': data_set['code'] = code data_set['status'] = status data_set['message'] = message # data_set['data'] = data.data try: data_set['data'] = data.data except TypeError: data_set['data'] = json.dumps(data) except AttributeError: data_set['data'] = data else: data_set['code'] = code data_set['status'] = status data_set['message'] = message return JsonResponse(data_set, safe=False, status=code) -
Due to a loop before pagination Django paginator takes too much time. How can I solve this problem?
I was asked to map the object customer. I was trying to do the pagination before the loop but I don't know how to do it, because I think that you need to pass all the data to the paginator when creating. This is my view I think the problem is that when I call the function "get_customer_view_data" it runs the loop inside this function and I believe this happens everytime I change page on the paginator, causing the delay class CustomersView(AdminStaffRequiredMixin, TemplateView): template_name = 'customers/tables.html' def get(self, request, activeCustumers, *args, **kwargs): controller = CustomerViewController() date1 = request.GET.get('date1', 1) date2 = request.GET.get('date2', 1) customer_view_data = controller.get_customer_view_data(activeCustumers, date1, date2) page = request.GET.get('page', 1) paginator = Paginator(customer_view_data, 10) try: customers_data = paginator.page(page) except PageNotAnInteger: customers_data = paginator.page(1) except EmptyPage: customers_data = paginator.page(paginator.num_pages) context = {'object_list': customers_data, 'num': len(customer_view_data)} return render(request, self.template_name, context) And this is my controller where I map the data: class CustomerViewController(object): def get_customer_view_data(self, get_active_custumers,date1,date2): data = [] dates = self.set_dates(date1, date2) if get_active_custumers == 1: obj = Organization.objects.filter(organizationmainapp__application__appinfoforstore__status=2, deleted=False, status=True, to_deleted=False) else: obj = Organization.objects.all() for o in obj: customer_view_data = Customer() customer_view_data.Organization_id = o.id customer_view_data.Organization_name = o.name try: customer_view_data.monthly_price_plan = o.organizationmainapp.application.applicationselectedplan.price_plan.monthly_price except Exception as e: print(e) try: if … -
Printing multiple items using serializer
@api_view(['GET']) def selected_device(request,pk=None): if pk != None: devices = Device.objects.filter(pk=pk) devicedetail = DeviceDetail.objects.filter(DD2DKEY=pk) cursor = connection.cursor() tablename= "dev_interface_" + str(pk) cursor.execute(f"SELECT interface FROM {tablename} ") righttable = cursor.fetchall() devserializer = DeviceSerializers(devices, many=True) devdserializer = DeviceDetailSerializers(devicedetail, many=True) interfaces = [] for i in righttable: interfaces.append(i[0]) for i in interfaces: data =[{"interface": i}] interserializer = InterfaceSerializers(data, many = True) results = { "device":devserializer.data, "device_details" : devdserializer.data, "interface":interserializer.data, } return Response(results) In interfaces, I have the following ['G0/1', 'TenGigabitEthernet1/1/3', 'TenGigabitEthernet1/1/5', 'TenGigabitEthernet1/1/20', 'TenGigabitEthernet1/1/21', 'TenGigabitEthernet1/1/22', 'TenGigabitEthernet1/1/23', 'TenGigabitEthernet1/1/24', 'TenGigabitEthernet1/1/25', 'TenGigabitEthernet1/1/26'] But the above codes just print the last item in interface, how do I ensure it to print everything in interface? -
How to pass value into another model based on conditional statement [Django]
I want to create a countdown timer target that will be added into date_target model, using override save method in models.py, the time will countdown differently based on it's variety. import datetime class CustomerVariety(models.Model): variety = models.CharField(max_length=100, null=True) def __str__(self): return self.variety class Customer(models.Model): cardnumber = models.CharField(max_length=15, null=False) name = models.CharField(max_length=100, null=False) date_in = models.DateTimeField(auto_now_add=False, auto_now=False, blank=True, null=True) date_target = models.DateTimeField(auto_now_add=False, null=True) variety = models.ForeignKey(PerihalPermohonan, on_delete=models.SET_NULL, null=True) def __str__(self): return self.name def save(self, *args, **kwargs): if not self.pk: if self.variety == "Priority Customer": self.date_target = self.date_in + datetime.timedelta(days=3) elif self.variety == "Secondary Customer": self.date_target = self.date_in + datetime.timedelta(days=5) super(Customer, self).save(*args, **kwargs) when i pass value into form and save it, why date_target models doesn't full fill the value ? -
Django / React - JWT Auth: How to persist token in-memory OR utilize httpOnly cookie in request
How can I use my access token either (1) through persisting it in-memory or (2) utilizing httpOnly cookies with my React app? Context Pretty confused with this right now. I'm using dj-rest-auth and djangorestframework-simplejwt for authentication. When I call the login endpoint from my backend, I get the refresh_token and access_token + set-cookie for both of these. This is fine. Attempt 1 When I try to utilize the token with an Authorization header on another page, it's undefined. This means there's a flaw with my AuthContextProvider (probably because I'm using a state variable that resets it). AuthContext const AuthContext = React.createContext({ token: '', isLoggedIn: false, login: (token) => { }, logout: () => { }, refreshToken: () => { }, }); export const AuthContextProvider = (props) => { const [token, setToken] = useState(); const userIsLoggedIn = !!token; const loginHandler = (token) => { setToken(token); } const logoutHandler = () => { setToken(null) } const contextValue = { token: token, isLoggedIn: userIsLoggedIn, login: loginHandler, logout: logoutHandler, } return ( <AuthContext.Provider value={contextValue}> {props.children} </AuthContext.Provider> ); }; export default AuthContext; Using authContext.token (authContext being the local variable from useContext), the token is undefined on any other page. Attempt 2 Ok, so the token … -
Accessing matching entry of two models using ForeignKey
I have three models: a Game model, a Distributor model and a Relation model. The Relation model has two ForeignKeys. One linking to Game model and other to Distributor model. I need to access on template (on the same view) the data from the Game model and from the Relation model for the matching entry. Models.py class Game(models.Model): name = models.CharField(max_length=100, unique=True) class Distributor(models.Model): dist = models.CharField(max_length=30, unique=True) class Relation(models.Model): game = models.ForeignKey('Game', on_delete=models.CASCADE) distributor = models.ForeignKey('Distributor', on_delete=models.CASCADE) Views.py class GameDetailView(DetailView): model = models.Game context_object_name = 'game_detail' template_name = 'gamesDB/game_detail.html' def get_context_data(self, **kwargs): context = super(GameDetailView, self).get_context_data(**kwargs) context.update({ 'game_status': models.Relation.objects.all() }) return context I think my view isn't right. But I can't find the way to make it work. How can I access on template the data from the Relation model for the matching game added on the Game model? Thanks in advance. -
Why Django Updating object not triggering at first time?
I have two function. My first function updating an Boolean filed True to False. My first function working properly but my second function not updating object False to True. If I try two time then second time my second function updating object False to True. I am not understanding why it's not updating at first time? here is my code: function1 #this function working properly views.py def ForgetPassword(request): if request.method == "POST": .....my others code profile_obj = UserProfile.objects.get(user=user_obj) profile_obj.email_confirmed = False profile_obj.save() .....my others code function2 #this function not working properly If I try two time then second time my this function updating object False to True: class ChangePassword_link(View): #my others code.... if user is not None and account_activation_token.check_token(user, token): profile_obj = UserProfile.objects.filter(user=user).update(email_confirmed = True) messages.success(request, ('Your account have been confirmed. Now you can login')) return redirect('members:change-password-page') else: messages.warning(request, ('The confirmation link was invalid, possibly because it has already been used.')) return redirect('members:change-password-page') #my others code.... -
How to integrate InvoiceCreator into the checkout flow
Im following the instructions on how to utilize django-oscar-invoices on https://django-oscar-invoices.readthedocs.io/en/latest/quickstart.html , but I dont understand how to integrate oscar_invoices.utils.InvoiceCreator into the checkout flow. Can anyone explain how to do this? -
Building a complex User Schema for website
I have made my first website using Django. Currently, I just have a simple custom user model with name, email etc. Now I want to integrate a payment gateway wherein users can pay and then access the website. The caveat is, I have two types of users, let's say A and B. User type A pay an amount that I have negotiated with them so I have to manually charge them. B pays the amount as per the subscription plans I have set. Now, I want that people A should be able to 'Sponsor' users from their firm or their clients. User type B should be able to collectively apply for a set number of accounts and get a discount based on the number of accounts they purchase. (I know its a bit too complicated but that's what my boss asked of me) I'm using a token payment system linked to a third party service. Does anyone have a good schema recommendation for this problem? My current best idea for this schema is User Details (name address etc) is Sponsor (boolean field - if the user is a sponsor) Sponsored by (if user is not the sponsor, who's sponsoring) - … -
How to remove user using Django Allauth API?
When a user in my Django app cancels their account, I set is_active=False in the auth_user table. However, if that use signs up again, Allauth complains that the email is already in use, even if I manually change the email field to something else in the auth_user table. Allauth is going by the email addresses in the 'account_emailaddress' table. So what's the correct API call to tell Allauth to forget that email, while also setting the auth_user table to not active? Is it safe to delete the entry from the 'account_emailaddress' table myself? Or maybe there's a signal that listens for the record in the auth_user table being completely deleted by my app, and just unsetting 'is_active' isn't enough? I see no such signal listed in the docs, though there is one for changing the email. In short, what's the Allauth way to a) suspend and/or b) delete a user? I'm not using a social account. The following answer implies it's enough to set is_active=False as I describe above, but I've found that more is needed if you want to allow that email to be reused. How to allow user to delete account in django allauth? -
Django how to improve security of password reset?
I setup an password reset option for my users. But I found few security risk: 1) password reset link not expiring: Right now my password reset link not expiring. I want password reset link can be use only one time. User can't use it second time for change his password 2) How to prevent password change if user change the value of HTML : Let you explain. I have an html hidden input filed like this <input type="hidden" name="user_id" value="{{user_id}}"> if user change the html value of user_id then I want to prevent password changing. here is my code: token.py for sent password reset link to mail def send_forget_password_mail(email,token): subject = 'EXAMPLE.COM Password Reset Link' message = f'hi your forgot password link http://127.0.0.1:8000/change-password/{token}' email_from = 'noreply@EXAMPLE.com' recipient_list =[email] send_mail(subject,message,email_from,recipient_list) return True views.py This is the forget password view where user submit mail for get password reset link. Here I also saving token in user profile. def ForgetPassword(request): if request.method == "POST": email = request.POST["email"] User = get_user_model() if not User.objects.filter(email=email).first(): messages.success(request, "Invalid mail") return redirect('members:rest-password') user_obj = User.objects.get(email=email) print(user_obj) token = str(uuid.uuid4()) profile_obj = UserProfile.objects.get(user=user_obj) profile_obj.forget_password_token = token profile_obj.save() send_forget_password_mail(user_obj.email,token) messages.success(request, "An password reset link sent to your email") return … -
How to query overlapping dates on Postgres DateRange field
I have a model with a PostgreSQL DateRange field: class MyModel(models.Model): date_range = DateRangeField() If I want to query this to see if another date overlaps, that's easy enough: MyModel.objects.filter(date_range__overlap=other_date) But if I have built a list of DateRange objects, how can I perform the same query: mylist = [DateRange([2021-10-04, 2021-10-05]), DateRange([2022-10-04, 2022-10-05])] for dr in mylist: dr.overlap(query_date) # fails -
Tableau server hosted on AWS and Embedding with Django
I have my tableau server configured on an AWS instance. I have published a dashboard into the server(Using the trial version). I am trying to display that in a web page locally as of now. I have tried the following steps: Note: I have replaced my code with original ec2 instance with "ec2-server" just for confidential purpose. I copied the embedded code from the share option in the server and pasted in the html file that i am rendering in django. It requests me to log in to the server and then displays the same login page again and again. ( I tried this method with tableau online and instantly i was able to display my dashboard). It says to login again but nothing happens... I then read into the Trusted Authentication from tableau docs and came up with this code to get the ticket and embed in the view that renders my home.html page : from django.shortcuts import render from django.http import HttpResponse from rest_framework import status from rest_framework.response import Response import requests from rest_framework.decorators import api_view import sys def home(request): #I have replaced my code with original ec2 instance with "ec2-server" just for confidential purpose. url = 'http://ec2-server.compute-1.amazonaws.com/trusted/' … -
i can't use python python .\manage.py makemigrate
when i run it i get this: C:\Users\owen pierce\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\python.exe: can't open file 'C:\Users\owen pierce\desktop\galeana.biz\pagina-base\manage.py': [Errno 2] No such file or directory