Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to override Django many to many field add() and remove() methods
I am trying to set up a Facebook-like activity notification system using Django-Activity-Stream. The library provides a special action signal for creating the actions. According to the documentation, to trigger this action, You can do it through custom forms or by overriding predefined model methods, such as Model.save(). The logic is to simply import the action signal and send it with your actor, verb, target, and any other important arguments. For example, action.send(request.user, verb='reached level 10') However, I have an intermediate through model from which the action signal has to be sent. Since Model.save() method is not called when M2M add() or remove() methods are instead used, I want to know if there is any way to override those add() and remove() methods. I have thought about using M2M changed signals but soon realized that I wouldn't be able to easily access request.user in M2M changed signals. (I need to always know who request.user is to generate any useful activity notifications). I am concerned that accessing a user instance in a signal (by creating a separate middleware to store request.user in a thread, for example) may be costly and unsafe. If it is a reliable option, please tell me. -
Nested for in Django template with dynamic key
I have two query set results group = [{'id': 1, 'group1'}, {'id': 1, 'group2'}] sub_groups = [{1: [{'id': 1, 'sub_group1'}, {'id': 2, 'sub_group2'}], {2: [{'id': 3, 'sub_group3'}, {'id': 4, 'sub_group4'}] I need to show group and its sub group in template. So, I am looping through the groups and then I need to loop through sub_groups. I can't able to access the sub_groups by group id. Getting Could not parse the remainder: '[group.id]' from sub_groups[group.id]' <ul class="list-group"> {% for group in groups %} <li class="list-group-item">{{group.name}}</li> <ul> {% for sub_group in sub_groups[group.id] %} <li class="list-group-item">{{sub_group.name}}</li> {% endfor %} </ul> {% endfor %} -
django - urlpatterns giving 404 error for defined URLs
I have an application running on django. But I am getting error code 404 for some urls even though these are defined. from .views import check_secret_key # a function in views.py from .swagger_schema import SwaggerSchemaView # a class inheriting APIView from .kom.kom_writer import kom_status # a function urlpatterns = [ url(r'^docs/api-docs/', SwaggerSchemaView.as_view()), url(r'^nag/secret-key/', check_secret_key), url(r'^nag/kom-status/', kom_status), ] API curl http://localhost:9999/internal/docs/api-docs/ works fine but curl http://localhost:9999/internal/nag/kom-status/ and nag/secret-key fir 404 errror. Not FoundThe requested resource was not found on this server. I am not sure what is it that I am missing. Note: App was recently updated from DJango 1.8 to 1.11 and djangorestframework 3.2.5 to 3.5.3. Before that it was working fine. -
How do I pass a variable from Django's render method's context param to a javascript script on the frontend?
For context here, I am experienced with JavaScript but new to Django. Goal: Log the contents of a Django context variable in the browser's console using JavaScript. Specifically I'd like to log the contents of context in the Django render method I write below. In script.js I have console.log("hey", foo) which I expect to output the contents of a variable I pass into the Django render method. It gives me an error: Uncaught ReferenceError: foo is not defined I found two StackOverflow threads that seem to answer my question re: how to do this correctly. Neither worked. In (1) How can I pass my context variables to a javascript file in Django?, the answer from user Brian Neal claims I can deliver the Django variable into a javascript script at the top of the html file Django uses to render the page. Here is how I tried his answer: Django's render method says... def page(request): bar = "a" doohickey = "b" context = {'foo': bar,'baz': doohickey} return render(request, 'myPage.html',context=context) Then in myPage.html I say: {% load static %} {% block js %} <script>var foo = {{ foo|safe }}; console.log("aliens");</script> <script src="{% static 'js/script.js' %}" type="text/javascript" defer></script> {% endblock %} And … -
Djang-allauth signup issue on Heroku
before I get any deeper I’d just like to ask if any of you have experienced this issue. When in local environment logging and signing up redirection work fine. After deploying to Heroku, logging is fine but after signing up, redirection is not working and I’m getting Server Error 500. Unfortunately, Heroku logs don’t give me any closer description why it is so. It is just suspicious that locally is everything fine. Is there any known issue I should be aware of? I haven’t found anything online and already spent days digging. Many thanks for any help. -
Pythonanywhere django.urls.exceptions.NoReverseMatch: Reverse for 'activate' with keyword arguments
i work in pythonanywhere and i have run a signup script - local it works without problems in pythonanywhere i get this error 2020-09-13 15:37:43,507: Internal Server Error: /signup1/ Traceback (most recent call last): File "/home/username/.virtualenvs/myenv/lib/python3.6/site- packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/username/.virtualenvs/myenv/lib/python3.6/site- packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/username/werkvertragrepo/werkvertrag/views.py", line 612, in signup1 text_body = render_to_string('acc_active_email.txt', merge_data) File "/home/username/.virtualenvs/myenv/lib/python3.6/site- packages/django/template/loader.py", line 62, in render_to_string return template.render(context, request) File "/home/username/.virtualenvs/myenv/lib/python3.6/site- packages/django/template/backends/django.py", line 61, in render return self.template.render(context) File "/home/username/.virtualenvs/myenv/lib/python3.6/site- packages/django/template/base.py", line 170, in render return self._render(context) File "/home/username/.virtualenvs/myenv/lib/python3.6/site- packages/django/template/base.py", line 162, in _render return self.nodelist.render(context) File "/home/username/.virtualenvs/myenv/lib/python3.6/site- packages/django/template/base.py", line 938, in render bit = node.render_annotated(context) File "/home/username/.virtualenvs/myenv/lib/python3.6/site- packages/django/template/base.py", line 905, in render_annotated return self.render(context) File "/home/username/.virtualenvs/myenv/lib/python3.6/site- packages/django/template/defaulttags.py", line 446, in render url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app) File "/home/username/.virtualenvs/myenv/lib/python3.6/site- packages/django/urls/base.py", line 87, in reverse return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)) File "/home/username/.virtualenvs/myenv/lib/python3.6/site- packages/django/urls/resolvers.py", line 685, in _reverse_with_prefix raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'activate' with keyword arguments '{'uidb64': 'NTA', 'token': 'aa5a2v-c248dcaea908540be1e8e3d5feff970f1'}' not found. 1 pattern(s) tried: ['activate/(?P<uidb64>[0-9A-Za-z_\\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A- Za-z]{1,20})/'] serverlogs 2020-09-13 15:37:43 {'user': <User: user@usermail.de>, 'domain': 'www.mywebsite.de', 'uid': 'NTA', 'token': 'aa5a2v-c248dcaea908540be1e8e3d5feff970f1'} 2020-09-13 15:37:43 Internal Server Error: /signup1/#012Traceback (most recent call l ast):#012 File "/home/username/.virtualenvs/myenv/lib/python3.6/site- packages/django/core/handlers/exception.py", … -
Can not able to serve media files on cpanel django
I build a website with Django and now hosting it. I used Whitenoise to serve images but only static ones shows up when debug is False. How can I serve media files uploaded by users too? Since it is my first development with Django detailed help would be much appreciated kind folk of the Stack. -
DJANGO WEB SOCKET WITHOUT CHANNELS
I will start django project for my bussiness (food), i focus on android app, but i want set my server with django. I want my android app use websocket for realtime food queue. EX: Android app -> server(django) -> merchant app(android) If i saw on tutorial always use django channels, but it not work on my project. I think, use django as webserver and make own websocket using python in same address (ip/port). So in this project, websocket only used for send data/notif to android app. In my mind, i use django for webserver and make tcp socket (not websocket) for send data to merchants. Thanksss... -
Cannot read property 'title' of null error when using Vue with Django Rest Framework When LimitOffsetPagination
As a test to use Vue to do a GET on a Django Rest Framework api url, it appears to work fine and I will get a listing of the tutorial title and rendering of the tutorial id in my links as expected: My html file: <li v-for="tutorial in tutorials"> <a href="/tutorial/[[ tutorial.id ]]/"> [[ tutorial.title | title ]] </a> at [[ tutorial.created ]] by [[ tutorial.author ]] </li> <script type="text/javascript"> let app = new Vue({ el: "#app", delimiters: ["[[", "]]"], data: { tutorials: {} }, mounted() { axios.get('/api/tutorials/').then(response => { this.tutorials = response.data }) } }); </script> As far as the rest api goes for Django, the serializer used in Django is: class TutorialSerializer(serializers.HyperlinkedModelSerializer): author = serializers.StringRelatedField() class Meta: model = Tutorial fields = [ "title", "description", "summary", "author", "graphic", "created", "modified", "is_approved", "is_published", "publish_date", ] But when I introduce a limit like so in settings.py: REST_FRAMEWORK = { ... 'DEFAULT_PAGINATION_CLASS': \ 'rest_framework.pagination.LimitOffsetPagination', 'PAGE_SIZE': 100, } I now get this in the console: TypeError: Cannot read property 'title' of null at eval (eval at Ya (vue:6), <anonymous>:3:331) at wn.vt [as _l] (vue:6) at wn.eval (eval at Ya (vue:6), <anonymous>:3:177) at wn.e._render (vue:6) at wn.r (vue:6) at fn.get (vue:6) at … -
How to count ManytoManyField within form in Django?
I have a form class called AttendanceForm. Inside that form I have a field called student which is a ManytoManyField with Student model. Also I set the widget of student field to CheckboxSelectMultiple. Now how can I count or know how many students or checkboxes in the form? I have tried {{ form.student.count }} within the template but it's not working. here is my models class Student(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, primary_key=True) class Attendance(models.Model): student = models.ManyToManyField(Student) my forms.py class AttendanceForm(forms.ModelForm): class Meta: model = Attendance fields = ['student',] widgets = {'student': forms.CheckboxSelectMultiple()} this is how i render form in template <form method="POST"> {% csrf_token %} <div class="row"> {% for form in form.student %} <div class="col-md-4"> <div class="row"> <h6 class="ml-2 mt-3" id="info-text"> {{ form.tag }} {{ form.choice_label }} </h6> </div> </div> {% endfor %} </div> <button type="submit">Check</button> </form> this is my view ( Im using form within the detailview) class Class_detailView(LoginRequiredMixin, FormMixin, DetailView): login_url = '/' model = Class form_class = AttendanceForm template_name = "attendance/content/teacher/class_detail.html" def get_success_url(self): return reverse('class_detail', kwargs={'pk': self.object.pk}) def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) def form_valid(self, form): form.save() return super().form_valid(form) -
How to make relations between Mongodb Collection in Django
I am building an online job posting and searching website in django and using mongodb as a database. I am new to both of them. I am stuck at a point where I have to connect two mongodb documents with each others. The User_Registration model is for the sign_up and sign in of the user. Username is unique I am using this as a foreign key in the other model which is for the job that user has posted. When user sign in to the website he/she view the job that has been posted by him/her. Following is the models which I have made. Am I doing it the right way or not I am a bit confused with this, Kindly help me out. class User_Registration(models.Model): company_name=models.CharField(max_length=250,blank=False) username=models.CharField(max_length=10,primary_key=True,unique=True,blank=False) password=models.CharField(max_length=10,unique=True,blank=False) email=models.EmailField(max_length=250,blank=False) class New_Job(models.Model): username=models.ForeignKey(User_Registration,on_delete=models.CASCADE,null=True) company_name=models.CharField(blank=False, max_length=15) job_title=models.CharField(blank=False,max_length=15) job_description=models.TextField(blank=False,max_length=300) job_requirements=models.TextField(blank=False,max_length=500) company_logo=models.ImageField(blank=True,upload_to="images/") -
Bootbox with DeleteView can't find url in Django
I'm using Bootbox to delete a listing in my app but the url is not working. Here's the script: <script> $(".delete-file").click(function () { var button = $(this); let id = button.attr("data-id"); bootbox.confirm("Are you sure you want to delete this file?", function (result) { if (result) { $.ajax({ method: "GET", url: "{% url 'delete_file' pk=id %}", success: function(){ #success } }); } }); }); </script> Urls.py url(r'^delete/(?P<pk>\d+)/$', views.FileDelete.as_view(), name="delete_file"), Html: <a data-id="{{ file.pk }}"/ class="delete-file">Delete</a> I've added the dash / because Stack was rendering this as a button. The error I'm getting is: Reverse for 'delete_file' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['delete/(?P\d+)/$'] -
Django css problems wiht svg map
I have the following html with an svg: html code and the following css: body{ background-color: rgb(162, 190, 199); } .mapdiv{ width:28%; margin: auto; } .mapdiv path { fill: #e8e9d6; stroke: #000000; stroke-width:0.8px; transition: fill 0.3s; } .mapdiv :hover { fill:rgb(177, 38, 38); } Wich looks like this: However when use the same code in django and load static like this: {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <title>SVG Map</title> <link rel="stylesheet" href="{% static 'css/style.css' %}"> </head> The css work fine except for the :hover .mapdiv :hover { fill:rgb(177, 38, 38); } Why? -
DRF: making my gateway forward incoming request with InMemoryUploadedFile to next service
My front-end used to post images with user posts to my back-end just fine. But I have implemented a gateway and now the only thing I am still struggling with is just forwarding a file that the user posts to the required service: All my gateways just dumps the incoming request data and moves on, but with the image I get an error along the lines of: TypeError: Object of type InMemoryUploadedFile is not JSON serializable My gateway view: class DailyReportImages(APIView): def post(self, request, *args, **kwargs): url = INSERT_DAILY_REPORT_IMAGE res = requests.post(url, headers=request.headers, data=json.dumps(request.data), files=request.files) return Response(res.json(), res.status_code) The only time I actually get something through to the service is with code like this: res = requests.post(url, headers=request.headers, data={"name": "test", "report": "myreport"}, files={'Screenshot from 2020-01-06 19-04-33.png': request.FILES["image"]}) But then my service complains that the name/report values are empty. What is the correct way to just route a front-end request (that used to work) through a gateway to a service (that used to work). (Even now, if I send the front-end request strait to the service everything still works, so it it just my gateway view that is not handling and forwarding the request properly) -
Read scale weight connected via rs232 cable in django
I have a system developed in Django. One of the applications has to work with a scale connected to the server via a RS232 cable. What I want to achieve is to read the weight (when an object is placed on the scale weighing platform) on the scale terminal and store it in the system database. Any pointers will be greatly appreciated. -
TypeError at /project/create 'Account' object is not iterable
I am facing a problem. I can not assign user with project using many to many field here is the details here is my model.py from django.conf import settings from django.db import models from workingSkills.models import Domain,Environment,ToolsAndTechnology class Project(models.Model): profile_of = models.ManyToManyField(settings.AUTH_USER_MODEL, null=False) project_title = models.CharField(max_length=100) domain = models.ManyToManyField(Domain) environment = models.ManyToManyField(Environment) tools_and_technology = models.ManyToManyField(ToolsAndTechnology) here is views.py @login_required(login_url= 'login') def createProject(request): form = createProjectForm() print(request.user) if request.method == 'POST': form = createProjectForm(data=request.POST) if form.is_valid(): user = Account.objects.filter(request.user) instance = form.save(commit=False) #instance.save() instance.profile_of.set(user) instance.save() return HttpResponseRedirect('createprofile') form = createProjectForm context = {'form': form} return render(request, 'project/create_project.html', context) here is error image -
Python selenium keep browser open for the next http request
I have the following view in django where I am using selenium to check the visibility of element in a webpage and return it in a http response. def check_visibility(request): element_css_selector = request.GET.get("element_css_selector") url = request.GET.get("url") chrome_options = Options() chrome_options.add_argument('--headless') chrome_options.add_argument('--no-sandbox') chrome_options.add_argument('--disable-dev-shm-usage') chrome_options.add_argument('--privileged') chrome_options.add_argument('--start-maximized') chrome_options.add_argument('--js-flags=--expose-gc') chrome_options.add_argument('--enable-precise-memory-info') chrome_options.add_argument('--disable-popup-blocking') chrome_options.add_argument('--disable-default-apps') chrome_options.add_argument('--disable-infobars') chrome_options.add_argument('--disable-gpu') chrome_options.add_argument('--enable-logging=stderr') fox = selenium.webdriver.Chrome(os.path.dirname(os.path.abspath(__file__)) + '/chromedriver', chrome_options=chrome_options) fox.set_page_load_timeout(30) try: fox.get(url) # 'http://stackoverflow.com/') required_width = fox.execute_script('return document.body.parentNode.scrollWidth') required_height = fox.execute_script('return document.body.parentNode.scrollHeight') required_width = 1440 # laptop size fox.set_window_size(required_width, required_height) time.sleep(10) except TimeoutException as ex: fox.quit() return HttpResponseBadRequest("Failed at getting page") display = False try: element = fox.find_element_by_css_selector(element_css_selector) if element.is_displayed(): display = True except NoSuchElementException: pass fox.quit() response = { "display": display } return HttpResponse(json.dumps(response), content_type="application/json") But I am checking the visibility of hundreds of elements by making the http calls to this endpoint with the same url and different element_css_selector parameter Opening and closing selenium browser hundreds of times within a few seconds causes RAM overload and makes my system crash. I want that for each new url that this endpoint gets, it should keep the selenium browser open for any of the incoming http requests that pass the same url but different css selector, so that it can check the … -
Django Static - Google Cloud Storage - CDN
I am still new with serving my Django static/media files to Google cloud storage. It's working now but I am not sure if this is right or is this enough already, do I still need to use CDN like Cloudfront or other similar services? I am really confused and any recommendation would be much appreciated. Below is my configuration. Thanks you so much! -
How to import modules in a Django project in pydriod 3
I'm trying to import a module in one of my apps to another file in that same app directory. The app 'blog' under my Django project 'django_project' where I wanted to import views.py to urls.py,from the tutorial the import was simply done by this 'from . import views' but I guess it didn't work because I was using an pydriod 3 on my phone. I tried this 'from views import *' which works perfectly in other python codes I have written but doesn't work on Django when I run the server on terminal,I still don't get what's the right way to import those files -
Djagno queryset field lookup list of objects
I'm trying to create a query of field lookup (part of a longer query). The field is a JsonField that contains a list of objects with attributes "id" and "type". This is the model (partial): class MyModel(models.Model): id = models.CharField(max_length=200) my_list = JSONField(default=dict) Let's say I have this value in my_list: my_list = [{"id": "12345", "type": "2"}, {"id": "23456", "type": "3"} ] and I want to check if any of the 'id's contains any of list of 'id's for example: ids = ['12345', '45678'] I can do something like this: MyModel.objects.filter(Q(my_list__contains=[{'id': '12345'}]) | Q(my_list__contains=[{'id':'45678'}])) In that case I will need to take that list of ids and somehow create this query out of it. Is there a better way to do it? -
Docker connection error for PostGIS and Django
I am getting an error when I run PostGIS and Django in Docker. I am trying to set up a Django project to use PostGIS database. docker-compose.yml version: '3' services: db: image: postgis/postgis environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres ports: - 5432:5432 web: build: . command: bash -c " python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000 " volumes: - .:/code ports: - "8000:8000" depends_on: - db Dockerfile FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ error message: web_1 | File "/usr/local/lib/python3.8/site-packages/psycopg2/__init__.py", line 127, in connect web_1 | conn = _connect(dsn, connection_factory=connection_factory, **kwasync) web_1 | django.db.utils.OperationalError: could not connect to server: Connection refused web_1 | Is the server running on host "db" (192.168.192.2) and accepting web_1 | TCP/IP connections on port 5432? web_1 | ht_djangoapp_web_1 exited with code 1 -
JWT authentication for django rest framework
I have a very interesting issue. We have built couple of apis using django rest framework . These apis are consumed by frontend designed using React. We use SAML withe sessions to manage the authentication process.This SAML authentication is handled by a django middleware. Now I have a requirement to make some of these apis accessible to a different domain, where their backend would call our apis programmatically . So I need to give auth details to them for them to able to access it. Since SAML is enabled here, how do I able to set the authentication using JWT and give them the tokens. The saml middleware code looks like this, def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if hasattr(request, 'user') and request.user.is_anonymous and 'samlUserdata' in request.session: data = request.session['samlUserdata']['mail'][0] if data is not None: try: email=data user = User.objects.get(email=email) except ObjectDoesNotExist: user = User.objects.create_user(username=data.split("@")[0], email=data) login(request,user) request.session.set_expiry(settings.SESSION_EXPIRY) elif not settings.DEBUG and 'samlUserdata' not in request.session \ and not request.get_full_path().startswith('/admin'): if not request.path == settings.REDIRECT_LOGIN_URL and not request.path == REDIRECT_LOGOUT_URL and \ not request.path == '/saml': return redirect(settings.REDIRECT_LOGIN_URL) response = self.get_response(request) request.session.set_expiry(settings.SESSION_EXPIRY) return response Now for this I am trying to use djangorestframework-simplejwt. But since SAML is … -
How to run Python functions in frontend
I know front-end developement with React.js. I want to make a basic web-app where I use some python functions (for example on onClick of buttons etc). These functions would mainly revolve around machine learning algorithms where I will be using pre-built libraries (won't be too complex). Is there any way to run python functions from React.js apart from ajax queries? If not, which Python framework should I use to do web development in Python such that I can directly run Python functions as well? I have come across names like Django, Tinkter and Flask but couldn't figure out what exactly would suit my requirement. -
Create new item and select the item like Django admin
I have an model that has a one-to-one relationship with another mode. Model Code has relationship with Language. What I can do: User can select the Language while then write new code from the list. But I want to add a system like the Django Admin panel where user can also add new Language and select while adding new code. I am new to Django, can anyone help? -
Running Face Recognition when new user is added Django
I have this ViewSet which returns my Student model and should run the Facial Recognition, however when I start my Django server, the Facial Recognition runs without being POSTed to and the server never starts because it started the facial rec class StudentView(viewsets.ModelViewSet): queryset = Student.objects.all() serializer_class = StudentSerializer recognize.break_run() recognize.train("media", model_save_path="trained_knn_model.clf") recognize.run_recognition(0, faceFound) Output: I:\Programs\Jetbrains\Toolbox\apps\PyCharm-P\ch-0\202.6948.78\bin\runnerw64.exe I:\Programs\anaconda3\envs\AutoSecurityBackend\python.exe I:/Projects/AutoSecurityBackend/manage.py runserver 8000 Watching for file changes with StatReloader Performing system checks... Setting cameras up... Any ideas as to what is causing this, I'm pretty new to Django