Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django display loop in template
Hello I am doing a calculation in my view for the customers, I need to display the result for every customer in the template. I know I need to loop through in the template but unsure what values to use.Image of view for loop For example in the picture the value I need to show is 'first_day_rate_calc'. If I just put {{ first_day_rate_calc}} in my template I only get one result but I need to display them all. Thank you. -
Django : how to add a link in django admin form and redirect to another page and select an input, and comes back to the form
I have a django admin form as shown. When a User inputs a data in the content_type field, a link should appear and it will redirect to another page which shows object values corresponding to the content_type User selected earlier. From there user can select an object and the id of the object will be saved to Object_Id field in the form. how it can be implemented ? This is the django admin form -
Django: How to show the updated information on the page without reloading
I am working in Djnago and I want to update the information without reloading the page. At first, I have used Ajax for not reloading the page after submitting the form, and it is working properly. Then I used Ajax for get operation and it is working too but to see the new information on the page, I have to refresh the page. The view.py file: def bfs_view(request): form = BFSForm(request.POST or None) if form.is_valid(): form.save() form = BFSForm() try: image_url_info = None num_states_explored = None final_solution = None text_file = open("BFS\outputs\maze.txt", "w") field_name = 'description' input_value = BFS.objects.latest('id') field_object = BFS._meta.get_field(field_name) field_value = field_object.value_from_object(input_value) field_string_value = str(field_value).split("\n") text_file.writelines(field_string_value) text_file.close() m = Maze("BFS\outputs\maze.txt") print("Maze:") m.print() print("Solving...") m.solve() print("States Explored:", m.num_explored) print("Solution:") m.print() image_url_info = "/../../../static/search/bfs/maze.png" num_states_explored = m.num_explored # final_solution = ''.join(m.end_result) final_solution = str(''.join(m.end_result)) print(''.join(m.end_result)) # BFS.objects.latest('id').delete() except: print("BFS ERROR: Error in the try session of BFS in view.py") context = { 'form': form, 'image_url': image_url_info, 'states_explored': num_states_explored, 'solution': final_solution} return render(request, "BFS/bfs.html", context) def post_bfs_view(request): if request.method == "POST" and request.is_ajax(): bfs_view(request) return JsonResponse({"success":True}, status=200) return JsonResponse({"success":False}, status=400) def get_bfs_view(request): if request.method == "GET" and request.is_ajax(): try: image_url_info = None num_states_explored = None final_solution = None text_file = … -
Django ORM order by filters
Help me please with my problem. I want to get objects sorted first by one filter and then by another filter. How can I get objects with this ordering in 1 query to the DB (need for pagination)? This example shows queryset without ordering: rooms = Room.objects.filter(Q(name__icontains=search) | Q(owner__username__icontains=search)) I have the room model: models.py from django.db import models from django.contrib.auth.models import User class Room(models.Model): name = models.CharField(max_length=150) owner = models.ForeignKey(User, on_delete=models.CASCADE) views.py (my bad code) class RoomListView(ListAPIView): def get_queryset(self): search = 'test' # for example rooms1 = Room.objects.filter(owner__username__icontains=search) rooms2 = Room.objects.filter(name__icontains=search) return list(rooms1) + list(rooms2) The wrong result: search = "test" [ { "id":1, "name":"test", "owner":{ "username":"user1" } }, { "id":2, "name":"room1", "owner":{ "username":"test" } }, { "id":3, "name":"test2", "owner":{ "username":"user2" } } ] The correct result: search = "test" [ { "id":2, "name":"room1", "owner":{ "username":"test" } }, { "id":1, "name":"test", "owner":{ "username":"user1" } }, { "id":3, "name":"test2", "owner":{ "username":"user2" } } ] How can I get objects with this ordering in 1 query to the DB (need for pagination)? -
How to disable HTML view with django?
Imagine you are using django guardian for some object level restrictions. Now I have the following code; admin.py class ControlAdmin(GuardedModelAdmin): prepopulated_fields = {"description": ("title",)} list_display = ('title', 'description', 'priority') search_fields = ('title', 'description') ordering = ('-title',) Now I have selected in the database that user maxdh has no permissions for viewing a control, which checks out: >>> control = Control.objects.first() >>> checker = ObjectPermissionChecker(maxdh) >>> checker.has_perm('change_control', control) False >>> checker.has_perm('view_control', control) False However when I go to the html which renders the table for the controls I can still see the table: html: <div class="card-body"> <div class="card-body"> {% load django_tables2 %} {% render_table controls %} What am I is missing? I read the docs but could not identify Please help! -
Sending part of the data to frontend and after clicking next pages sending another request to backend for the rest of it for efficiency
I have a large dataset sometimes containing millions of products data. When I am sending this to frontend I limit it to 1000 product at first to be fast. This is how I am doing with Django rest: def get_products(self, request, pk=None): page = int(request.query_params['page']) if 'page' in request.query_params else 0 page_size = 1000 data = list(collection.find(filter_query, {'_id': 0}).skip(page * page_size).limit(page_size)) total_count: collection.count() return Response({'message': 'success', 'data': data, 'count':total_count}, 200) So in React, I accept the first 1000 products at first request. I show them on AG-GRID table. But I also need to show real page numbers ( I have the total count of the products). If user clicks on page=650 for example, I will send another request to the backend with the equivalent page number and fetch the remaining data. `http://localhost:8000/${ID}/products?page=${page}` This is how I fetch data and show in AG grid on frontend: React.useEffect(() => { jwtAxios( `http://localhost:8000/${ID}/products/` ).then((result) => { if (!result || !result.data.data || !result.data.data.length) { setRowData([]); setColumnData([]); return; } setRowData(result.data.data); // Get column fields const columnDefs = []; Object.keys(result.data.data[0]).map((fieldName) => { columnDefs.push({ headerName: fieldName, field: fieldName, }); return null; }); setColumnData(columnDefs); }); }, [catalogID]); // enables pagination in the grid const pagination = true; const … -
django RuntimeError at /admin/users/user/1/change/, Single thread executor already being used, would deadlock
i tried to make chat app with django-channels. RuntimeError is occurred when New django-chaneels project and edit data in adminsite.. I'm not sure that i think the error occurred because i made several django-channels projects.. When I built my first project, websocket is not working.. so i made other 2nd, 3rd, 4th projects with django-channels.. now websocket is connected, but i have trouble with RuntimeError (Error message: Single thread executor already being user, would deadlock) So.. what can i do for this...? myproject/settings.py enter code heremport os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = "django-insecure-is!$&voe3y058!2sus9egmxh@d!$)=l&o8_vl=m8zz!ap+d#a#" # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "users.apps.UsersConfig", "channels", "core.apps.CoreConfig", "broadcasts.apps.BroadcastsConfig", ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] ROOT_URLCONF = "busker.urls" TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "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", ], }, }, ] … -
Django read from filefield returns hex, when I try to decode it I get weird characters
Im builing a django website that matches documents, and I upload documents to Minio bucket, so the defaut storage is storages.backends.s3boto3.S3Boto3Storage from django-storages and not the default Django storage class. This question is similar to Why is Django FieldFIle readline() returning the hex version of a text file? class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['title', 'doc_file'] def form_valid(self, form): form.instance.author = self.request.user f = form.instance.doc_file.open('r') text = ''.join(i.decode("utf-8", 'ignore') for i in f.readlines()) form.instance.content = ''.join( [i if ord(i) < 128 else ' ' for i in text]) return super().form_valid(form) If I upload a .txt file it reads it properly but if I upload a doc file it gives me alot of weird characters even after I do ##''.join([i if ord(i) < 128 else ' ' for i in text])## For example if the file contains just SSSSSSSSssss, I get !# ddddSxSx l SSSSSSSSssss OJQJCJ &p@P ! i4@4NormalCJOJPJQJmH <A@<Default Paragraph Font GTimes New Roman5Symbol3Arial;Helvetica 0hKl&Kl& 0" Oh+'0 .+,0 "Root Entry F$1TableWordDocumentSummaryInformation(DocumentSummaryInformation8 -
How can we align child div right side of the parent div
In my below code I have one anchor tag and inside that anchor tag I have one div. So here what i am trying is to align both anchor tag and div side by side. In my case while I am giving left and right property to div then it is hiding inside anchor tag it is not appearing left and right so how can we align it side by side like left side is anchor and right side is div. {% if CategoriesBar%} {% for Categories in CategoriesBar %} <a class="trigger" href="{% url 'getProductsByCategory' Categories.cat_name {{Categories.cat_name}} <div class="sub"> {% for subCategories in SubCategoriesBar %} {% if Categories.cat_id == subCategories.parent_id %} <div class="item">{{subCategories.cat_name}}</div> {% endif %} {% endfor %} </div> </a> {% endfor %} {% endif %} css .trigger { box-sizing: border-box; position: relative; width: 120px; margin: 0 0 50px; padding: 10px; background: #bada55; text-align: center; } .sub { box-sizing: border-box; position: absolute; top: 100px; left: 0; width: 120px; background: #4863a0; color: #fff; text-align: left; -
How to solve PermissionError:[Errno13] using Python matplotlib.pyplot.savefig in Ubuntu 18.04 apache2 server Django
I made a line chart using this code in Django, Python 3.6, Apache2, Ubuntu 18.04 Before moved to the server(Ubuntu), I tested in my local environment(Mac OS), And it worked. def saveChart(request): ... plt.plot(val1, var2) plt.savefig('django project dir/static/chart.png') plt.close() And I got PermissionError:[Errno13] with plt.savefig() I've tried to give a 777 permission on my view.py but it didn't work. Is there anything I can do? -
AttributeError: module 'django.http.request' has no attribute 'user // i have Django rest installed
Error I am getting AttributeError: module 'django.http.request' has no attribute 'user' Signal I am trying to send when user logs in def auth_done(sender, **kwargs): print('User has logged in') tok = Token.objects.create(user=request.user) print(tok.key()) user_logged_in.connect(auth_done, sender=User) Login view @csrf_exempt def login_in(request): if request.method == 'POST': name = request.POST['first_name'] password = request.POST['password'] user = authenticate(username=name, password=password) if user is not None: print(user) login(request, user) tok = Token.objects.create(user=request.user) print(tok.key) print('User is authenticated') else: print('Not authenticated') return render(request, 'Auth/user.html') Settings REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', ], # Use Django's standard `django.contrib.auth` permissions, 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.isAuthenticated' ] } -
pipenv failed to build image pip
I was trying to start a pipenv shell to start working on a django project on python 3.8.9 and it keeps giving me this error: Using C:/Users/CY/AppData/Local/Programs/Python/Python38/python.exe (3.8.9) to create virtualenv... [=== ] Creating virtual environment...RuntimeError: failed to build image pip because: Traceback (most recent call last): File "c:\users\cy\appdata\local\programs\python\python38\lib\site-packages\virtualenv\seed\embed\via_app_data\via_app_data.py", line 57, in _install installer.install(creator.interpreter.version_info) File "c:\users\cy\appdata\local\programs\python\python38\lib\site-packages\virtualenv\seed\embed\via_app_data\pip_install\base.py", line 46, in install for name, module in self._console_scripts.items(): File "c:\users\cy\appdata\local\programs\python\python38\lib\site-packages\virtualenv\seed\embed\via_app_data\pip_install\base.py", line 131, in _console_scripts entry_points = self._dist_info / "entry_points.txt" File "c:\users\cy\appdata\local\programs\python\python38\lib\site-packages\virtualenv\seed\embed\via_app_data\pip_install\base.py", line 118, in _dist_info raise RuntimeError(msg) # pragma: no cover RuntimeError: no .dist-info at C:\Users\CY\AppData\Local\pypa\virtualenv\wheel\3.8\image\1\CopyPipInstall\pip-21.1.1-py3-none-any, has pip Failed creating virtual environment [pipenv.exceptions.VirtualenvCreationException]: Failed to create virtual environment. -
AttributeError at /search 'search' object has no attribute 'cleaned_data' django
def searchform(request): if request.method == "POST": form1 = search(request.POST) if form1.is_valid : titl = form1.cleaned_data.get("query") top = False for i in util.list_entries(): if titl == i: htmlconvo = util.get_entry(titl) mdcovo = markdowner.convert(htmlconvo) top = True break if top : return HttpResponseRedirect(request,"encyclopedia/title.html",{ "form":form1, "content":mdcovo, "title": titl }) else: lst = [] for j in util.list_entries(): if titl in j: lst.append(j) if len(lst) == 0: form1 = search() return render(request, "encyclopedia/error.html", { 'form': form1, }) else: return render(request, "encyclopedia/index.html", { "entries": lst, "form": form1}) else: form1 = search() return render(request,"encyclopedia/error.html",{ "form":form1, }) This is the view code of search in which i am getting an error AttributeError at /search 'search' object has no attribute 'cleaned_data' What should i do <form action="{% url 'search' %}" method="POST"> {% csrf_token %} <input type="text" name="search" placeholder="Search Encyclopedia"> </form> this is my layout.html -
How to get all of field names in serializer
Imagine if I have a ModelSerializer. How can I get all of my field names in serializer? for example: class AnyModelSerializer(serializers.ModelSerializer): class Meta: model = AnyModel fields = ['field1`, `field2`, ...] I want something to iterate through all field names, something like: for field in field_names: # do stuff here ... -
How to get a user's manager by python LDAP or Django LDAP?
How to get a user's manager by python LDAP or Django LDAP? BTW, could it possible to check if a user is deactived (means have left company)? -
Django pass variables from views to Ajax
In my django project i have a method in a view where execute some calculation e define a variable for message and pass to my Ajax method. I do: views.py ... try: msg="Prodotto inserito nel carrello" if request.POST['pgift'] == "true": <do some calculations> else: msg = "Non hai abbastanza punti per acquistare utilizzando il gift" except Exception as e: msg = "Errore imprevisto. Riprova ad inserire il prodotto o contattaci per maggiori informazioni" response = [] valrst = {'r_msg': msg} response.append(valrst) json = simplejson.dumps(response) return HttpResponse( json, content_type='application/json' ) then in my js code: test.js function update_item(upd_id, qta_val) { //oCtemplates = document.getElementById("t_select"); $.ajax({ type: "POST", url: "/update_cart/", data: { "updid": upd_id, "nqta": qta_val }, success: function (data) { $.each(data, function (index) { }); } }); How can i pass my django msg variable into my js for ceate an alert with this data? So many thanks in advance Manuel -
"TemplateDoesNotExist at/" issue in Python Django
Can someone assist me with the below error? I can't figure out the error here. I can't move forward with this error. I am a new learner of Django. I need to fix this issue ASAP. Thank you. -
How do I use a custom class based validator for multiple fields in Django Rest Framework?
I need to validate a field depending on another field with multiple validators like so: logged_in_id = serializers.UUIDField(validators=[Internal() | LoggedIn()]) where Internal and LoggedIn are class based validators: class LoggedIn: def __call__(self, value): if other_id == value: # other_id is another field like logged_in_id return True return False Can I access the validated_data of the serializer in a validator class somehow? Or write a validator class not for a specific field, but for the whole serializer, like the validate function? -
Django: Attributes Not Being Applied to Form
As the title states I have a django form that I am trying to customize yet for some reason the attributes are not being applied to it. I have used the exact same code in other projects and it worked perfectly except now for some reason it is not. The only other question I have found by googling is this one question. I have the exact same issue as this, I am trying to inject attributes into my label field but for what ever reason it is not working no matter what I have tried. My code is as follows: class MyAuthenticationForm(AuthenticationForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['username'].widget = forms.widgets.TextInput(attrs={ 'class': 'form-control' }) self.fields['password'].widget = forms.widgets.PasswordInput(attrs={ 'class': 'form-control' }) The weirdest thing was when I first started coding this morning it worked, then every subsequent time I visited my form it stopped. I truly have no idea what is going on and why this isn't working. Any help is greatly appreciated! -
how to use jquery selector to select id of django template variable value?
I have a django web app. In the html page, some element id in the for loop used django template variable value, as in the for loop every line should have different id value. But in the below jquery, when I tried to use selector, the django template variable value could not be selected(obj.title here in my case). <script src="http://code.jquery.com/jquery-2.1.0.min.js"></script> {% for obj in query_results_book %} <td> <select name="keep_discard" id="keep_discard" onchange="GetVal(this)"> <option value="Keep">Keep</option> <option value="Discard">Discard</option> </select> <select name="discard_reason" id="{{obj.title}}"> <option value="Change edition">Change edition</option> <option value="Change to eTextbook">Change to eTextbook</option> <option value="Change title">Change title</option> <option value="No material required">No material required</option> </select> </td> {%endfor%} <script> function GetVal(obj){ var index = obj.selectedIndex; if(index == 1){ $("#obj.title").show(); } else{ $("#obj.title ").hide(); } } </script> Now the js script could not work for the query selector, it does not select my element. How could I let the jquery selector select some id, which is my django template variable value? -
How to send data (from Reactjs) through a class based API (Django Rest Framework)
I'm trying to send some form data to the backend, I always used function based api but since I couldn't find how to do what i needed I followed a tutorial and got some class based API but I don't really know how it works. Using POSTMAN and by entering all the keys and values, the request works and the data is inserted, however inside my react Project when I send the data It doesn't go in Views.py class TestView(APIView): def post(self, request, *args, **kwargs): serializer = EnrolSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors) Serializers.py class EnrolSerializer(serializers.ModelSerializer): class Meta: model = Enroles fields = '__all__' Urls.py path('testapi/', TestView.as_view(), name='testing'), I'm not too sure how to send the data since I'm taking regular text-based data along with file and image Page.js import React, { useState } from "react"; import { useDispatch, useSelector } from "react-redux"; import Registration from "./Registration"; import RegistrationSteps from "./RegistrationSteps"; import { Container, Button, Row, Col, Form } from "react-bootstrap"; import FormContainer from "../FormContainer"; import pictures from "../../pictures"; import { finalPageRegistration, } from "../../actions/registrationActions"; function RegistrationFinale({ history }) { const [dossier, setDossier] = useState(); const [avatar, setAvatar] = useState(); const dispatch = useDispatch(); const registrationInfos = useSelector((state) … -
running heroku django app from a virtual environment
I have a django app which i run from my virtual environment on my localhost and in that virtual environment i made some changes to django admin panel's html source code but when i deploy it to heroku. it installs another django with pip and doesn't run from the virtual environment i made changes to resulting into the loss of the changes i made. -
Problem with Django query on Elastic Beanstalk
I've met a problem with my Django query. So, I have a filter like this. Discount.objects.filter(end_date__gte=date.today()) #end_date is DateField It works properly on my localhost. But, on the server that I deployed with Elastic Beanstalk, it still returns yesterday's records. And, when I redeploy the server (without any changes), it works fine, yesterday's records have been filtered and hided. I tried but can't find where is the problem. Hope anyone can help me. Thank you all. -
Setup apache2 for routing internal requests
I have multiple Django applications, running on the same server under apache2 mod_wsgi, each having its own domain and conf file. etc/ ├─ apache2/ │ ├─ sites-available/ │ │ ├─ 000-default.conf │ │ ├─ a.example.com.conf │ │ ├─ b.example.com.conf These applications communicate with each other via http over the internet. I would like to route these requests locally without going through the internet seeking for reduced latency. My current setup is based on the typical Django mod_wsgi as documented. ... WSGIDaemonProcess example.com python-home=/path/to/venv python-path=/path/to/mysite.com WSGIProcessGroup example.com WSGIScriptAlias /mysite /path/to/mysite.com/mysite/wsgi.py process-group=example.com ... Any suggestion for a way to allow application A to reach application B via localhost call for internal requests ? -
How to show data from Django (DRF) to frontend of vue.js?
Here are the snippets provided required to solve the issue. I would be very thankful if anyone solve this isssue.