Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django unitTest response.content doesnt show proper user info
I am facing the following problem. When I am running a unit test to verify whether user logged in properly, returned HTTP response doesn't contain variables from the template. class WorkflowViewTest(TestCase): def test_response_authorized(self): User = get_user_model() user = User.objects.get(username='JohnDoe') self.client.force_login(user) response = self.client.get('/workflow/') print(response.content.decode()) # response content is not right self.assertEqual(response.status_code, 200) # assertions are passing just fine self.assertTemplateUsed(response, 'workflow.html') Simplified content of used template 'workflow.html' is: {% extends "base_generic.html" %} {% load static %} {% block content %} {% if user %} {{user}} {{user.username}} {{user.first_name}} {{user.last_name}} {{user.email}} {% else %} User variable not provided {% endif %} {% endblock %} Where encoded response.context.content is following: <body> AnonymousUser </body> </html> I have tried to create a user within setUp of the test, I also created user manually, I tried both self.client.force_login() and self.client.login(). None of the proposed solutions I found were working. I really appreciate any insight. Thanks -
Django How can I trace back where this call is done Not Found: /graphql
Since I created a new project (Django 2.2 and Python 3.7) I am having this error been printed every time I load a new page or some times it does it periodically. Not Found: /graphql [24/Sep/2019 13:23:50] "GET /graphql HTTP/1.1" 404 4216 ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 53701) Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socketserver.py", line 720, in __init__ self.handle() File "/Users/robertofernandez/KMH/flowlemon_backen/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 171, in handle self.handle_one_request() File "/Users/robertofernandez/KMH/flowlemon_backen/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 179, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socket.py", line 589, in readinto return self._sock.recv_into(b) ConnectionResetError: [Errno 54] Connection reset by peer I think this error is caused by some dependency that I have installed (I don't have any view or URL call graphql and I am not using graphql at all in my project), but I am unable to detect which package is the one causing the problems. requirements.txt attrs==19.1.0 certifi==2019.6.16 chardet==3.0.4 coreapi==2.3.3 coreschema==0.0.4 defusedxml==0.6.0 Django==2.2.4 django-braces==1.13.0 django-cors-headers==3.1.0 django-extensions==2.2.1 django-filter==2.2.0 django-oauth-toolkit==1.2.0 django-rest-framework-social-oauth2==1.1.0 djangorestframework==3.10.2 drf-yasg==1.16.1 idna==2.8 inflection==0.3.1 itypes==1.1.0 Jinja2==2.10.1 loguru==0.3.2 MarkupSafe==1.1.1 oauthlib==3.1.0 packaging==19.1 PyJWT==1.7.1 pyparsing==2.4.2 python-decouple==3.1 python3-openid==3.1.0 pytz==2019.2 requests==2.22.0 requests-oauthlib==1.2.0 ruamel.yaml==0.16.5 ruamel.yaml.clib==0.1.2 six==1.12.0 social-auth-app-django==3.1.0 social-auth-core==3.2.0 sqlparse==0.3.0 uritemplate==3.0.0 urllib3==1.25.3 Any idea … -
Django Place Lock on a URL
Not 100% sure how to phrase the question but here is the problem: I have a website serving documents which each have their own URL, for example: www.app/doc/1 www.app/doc/2 The website allows users to edit the documents and save the changes. I want to put a lock in place so that only one user can edit a document at a time. So, if one client has www.app/doc/1 open then noone else should be able to open the same URL. The web app is developed in Django. Any pointers on how to do this? I know some websites are able to pick up if you have a page open in another tab and force you to pick an active tab. What is the method that they use? -
Django built in server keep disconnecting when loading a template
I'm using Django built in server for developing a web application. Upon rendering a template for a specific web page, the server stop working without any log or warning on the console. It's just suddenly disconnected everytime i try to access that page. After a while, i found out that if i remove a block of code which has the function of creating a dropdown list, the problem disappeared. But it's just a very simple code in order to get a list of departments, iterate it and make a dropdown list. I have seen other people do the same on the internet, so i have no idea why this is happening. Here is the code of the view: def edit(request): departments = Department.objects.filter() # I can iterate the QuerySet normally for d in departments: print(d.id, d.name, d.department_code) return render(request, 'edit/edit.html', {'departments': departments}) and the block of code which creates a dropdown list: <select name="department1" class="department"> <option value=""></option> {% for d in departments %} <option value="{{ d.id }}"> {{ d.name }} - {{ d.department_code }} </option> {% endfor %} </select> Any help would be appreciated. Thank you. -
failed to change language manually in django
For some reason I don't want to use this method. Right now I want to change language via a GET request. But it's not working as expected. Here is my settings: MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', ] LANGUAGE_CODE = 'en' LANGUAGES = ( ('en', 'English'), ('bn', 'Bengali') ) LOCALE_PATHS = [ os.path.join(BASE_DIR, 'locale') ] TIME_ZONE = 'Asia/Dhaka' USE_I18N = True USE_L10N = True USE_TZ = False urls.py urls = [ path('language/', base.change_lan, name='change_language'), ] urls += i18n_patterns( path('login/', base.login, name='login'), prefix_default_language=False, ) html: <div class="header-menu"> <ul> <li><a href="{% url 'change_language' %}?lan=en"><img src="{% static 'image/flag/en.png' %}" alt="USA Flag">ENGLISH</a></li> <li><a href="{% url 'change_language' %}?lan=bn"><img src="{% static 'image/flag/bn.png' %}" alt="Bangladesh Flag">বাংলা</a></li> </ul> </div><!-- End .header-menu --> and views: def change_lan(request): allowed_lan = ('en', 'bn') get_lan = request.GET.get('lan', 'en') if get_lan in allowed_lan: translation.activate(get_lan) request.session[translation.LANGUAGE_SESSION_KEY] = get_lan request_url = request.META.get('HTTP_REFERER', '/') // ex: http://localhost:8000/login/ redirect_url = urls.translate_url(request_url, get_lan) //ex: http://localhost:8000/bn/login/ return redirect(redirect_url) else: return redirect(request.META.get('HTTP_REFERER', '/')) -
How to create a user specific homepage in django 2.2?
I'm a newbie to Django framework, I wanted to create a homepage(initial page), which shows a specific set of content made for that particular user if that user is already logged in. -
Handling Custom Error Pages(404, 500) In Django
Why when I click on the page does not exist imposed error page appears in the project folder but I see the emergence of the page django with all the code is true in view from django.shortcuts import ( render_to_response ) from django.template import RequestContext def page_not_found(request,exception): response = render_to_response('404.html',context_instance=RequestContext(request)) response.status_code = 404 return response in url from django.conf.urls import ( handler400, handler403, handler404, handler500 ) handler404 = 'listings.views.page_not_found' -
How to update multiple queries in postgresql stored procedure?
I want to update table in postgresql using array data as per code. I am using stored procedures in postgresql. update table_name set number = '123' where type in ('ab','cd') I want to use same above query in stored procedures also but when placing same code in stored procedures getting errors. Please let me know if anyone has solution for it. -
Google API file permissions using python
I need to do some functionality for different users of my site to automatically upload html files to google disk and open them for viewing and editing in google docs. To do this I create a document, pass it to google disk and use the id of the created document to open it in google docs. To access api, I use a json file taken from the service Google account. I tried to execute my code with owner and view rights, but the result is the same. class CvView(AuthorizedMixin, View): """Here I check if the file format is html, I temporarily save it on disk and pass it to the file_to_drive function (to save it to google disk and open it in google docs) and delete it from disk""" def get(self, request, employee_id, format_): """Returns employee's CV in format which is equal to `format_` parameter.""" employee = get_object_or_404(Employee, pk=employee_id) user = request.user content_type, data = Cv(employee, format_, user).get() if isinstance(data, BytesIO): return FileResponse( data, as_attachment=True, filename=f'cv.{format_}', content_type=content_type) if content_type == 'text/html': try: name = uuid.uuid4().hex + '.html' with open(name, 'w+') as output: output.write(str(data)) return HttpResponseRedirect(file_to_drive(import_file=name)) finally: os.remove(os.path.join(settings.BASE_DIR, name)) return HttpResponse(data, content_type=content_type) file_to_drive from google.oauth2 import service_account from django.conf import settings … -
127.0.0.1:8000 was blocked after securing the site to host
to host my site I went to https the problem is that for the creation of another site I can not connect myself to the http how do I delete the security script but I still have the same error This site can not provide a secure connection -
Access Contrib.Auth User Model Email In My Django Model
So basically, my users already input their email on registration, but I have a separate model with some custom fields that are filled in after registration which show up in the admin section, and I want the email to show there too, but I don't want to ask them for their email twice. What I want to do is a add a field to my model, which just takes their email address from the django auth user model, i.e. class Model(models.Model): field1 = models.CharField email = request.user.email How would I achieve this? -
how to do migrations dynamically in django?
Is there any way that we can create an create an input field dynamically in the form without doing manually work, like first create the particular field in model and then run makemigartions command and then run migrate command. I have tried using formset but that is not what i am looking for. reffer this link -https://demo.vtiger.com/vtigercrm/index.php?module=LayoutEditor&parent=Settings&view=Index&sourceModule=Assets&mode=showFieldLayout when you open this link there is a option "ADD CUSTOM FIELD". i want to do same with my django. Hope i am able to explain you what i wants to do. I am searching for this since 3 days and cannot able to implement that. -
If We disable the admin module of Django , how does user authentication and authorization works
If We disable the admin module of Django , how does user authentication and authorization works. I tried searching but could not get any reference.I am new to Django please help . -
How to delete line_items from a woocommerce order using python
I am trying unsuccessfully to delete all the products related with a woocommerce order in order to update this order with new products. To do this I guess the 1st step is to delete all the line_items of the specific order and make a put to update. The 2nd step is again to make a put but with the new products this time in the position of line_items. Has anyone any idea what's going wrong with my code? In this post , https://github.com/woocommerce/woocommerce/issues/22177, I saw that I have to put in the quantity field of every product in my line_items the value of 0, but it doesn't work. Here is my code: def update_woocommerce_order_products_with_quantities(wcapi,order,oldWooOrderHasProducts): fetched_products=Woo_Order_Has_Products.objects.filter(woo_order_id=order_id) #FIRST I HAVE TO DELETE THE PRODUCTS OF THE WOOCOMMERCE ORDER for oldWooOrderHasProduct in oldWooOrderHasProducts: data = { "line_items": [ { "id": str(oldWooOrderHasProduct.wholesale_product.pid), "quantity": 0, } ] } wcapi.put("orders/"+str(oid),data).json() #for every product update the price and quantity for fetched_product in fetched_products: data = { "line_items": [ { "id": str(fetched_product.wholesale_product.pid), "quantity": str(fetched_product.quantity), "price": str(fetched_product.price) }] } wcapi.put("orders/"+str(oid),data).json() -
Showing graphs with Plotly based on Django, url - view problem
I am trying to show scatter graph created by plotly at plots.py and to show in html at simulator.html. The problem is, when I run sever with following codes, it shows the basic error when accessing http://127.0.0.1:8000/simulator/ as below. As you can see at settings.py, I believe all the necessary settings should have been done. Could you guys figure out what would be the cause of this error and how to fix it, please? Error message: TemplateDoesNotExist at /simulator/ simulator.html Request Method: GET Request URL: http://127.0.0.1:8000/simulator/ Django Version: 2.2.4 Exception Type: TemplateDoesNotExist Exception Value: simulator.html Exception Location: /Users/user/.pyenv/versions/3.7.3/lib/python3.7/site-packages/django/template/loader.py in select_template, line 47 Python Executable: /Users/user/.pyenv/versions/3.7.3/bin/python3 Python Version: 3.7.3 Python Path: ['/Users/user/Desktop/Django/price_simulator', '/Users/user/.pyenv/versions/3.7.3/lib/python37.zip', '/Users/user/.pyenv/versions/3.7.3/lib/python3.7', '/Users/user/.pyenv/versions/3.7.3/lib/python3.7/lib-dynload', '/Users/user/.pyenv/versions/3.7.3/lib/python3.7/site-packages', '/Users/user/.pyenv/versions/3.7.3/lib/python3.7/site-packages/IPython/extensions'] Server time: Tue, 24 Sep 2019 11:14:59 +0000 simulator.html {% extends 'base.html' %} {% block customcss %} {% endblock customcss %} {% block header %} <script src="https://cdn.plot.ly/plotly-latest.min.js"></script> </div> {% endblock header %} <div class="card" style="width: 100%;margin-top: 15px"> <div class="card-body"> <h5 class="card-title">title</h5> {{ scatter|safe }} </div> </div> Extract of settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'simulatorapp' ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR, 'templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] url.py … -
How to remove all permissions from a group in Django
In Django authentication permissions, how to remove all permissions granted to a group? -
Override django admin action
I have a base admin model which I managed to override some fields like inlines, fields, etc but for some reason I cannot override the actions, what am I missing? class BaseOrderAdmin(admin.ModelAdmin): actions = ['some_action'] class OrderAdmin(BaseOrderAdmin): actions = ['some_new_action'] Order model should only have "some_new_action" action but it only has the base admin action 'some_action' so isnt overriden. -
djstripe customer subscription deletion webhook event not working properly
I have configured the djstripe webhook subscription deletion webhook to save subscriptions with cancel status. from djstripe import webhooks import djstripe.model @webhooks.handler("customer.subscription.deleted") def subscription_deletion_handler(event, **kwargs): data = event.data.get("object", {}) djstripe_subs_status = data.get('status') djstripe_subs_id = data.get('id') djstripe_subscription = djstripe.models.Subscription.objects.get(id=djstripe_subs_id) djstripe_subscription.status = djstripe_subs_status djstripe_subscription.save() But while getting subscription object it throws djstripe.models.billing.subscription.DoesNotExist exception and automatically deleted object from database. Please correct me and let me know if there is any issue in the above code. -
I am trying to import my database values, but the results are not being displayed, even though the table structure is correct
Table creation here at views.py def products(request): if request.method=='POST': form = ProductForm(request.POST) if form.is_valid(): try: form.save() return redirect('show') except: pass else: form = ProductForm() return render(request,'show.html',{'form':form}) This is the content from show.html file. <tbody> {% for items in products %} <tr> <td>{{ items.pid }}</td> <td>{{ items.pname }}</td> <td>{{ items.pprice }}</td> <td> <a href="/edit/{{ items.id }}"><span class="glyphicon glyphicon-pencil" >Edit</span></a> <a href="/delete/{{ items.id }}">&nbsp;&nbsp;<span class="glyphicon glyphicon-remove">Delete</span></a> </td> </tr> {% endfor %} </tbody> The database value isn't being displayed on the webpage. -
How does Post Request Work with Django Testing Tools
I am quite new to Django and Django Rest Framework Testing Tools and am a bit confuse on how sending a Post Request works on uploading a file. Here is the APITestCase I have to upload a file: (The file is an xml of a ZAP report) class UploadTest(APITestCase): c = APIClient() def test_file_upload_ZAP(self): self.c.force_authenticate(UserFactory.create()) with open(path.join('VMA', 'test', 'Test.xml'), "rb") as fp: self.c.post('/upload/TestZAPXML.xml', {'filename': 'name', 'attachment': fp}) The issue is the code keeps breaking due to an XML Parsing Error. I have no issue when sending a POST Request through Postman or httpie - the XML Parser works as intended. [The only difference I noticed between the Django Post request to Postman is: I change the Body in Postman to send as binary] To find why it is breaking: I decided to run a file.read() in the my fileHandler(file) method. The file prints out: b'--BoUnDaRyStRiNg\r\nContent-Disposition: form-data; name="filename"\r\n\r\nname\r\n--BoUnDaRyStRiNg\r\nContent-Disposition: form-data; name="format"; filename="Test.xml"\r\nContent-Type: application/xml\r\n\r\n The XML Parser doesn't like this and therefore throws an exception. file.read() should print out like this: <?xml version="1.0" encoding="UTF-8"?><OWASPZAPReport generated="Fri, 29 Mar 2019 21:02:52" version="2.3.1"> Which is what prints out when I am using Postman. This is also the actual XML file. What am I doing wrong in … -
send context data in django rest framework
I created a calendar in my django app for which I had to pass queryset in the context. Here's the code: def event(request): all_events = Quiz.objects.filter(owner_id=request.user, status="Assigned") context = {"events": all_events, "get_event_types": all_events, } return render(request, 'classroom/teachers/calendar.html', context) Both events and get_events_types are then used in the Django templates. Now I want to do the same in django rest framework. So I did this: Views.py class calendareventsview(viewsets.ModelViewSet): serializer_class = CalendarSerializer queryset = Quiz.objects.all() def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) queryset = queryset.filter(owner_id=request.user, status="Assigned") serializer = self.get_serializer(queryset, many=True) print("serializer data is", serializer.data) return Response(serializer.data) serializer.py class CalendarSerializer(serializers.ModelSerializer): class Meta: model = Quiz fields = "__all__" Now this sends me the queryset in the data form but Can I get them against "events" or "get_event_types"? so that I can use them ? -
How to call remote API in django from views.py?
I m new to Django, I got stuck while calling remote API from views.py. from django.http import HttpResponse if request.method == 'post': r = requests.post('domain_name/api/test/', d=request.POST) And it is giving me error What is the proper way to to call API? Please Help !!!! -
How to aggregate sum of all data in django restframe work and it should filter by date
I am trying to filter data by daterange and i am able to do this but i have question how to create summary of table and filter by date also i am also attached code that you can see and help me out Actual api look like this { "count": 4, "next": null, "previous": null, "results": [ { "pk": 1, "bikeid": "425432", "milage": 12, "movingtime": "5hr 12min", "averagespeed": 14, "kgtrasported": 234, "co2": 180, "additionalbox": 4, "nouser": 8, "too": "2019-09-23", "fromm": "2019-09-23" }, { "pk": 2, "bikeid": "425433", "milage": 11, "movingtime": "5hr 12min", "averagespeed": 13, "kgtrasported": 134, "co2": 170, "additionalbox": 7, "nouser": 4, "too": "2019-09-23", "fromm": "2019-09-23" }, But i want that my data will be look like this and it will filter by date also all sum value { "count": 4, "next": null, "previous": null, "total_milage":23, "total_co2":350, "total_additionbox":4, "total_user":12 "results": [ { "pk": 1, "bikeid": "425432", "milage": 12, "movingtime": "5hr 12min", "averagespeed": 14, "kgtrasported": 234, "co2": 180, "additionalbox": 4, "nouser": 8, "too": "2019-09-23", "fromm": "2019-09-23" }, { "pk": 2, "bikeid": "425433", "milage": 11, "movingtime": "5hr 12min", "averagespeed": 13, "kgtrasported": 134, "co2": 170, "additionalbox": 7, "nouser": 4, "too": "2019-09-23", "fromm": "2019-09-23" }, Here is Views.py # Electric Bike Add class Ebike(generics.ListCreateAPIView): … -
How to let user fetch only those objects they are related to (by many-to-many relationship)?
I have a project in which there are workspaces, and each workspace can have any number of users. Users can also belong to multiple workspaces, so there's a many-to-many relationship between them. Now, I have workspace creation and membership working, but I'm having trouble setting the permissions so that only the workspace members can see the workspace. I've tried with a custom object-level permission, but it doesn't seem to work. The workspace model looks like this: class Workspace(models.Model): name = models.CharField(max_length=100) users = models.ManyToManyField(User, related_name='workspaces') The view looks like this: class WorkspaceViewSet(viewsets.ModelViewSet): queryset = Workspace.objects.all().order_by('name') serializer_class = WorkspaceSerializer permission_classes = [permissions.IsAuthenticated|BelongsInWorkspace] The serializer is like this: class WorkspaceSerializer(serializers.ModelSerializer): class Meta: model = Workspace fields = ('name', 'users') def create(self, validated_data): instance = super(WorkspaceSerializer, self) instance.users.add(self.context['request'].user) return instance And finally, the custom permission I'm trying to use here: class BelongsInWorkspace(BasePermission): def has_permission(self, request, view): return True def has_object_permission(self, request, view, obj): return obj.users.filter(pk=request.user).exists() -
How to call postgresql stored procedure using sqlalchemy?
I have developed stored procedure in postgresql which accepting 2 parameters & I am calling it using sqlalchemy using below code but getting syntax error. I have tried sqlalchemy online tutorials. connection.execute('stored_proce_name ?, ?', para_1, para_2 ) Getting error like :ProgrammingError('(psycopg2.errors.SyntaxError) syntax error at or near "stored_proce_name "\nLINE 1: stored_proce_name ?, ?\n ^\n')