Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-simple-history track User from python shell
We are using django-simple-history to track changes in our models. All models have a history = HistoricalRecords() field. When making changes to a model from the python shell, the changes are tracked, however the changed_by field is saved as None. When changes are made in admin, the simple_history middleware grabs the User instance from whoever is logged in. Obviously in shell we don't have that. Is there any way to manually inject the User instance based on an existing Account object? Unfortunately I'm not able to change any of these models, so I can't add any of the history user getters and setters to our models (project manager is very strict about refactoring and we also have a lot of models) -
Role based access control in django
i have a table called stores and for each stores listed inside i need to give access to specific user . How can i achieve this feature in django admin page? admin.site.register(models.StoresDetails, StoresDetailsAdmin) admin.site.register(models.StoreServices, StoreServicesAdmin) admin.site.register(models.StoreImages) -
Unable to display the content of {% block content %}{% endblock %} in Django
I can't display the content of {% block content %}{% endblock %} on my web page. Here is the tree structure: toolbox/ toolbox/ lisa/ templates/ lisa/ lisa.html templates/ base.html Here is the code of base.html : {% load static %} <!DOCTYPE html> <html lang="fr"> <head> </head> <body> <section id="main-content"> {% block content %}{% endblock %} </section> </body> </html> And here is the code of lisa.html: {% extends 'templates/base.html' %} {% block content %} <h2>Bienvenue !</h2> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec rhoncus massa non tortor. Vestibulum diam diam, posuere in viverra in, ullamcorper et libero. Donec eget libero quis risus congue imperdiet ac id lectus. Nam euismod cursus arcu, et consequat libero ullamcorper sit amet. </p> {% endblock %} Do you know where it could have come from? Thank you in advance -
How to send signals to consumer in django?
I'm developing websocket programs in Django. I want to receive the request from client(ReactJS) and send signals to websocket consumer, and then websocket consumer send messages to client. How to solve such a problem? I tried as following. urls.py urlpatterns = [ url(r'^updatesignal/$',updatesignal), url(r'^stopsignal/$',stopsignal), ] views.py @api_view(['POST']) def updatesignal(request): print("update") consumers.isconnected = 1 return Response("update signal") @api_view(['POST']) def stopsignal(request): print("stop signal") consumers.isconnected = 0 return Response("stop signal") consumers.py from channels.generic.websocket import AsyncWebsocketConsumer import json import asyncio isconnected = 0 class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): print("connect") await self.accept() while isconnected == 1: await asyncio.sleep(2) print("true") # obj = # do_something (Ex: constantly query DB...) await self.send(text_data=json.dumps({ 'message': "aaa" })) async def disconnect(self, close_code): # Leave room group pass async def receive(self, text_data): # Receive message from WebSocket ..... But websocket consumer is fired after 10 seconds after receiving update siganl request. How to solve this problem? -
UWSGI no module named uwsgi
I hope you are doing well. I have problem with import uwsgi Thanks for helping, my rabbitmq is working behind scene dont worry about it I already installed uwsgi which version 2.0.15 and 2.0.18 and i tried still it does not work my purpose is import uwsgi and uwsgi.websocket_handshake( env['HTTP_SEC_WEBSOCKET_KEY'], env.get('HTTP_ORIGIN', '') ) If i can not import uwsgi so i can not use uwsgi.websocker_handshake """Receive messages over from RabbitMQ and send them over the websocket.""" import sys import pika import uwsgi def application(env, start_response): """Setup the Websocket Server and read messages off the queue.""" connection = pika.BlockingConnection( pika.ConnectionParameters(host='localhost') ) channel = connection.channel() exchange = env['PATH_INFO'].replace('/', '') channel.exchange_declare( exchange=exchange, exchange_type='fanout' ) # exclusive means the queue should be deleted once the connection is closed result = channel.queue_declare(exclusive=True) queue_name = result.method.queue # random queue name generated by RabbitMQ channel.queue_bind(exchange=exchange, queue=queue_name) uwsgi.websocket_handshake( env['HTTP_SEC_WEBSOCKET_KEY'], env.get('HTTP_ORIGIN', '') ) def keepalive(): """Keep the websocket connection alive (called every 30 seconds).""" print('PING/PONG...') try: uwsgi.websocket_recv_nb() connection.add_timeout(30, keepalive) except OSError as error: connection.close() print(error) sys.exit(1) # Kill process and force uWSGI to Respawn keepalive() while True: for method_frame, _, body in channel.consume(queue_name): try: uwsgi.websocket_send(body) except OSError as error: print(error) sys.exit(1) # Force uWSGI to Respawn else: # acknowledge … -
Django register.tag take a dynamic variable as kwarg
I notice register.simple_tag can easily achieve this but I unfortunately can't make the switch right now to use that and would like to use register.tag to implement this have a tag: register.tag(name='foo') def foo(parser, token): bits = token.split_contents() # rest of code.. template, i have an object that we call bar that needs to be passed into foo. Unfortunately i can't seem to get the dynamic value - the below 1. will just be a string 2. will be a string 1. {% foo arg='bar' %} {{ foo_* }} {% endfoo %} 2. {% foo arg=bar %} {{ foo_* }} {% endfoo %} It looks like I can do {% with b=bar %} {% foo arg=b %} {{ foo_* }} {% endfoo %} {% endwith %} I'm hoping to not have to use a with statement here and have the "token" come over with the bar object rather than just taking the literal of it. -
Why i receive error in automcomplete django admin?
I am trying to use openpyxl library to export django admin files, the export is working 90%, however the values are getting below each other and not filling the whole line This my action def export_as_xls(self, request, queryset): if not request.user.is_staff: raise PermissionDenied opts = self.model._meta field_names = self.list_display file_name = f'{opts.verbose_name}' blank_line = [] wb = Workbook() ws = wb.active ws.append(ExportExcelAction.generate_header(self, self.model, field_names)) for obj in queryset: row = [] for field in field_names: is_admin_field = hasattr(self, field) if is_admin_field: value = getattr(self, field)(obj) else: value = getattr(obj, field) if isinstance(value, datetime): value = convert_data_date(value) elif isinstance(value, bool): value = convert_boolean_field(value) ws.append([value]) # import pdb; pdb.set_trace() response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = f'attachment; filename={file_name}.xlsx' wb.save(response) return response This my output, the values are a single record -
Update credit card details of user for all subscriptions in Stripe using API
I've created one user using the Stripe API and that customer is subscribed to 5 lessons. Now the user is wanted to change the credit card information. How can I update credit card details in all the subscriptions so that amount will be deducted from the new card using the API? You can give answers in any programming language. -
How to display number of rows and columns of a csv file in a django web app
I want to get a csv file from the user and then simply want to display the number of rows and columns in that file to the user testapp.html: <form method="POST" action="rowcol"> {% csrf_token %} <input type="file" name="file" accept=".csv"> <button type="submit">Upload text</button> </form> views.py: from django.shortcuts import render from django.shortcuts import HttpResponse import numpy as np import pandas as pd def testapp(request): return render(request, 'testapp.html', {}) def rowcol(request): if request.method == 'POST': file = request.POST["file"] dataset=pd.read_csv('file') count_row = dataset.shape[0] count_col = dataset.shape[1] ans=("<H1>%d,%d</H1>",count_row,count_col) return HttpResponse(ans) urls.py: from django.urls import path from testapp import views urlpatterns = [ path('', views.testapp, name='testapp'), path('', views.rowcol, name='rowcol'), ] urls.py in outer folder: from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('', include('testapp.urls')), ] -
Logout in Django Rest Framework
Fails to implement the user logout. Here is the code. I'm trying to run from the command line curl -d "" POST http://127.0.0.1:8001/api/v1/users/settings/logout/ But in response I get a 401 error - {"detail": "Authentication credentials were not provided."}. Although the user is logged in. @action(detail=False, methods=['post']) def logout(self, request): print(999) #Nothing try: print(request.user.auth_token) request.user.auth_token.delete() except (AttributeError): pass from django.contrib.auth import logout logout(request) return Response({"success": _("Successfully logged out.")}, status=status.HTTP_200_OK) It seems that the function does not even work ... -
AJAX not working in django production mode?
I've a django app deployed on heroku. In one of the section I asks for feedback and email of the person. If the email is valid email then I just reply Thank you. This is all being done using AJAX from getting values of form to returning thank you. It works fine in developement mode but not in prouction mode. Here's my 'index.js' function valid(email) { var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/; return emailReg.test(email); } $(document).on('submit','.Myform',function(e){ e.preventDefault(); $.ajax({ type:'POST', url:'', data:{ message:$('#id_message').val(), email:$('#id_email').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), }, success: function() { let validate = valid($('#id_email').val()); if(validate){ $('.Myform').fadeOut(); $('.thank_you').fadeIn(); } else{ $('.Myform').show(); alert('Please enter valid email address.'); } } }); }); I've only one view in my app. So transferring data of AJAX to that view. Here's my views.py def index(request): if request.method == 'POST': form = FeedbackForm(request.POST) if form.is_valid(): message = request.POST['message'] email = request.POST['email'] print(message) print(email) return HttpResponse('') else: form = ThoughtForm() return render(request,'my_webapp/index.html',{'form':form}) My urls.py file- urlpatterns = [ path('',views.index,name='index') ] In developement mode- It all works well. In production mode as soon as I hit submit button it shows me the loading gif but then it dissappears with no thank you message, no wrong email alert nothing happens and form vanishes The … -
django password change completion fails
I have almost implemented the password reset process, but when I validate the password change I don't end up on the reset complete template and get the template says: The password reset link was invalid... However, the password change has been made and can log in with the new password. It looks the redirection is wrong but I can't figure out why. Here is my urls.py: path('reset/<uidb64>/<token>', auth_views.PasswordResetConfirmView.as_view( template_name='news/user/password_reset_confirm.html', success_url='../password-change/done'), name='password_reset_confirm'), path('password-change/done', auth_views.PasswordResetCompleteView.as_view(template_name='news/user/password_reset_complete.html'), name='password_change_done'), Here is my template: {% block content %} {% if validlink %} <p>Please enter your new password twice so we can verify you typed it in correctly.</p> <form method="post">{% csrf_token %} <fieldset class="module aligned"> <div class="form-row field-password1"> {{ form.new_password1.errors }} <label for="id_new_password1">New password:</label> {{ form.new_password1 }} </div> <div class="form-row field-password2"> {{ form.new_password2.errors }} <label for="id_new_password2">Confirm password:</label> {{ form.new_password2 }} </div> <input type="submit" value="Change my password"> </fieldset> </form> {% else %} <p>The password reset link was invalid, possibly because it has already been used. Please request a new password reset.</p> {% endif %} {% endblock %} -
Load multiple images with Javascript from Django backend
I'm working on a d3 based visualization tool that allows users to click paths on images. That works all fine until I tried to let the user change the background image by a simple dropdown. The problem was that javascript can not load files from the disk since to Cross-Origin permissions. So the solution I picked was to set up a backend. I choose Django. This is the javascript code which manipulates the image: window.LOADED_FILE = "PUT PATH HERE"; I have a working dropdown where the user can pick an image and I get then the path to the file. After this, I tried to load the image like the following. window.SVG.append("image") .attr("width", window.WIDTH + "px") .attr("height", window.HEIGHT + "px") .attr("xlink:href", window.LOADED_FILE); This doesn't work at all and I only get a placeholder image for the 404 Request. So tried to following two things: First of all, this is a solution that I found here. This works fine, but I don't want and I cant hardcode every possible image into an HTML file just to pick the correct variable when the user wants to select another image them later when the user wants. So I need a more dynamic solution. … -
Django return HttpResponse when database fail to connect or timeout
My Django App is hosted using Zappa (lambda) and using AWS Aurora Serverless database. Currently the coldstart for the database is quite long such that the django app will return a json {"message": "endpoint request timeout"} and it does not look nice and may give the message that the website is totally down. I don't want to change the database (yet) because it seems like the best option for my use case. Telling the user to try again in about a minute is good enough. I want to have something like DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '...', 'USER': '...', 'PASSWORD': os.getenv('db_password'), 'HOST': '...', 'PORT': '3306', }, 'OPTIONS': { 'timeout': 30, 'html_when_error': 'templates/sorry.html', }, } I have looked at this to create a custom middleware but not sure how to try it. -
Render Django-Forms Inside Of Bootstrap Modal
I am new to django and I am trying to get a django form to render inside of a bootstrap modal. Any Help is greatly appreciated. Thank you. Let me know if there is any clarification that its needed, or additional code. Again, I really appreciate any help. forms.py from django import forms from login.models import User class PersonForm(forms.ModelForm): firstName = forms.CharField(max_length=30, help_text="Enter Your First Name$ lastName = forms.CharField(max_length=30, help_text="Enter Your Last Name") emailAddress = forms.CharField(max_length=30, help_text="Enter Email Addres$ password = forms.CharField(max_length=30,min_length=6,) class Meta: model = User fields = ('firstName', 'lastName', 'emailAddress', 'password') views.py from django.template import RequestContext from django.shortcuts import render_to_response from login.forms import PersonForm def add_user(request): form = PersonForm() return render(request, 'base.html', {'form':form}) def registration(request): return render_to_response('base.html', {'form': PersonForm()}) base.html <!-- Modal --> <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> <h4 class="modal-title" id="myModalLabel">Log in </h4> </div> <div class="modal-body"> <form id="person_form" method="post" action="add_user" > {{ form.as_p }} </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button> <button type="button" class="btn btn-primary">Log In</button> </div> </div> </div> </div> -
TypeError: t.map is not a function - react-dom.production.min.js:4483
I am having issue deploying a react project to heroku, i checked my heroku logs and i see that heroku is having problem runing npm build, after googling around i found out that i need to degrade my react-scripts from 3.1.2 to 3.0.1 and heroku build it successfully. But Heroku is still display "Application error", so i had to run build myself locally,am getting a blank page and i see on my chrome console that error: TypeError: t.map is not a function - react-dom.production.min.js:4483 -
Django MultipleChoiceField Initial Not Working
I have a MultipleChoiceField in a form and form some reason I can't seem to pass in initial values for editing. What am I doing wrong, this appears correct but it is not actually selecting anything? self.fields['disabilities'] = forms.MultipleChoiceField( required=False, initial=['mobility', 'vision'], choices=[ ['mobility', 'Mobility'], ['vision', 'Vision'], ['hearing', 'Hearing'], ['other', 'Other'] ]) -
Domain name stuck on nginx welcome page, when pointing namesilo domain name to AWS ec2 Instance without using route 53
I am trying to point my own domain name bought from Namesilo to AWS EC2 instance but having a problem that I can visit my Django web app by going to EC2 pubic IP, but if I go to my domain name, it stops in Nginx welcome page. I do not understand what is going on. my Nginx configuration file is: server { listen 80; server_name Public_IP; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/my_first_django_project/myproject; } location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/my_first_django_project/myproject/app.sock; } } The creation of A record in Namesilo: enter image description here The result when I go to my domain name and EC2 public IP: enter image description here Does anyone have any ideas? -
User model with Alluth in djnago?
I have a costume user model in which i added a role field to. If i add an allauth social login with Facebook will the role field be ask asked upon login with Facebook? -
How to pass file contents to serializer?
I'm a new at django. I need to implement two POST options; one from url parameters and the other from file data. eg, curl -X POST localhost:8000/api/test?key=value OR curl -X POST -F "file=@myfile.json" localhost:8000/api/test I tested with below but failed. class TestEntryView(ListCreateAPIView): queryset = TestEntry.objects.all().order_by('-id') parser_classes = (MultiPartParser, FormParser,) serializer_class = TestEntrySerializer def perform_create(self, serializer): if self.request.FILES.get('file'): file_obj = request.FILES['file'] filename = '/api/mytest/.temp/testfile' with open(filename, 'wb+') as temp_file: for chunk in file_obj.chunks(): temp_file.write(chunk) with open(filename, 'r') as temp_file: data = json.load(temp_file) serializer.save(**data) serializer.save() => perform_create() is not getting called due to validating field failed. Is there recommended way for this purpose? -
How to fix fields clashes when using models multi-inheritance in django
Let's say we have a parent abstract model AModel that defines a field foo: class AModel(models.Model): class Meta: abstract = True foo = models.TextField(max_length=500, db_index=True) And we have two abstract model classes BModel and CModel those inherit from AModel: class BModel(AModel): class Meta: abstract = True class CModel(AModel): class Meta: abstract = True And we have a model class DModel that inherits from BModel and CModel: class DModel(BModel, CModel): The problem here is that foo field will clash with itself because it's defined in the two parent model classes. How to solve this problem? Is there a "Django" way to prevent this behavior? -
in __getitem__ raise KeyError(key) from None
I'm currently following a tutorial in which the database password is hidden/activated as a variable in the environment activate file. In the Django local_settings.py, the password is supposed to be retrieved like this: "PASSWORD": os.environ['DATABASE_PW'], However, this gives me the error: File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\User\Desktop\blog\project\project\settings.py" , line 325, in <module> exec(open(f, "rb").read()) File "<string>", line 21, in <module> File "C:\Users\User\Envs\blog\lib\os.py", line 678, in __getitem__ raise KeyError(key) from None KeyError: 'DATABASE_PW' In the environment activate file, the password is saved as: export DATABASE_PW = 'dbpass' The server has not been running during setting the password, the error happens when I try to run python manage.py runserver. I have also deactivated and re-activated the environment before trying to run the server. What's missing to make it work? -
Django: Using save method instead of auto_now and auto_now_add. What are the pros and cons
I found in a post that instead of using auto_now for modified_date field and auto_now_add for created_date field its preferred to assign the timezone.now() for modified and created date in the save method of the model. def save(self, *args, **kwargs): if not self.id: self.creation_date = timezone.now() self.modified_date = timezone.now() super().save(*args, **kwargs) What is the benefit of this over the auto_not/add. -
Taking a form response, making an api call then displaying the api call in Django
I'm trying to have a Django form capture data from a user's input, take the input to make an API call to Aylien API and display the raw json result on the same page. I'm able to take the form input and successfully make an API call & get the JSON to print on the console, but am having a hard time displaying the call's result on the page. I keep getting UnboundLocalError: local variable 'api_response' referenced before assignment error. Code below models.py from django.db import models # Create your models here. class News(models.Model): title = models.TextField(max_length=120) form.py from django import forms from .models import News class NewsForm(forms.ModelForm): class Meta: model = News fields = [ 'title'] views.py from django.shortcuts import render from .models import News from .form import NewsForm import requests import aylien_news_api from aylien_news_api.rest import ApiException def news_create_view(request): ## link form to model for gathering search term from user form = NewsForm(request.POST) if form.is_valid(): # create an instance of the aylien api class api_instance = aylien_news_api.DefaultApi() ## build opts for api call from the response from the user opts = { 'title': form.cleaned_data['title'], 'language': ['en'], 'not_language': ['es', 'it'], 'published_at_start': 'NOW-7DAYS', 'published_at_end': 'NOW' } try: # List the stories … -
Django REST framework JSONParser().parse(request) raising error
In Django view, I am trying this- @csrf_exempt def customer_list(request): """ List all customers, or create a new customer. """ if request.method == 'GET': snippets = Customer.objects.all() serializer = CustomerSerializer(snippets, many=True) return JsonResponse(serializer.data, safe=False) elif request.method == 'POST': data = JSONParser().parse(request) serializer = CustomerSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) On posting data from postman,I get JSON parse error - Expecting value: line 1 column 1 (char 0)