Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Display Image in HTML from SSH with django
I'm trying to display a randomly fetched image via ssh-connection on an HTML page with Django. Currently, I save a temporary image and then display it in the HTML, but this doesn't seem to be necessary or right. views.py: def image_view(request): rgb_img = IMGLIB.get_random_img() # fetches the img with paramiko and returns numpy.array img = Image.fromarray(rgb_img, 'RGB') img.save(os.path.join(BASE_DIR, 'static/img/temp.png')) context = {} return render(request, 'app1/app1.html', context) IMGLIB.get_random_img() is a custom made python library for our postgis database and uses paramiko for ssh to fetch images: [...] with sftp.open(tif_path) as f: f.prefetch() s = f.read() with MemoryFile(s) as mem: file = mem.open() rgb_img = get_rgb_img(file) return rgb_img Since the original file is actually not .png or .jpg, but a .tif file its being convertet to "plain" rgb in get_rgb_img() Question: How can I efficiently display the RGB with my function-based view on HTML without storing it as a temporary file in Django? -
Can I use google social token to send email through gmail? Django app
I have a django app where I implementeed a method to sign-up through gmail authentication. Now I would like to allow users to send emails using my app through their gmail account. If a user signs-up with Gmail I have a social token from him, is that enough to allow them to send emails through gmail or do I need to go through the manual work of downloading credential.json for each users? -
How to style ModelForm Choicefield in Django?
I'm trying to style the ChoiceField options for the Medicines in a prescription ModelForm to be in this format: <select> <option value="">Select a Medicine</option> <optgroup label="Favorite Medicines"> <option value="First">Brufen - Abbott - 600 Mg - Tablets</option> </optgroup> <optgroup label="Other"> <option value="First">Brufen - Abbott - 400 Mg - Tablets</option> </optgroup> </select> Where I can get the values form my Medicine model, and check whether it is exits in the user's medicine's favorite list, if yes the medicine should exist in the 'favorite Medicines' group, otherwise it should show in 'Other' group. This is My forms.py: class PatientPrescriptionForm (ModelForm): patient = forms.CharField( label='', widget=forms.TextInput(attrs={'class': "text-field w-input", 'maxlength': "256", 'name': "prescPatient", 'data-name': "prescPatient", 'placeholder': "Add a Patient", 'id': "prescPatient"})) category = forms.ChoiceField( label='', choices=Medicine.CATEGORY, widget=forms.Select(attrs={'id': "PrescMedCat", 'name': "PrescMedCat", 'required': "", 'data-name': "PrescMedCat", 'class': "select-field w-select"})) dose = forms.CharField( label='', widget=forms.TextInput(attrs={'class': "text-field small w-input", 'maxlength': "256", 'name': "PrescDose", 'data-name': "PrescDose", 'placeholder': "Dose", 'id': "PrescDose", 'required': ""})) dose_unit = forms.CharField( label='', widget=forms.TextInput(attrs={'class': "text-field small w-input", 'maxlength': "256", 'name': "PrescDoseUnit", 'data-name': "PrescDoseUnit", 'placeholder': "Dose Unit", 'id': "PrescDoseUnit", 'required': ""})) EN_name = forms.ChoiceField( label='', widget=forms.Select(attrs={'id': "prescMedName", 'name': "prescMedName", 'required': "", 'data-name': "prescMedName", 'class': "select-field w-select"})) EN_route = forms.ChoiceField( label='', widget=forms.Select(attrs={'id': "prescRoute", 'name': "prescRoute", 'data-name': "prescRoute", 'class': "select-field-2 … -
Deploying Django application To AWS ElasticBeanstalk
I am trying to deploy a django application to AWS ElasticBeanstalk. I am working on a Linux machine. It all goes well but when deployment is done I get "502 Gateway Error". From a deep search I found that people with the similar problem created Procfile to the root directory of the project and added the following to that: "web: gunicorn--bind :8000 --workers 3 --threads 2 applicationName.wsgi:application". I tried that but then I get "ServiceError - Failed to deploy application." Any clues on that? -
Docker ModuleNotFoundError: No module named 'xhtml2pdf'
I've looked through several websites but I can't seem to find an answer. I'm new to django and docker and whilist building my first project which is a quotation generator, I've been looking for different ways to generate a pdf for each quote. I found a couple of tutorials on xhtml2pdf and my error appears when I try to run docker-compose up and get the following error: ModuleNotFoundError: No module named 'xhtml2pdf' I've installed xhtml2pdf using pip3 install xhtml2pdf and whenever I try to run it again I get: Requirement already satisfied: xhtml2pdf, the same for its dependencies. I've also tried pip install --upgrade --force-reinstall xhtml2pdf with no luck on my views.py file if I write from xhtml2pdf import pisa vs code gives me no errors regarding the import My requirements.txt lookslike this: psycopg2==2.9.1 pillow>=8.3 xhtml2pdf==0.2.5 reportlab==3.6.1 Dockerfile: FROM python:3.8 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /code COPY requirements.txt . RUN pip install -r requirements.txt COPY . . -
django refresh particular table instead of whole page
I'm trying to create a search function where instead of redirecting me to another page, I want to display a table instead. here's my index.html <body> <h2>My Personal TodoApp Project</h2> <br> <form action="/searchlist/" method="get">{%csrf_token%} <input type="text" name="content" placeholder="Search a todolist" class="form-control"> <input class="button button2" type="submit" name="submit" value="Search"/> </form> <form action="/addTodo/" method="post">{%csrf_token%} <input type="text" name="content" placeholder="Add a todolist" class="form-control"/> <input class="button button" type="submit" value="Add"/> </form> # where i want my table diplay after searching a particular word <div id="searchlistdiv"></div> </body> here's the table should be displayed in index.html, I'll call it searchlistdiv.html <table> <tr> <th colspan="2">List of Todos</th> </tr> {% for result in results %} <tr> <td>{{result.content}}</td> <td><form action="/deleteTodo/{{todo_items.id}}/" style="display: inline; " method="post"> {%csrf_token%} <input class="button button1" type="submit" value="Delete"/> </form></td> </tr> {% endfor %} </tr> </table> and my views.py def searchtodolist(request): if request.method == 'GET': query = request.GET.get('content', None) if query: results = Todoitem.objects.filter(content__contains=query) return render(request, 'todoapp.html', {"results": results}) return render(request, 'todoapp.html') -
JS files not updating in python dev server
I am running a local development server with python using VS as ide through python manage.py runserver. When I update and save JS files, the views in browser do not update (even restarting the server and PC). I refreshed the cache of the browser, however it does not resolve the issue. Anyone may know the root of the problem and/or possible solution? Thanks in advance! -
Django how to update objects status in class based views?
In function based views I am using this code Notifications.objects.filter(receiver=user, is_seen=False).update(is_seen=True) for update an objects status from False to True. How to do that in class based view: here is my code: class ListNoti(ListView): model = Notifications template_name = 'notifications/notifications.html' def get_context_data(self, **kwargs): data = super(ListNoti,self).get_context_data(**kwargs) data['author_noti'] = Notifications.objects.filter(receiver=self.request.user,duplicate_value="author").order_by('-date') data['commenter_noti'] = Notifications.objects.all().filter(sender=self.request.user,duplicate_value="commenter").order_by('-date') return data I also tried this code in my class based view but didn't work. def update_noti_status(self, *args, **kwargs): noti = Notifications.objects.filter(is_seen=False).update(is_seen=True) return noti -
Django rest framework invert serializers
In Django, I have in models.py models defined like this : class foo1(models.Model): name = models.CharField(max_length=100) class foo2(models.Model): name = models.CharField(max_length=100) .... foo1 = models.ForeignKey(foo1, on_delete=models.SET_NULL, null=True) class foo3(models.Model): name = models.CharField(max_length=100) .... foo2 = models.ForeignKey(foo2, on_delete=models.SET_NULL, null=True) class foo4(models.Model): name = models.CharField(max_length=100) .... foo3 = models.ForeignKey(foo3, on_delete=models.SET_NULL, null=True) .... and what i'm expecting to get is a json format like this : [ { "id": 1, "name": "test1", "foo2": { "id": 1, "name": "test1", "foo3": { "id": 1, "name": "test1", "foo3": { ... } }, .... ] What I have tried so far, and it gives me the opposite result of what I want, here is my serlialize.py : class NestedFoo1Serializer(serializers.ModelSerializer): class Meta: model = Company fields = '__all__' class Nestedfoo2Serializer(serializers.ModelSerializer): foo1= NestedFoo1Serializer(read_only=True) class Meta: model = Facility fields = '__all__' the resault : [ { "id": 1, "name": "test1", "foo4": { "id": 1, "name": "test1", "foo3": { "id": 1, "name": "test1", "foo2": { ... } }, .... ] and here is my view.py : class TreeView(generics.ListAPIView): serializer_class = NestedFoo4Serializer queryset = foo4.objects.all() -
how can I retrieve a specific JSON data
I want to retrieve a specific data after selecting an option form. When I select I got data in JSON format which I can't separated. I have tried obj.purchase_price but got undefined. my following code provide following data [{"model": "acc.productdetails", "pk": 4, "fields": {"purchase_price": "214.00"}}] I want purchase_price value for my form. Please help me to separate the value. My codes are given bellow In Views def priceFilter(request): product_id = request.GET.get('product_id',None) price = { 'data':serializers.serialize("json",ProductDetails.objects.filter(id=product_id), fields=('purchase_price',)) } return JsonResponse(price) In my page, script <script> $("#id_price").change(function () { var form = $(this).closest("form"); $.ajax({ url: form.attr("data-validate-price-url"), data: form.serialize(), dataType: 'json', success: function (price) { if (price.data) { let obj = price.data ; alert(obj) ; } } }); }); </script> I want to show my data here <input type="text" name="price" class="form-control" id="p_price" required> -
ModuleNotFoundError: No module named 'spyder'
I want to use a crawler project inside Django. I've set up celery and beats correctly but when I use the scraper project inside a Django app gives me the error ModuleNotFound even if I have added it to the setting.py file. The structure of the project is the following: |-- celery.log |-- celerybeat-schedule.db |-- db.sqlite3 |-- manage.py |-- requirements.txt |-- scraper | |-- __init__.py | |-- admin.py | |-- apps.py | |-- migrations | | |-- __init__.py | |-- models.py | |-- spyder | | |-- domain.py | | |-- general.py | | |-- link_finder.py | | `-- spider.py | |-- tasks.py | |-- tests.py | |-- urls.py | `-- views.py |-- src | |-- __init__.py | |-- asgi.py | |-- celery.py | |-- settings.py | |-- urls.py | `-- wsgi.py `-- templates `-- index.html The file scraper/spyder/tasks.py initiates the crawler and has the following code: ... from celery import shared_task import threading from queue import Queue from spyder.spider import Spider from spyder.domain import * from spyder.general import * ... -
Django download file using CBV
How to use Class Based Views eg. TemplateView to display Django template with download links? Clicking the link should start downloading selected file. I already know how to do it with Function Based Views. Also - is it good idea to put filename slug as URL parameter (filename) for GET requests or should I use different method? -
why Django favicon reloads on routing pages? (about SSR)
Hi I'm using Django framework and made a simple web application. But on routing each page, I could see favicon reloads (OR maybe it could be loading html file). So here's the question. Is it correct that favicon reloads itself? Or is it because on routing pages, as page needs to be loaded, favicon looks like loading motion? (But if so I'm so curious because literally I had no single code in some_page.html file even tags...) I also made a simple Next.js web application. But on routing pages, favicon stays still and I couldn't see any loading motions. So does it because when requesting routing on Django application, as it needs to return render('index.html') in views.py file, we see loading motions? I suppose this is because Django runs by SSR (just rendering pages. And even it renders ON REQUESTs), Next.js by SSG (pre-rendering pages). If so, I would much prefer JavaScript to Python... Thank you for reading my question! -
django-rest-passwordreset create and send token manually
reading the [django-rest-passwordreset][1] I have not found a way to create and send the reset_password_token manually, meaning without the use of the endpoint created by the package. Currently I have this implementation: urlpatterns = [ ... url(r'^api/password_reset/', include('django_rest_passwordreset.urls', namespace='password_reset')), ... ] Then when a user requests a password reset I send an email using the Signal provided by the package: @receiver(reset_password_token_created) def password_reset_token_created(sender, instance, reset_password_token, *args, **kwargs): """ Handles password reset tokens When a token is created, an e-mail needs to be sent to the user :param reset_password_token: Token Model Object :return: """ # send an e-mail to the user context = { 'email': reset_password_token.user.email, 'reset_password_url': f"{BASE_URL}new-password?token={reset_password_token.key}" } send_reset_pwd_to_sendingblue.delay(context) However, in my case, I want to programmatically create the token and send it to the user without the use of the endpoint meaning the user won't reset their password through the endpoint, rather my application will create the token and send it to the user. How can I go about doing that? [1]: https://pypi.org/project/django-rest-passwordreset/ -
How do I change a model after I ran makemigrations and migrate? Django
I made a model ran all the neccesery migrations commands and I want to add a field and change a field. How do i do that? I thought about changing them in models.py and ran makemigrations and migrate again but I dont know if that somehow ruins them. -
Python can't see environment variables from script
I was invited to collaborate on a Django project and now I need to set it up. I am stuck with setting environment variables. In the given project envparse is used. I was provided an .env file, where items look like export EMAIL="12345" Then i run source .env Supposedly it should be enough to start, but when I run python manage.py runserver It throws an error django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. Seemingly Python/Django somehow can't access environmental variables. I wrote a simple script in the same venv to check it and the script leads to the same result. from envparse import env def checker(environment_variable_to_check: str): print(env(environment_variable_to_check)) if __name__ == '__main__': checker('EMAIL') However, if I use python interpreter with basically the same command, I get the correct result >>> from envparse import env >>> print(env('EMAIL')) 12345 >>> I can't figure out what's wrong with it. I totally understand it's some simple newbie issue, and most probably I will get a bunch of downvotes, but I've already wasted two days trying to figure it out and I need some help. -
I want to complete a simple assignment [closed]
I want to crawl data from https://news.ycombinator.com/. After crawling I only need title, links and total comment number. After that I have to save that in database and show that data on the UI. Please help needed -
import "pyrebase" could not be resolve pylance(reportMissingImports)
Installed pyrebase4 in my system but still unable to import in my view.py even tried "import pyrebase4" still the same error, I followed a youtube tutorial for it I followed the exact same things he/she said can any explain me what is that error and how can I resolve it. from django.http.response import HttpResponse from django.shortcuts import render import pyrebase #here is the error from pyrebase.pyrebase import Database config={ "apiKey": "AIzaSyD4P5ITiUyMlb-A3OmjrgNNeqZ2vMqKTow", "authDomain": "filterflare.firebaseapp.com", "projectId": "filterflare", "storageBucket": "filterflare.appspot.com", "messagingSenderId": "828393456186", "appId": "1:828393456186:web:14b075fb0e9ad519926b03", "measurementId": "G-8W3W2ED4RH" } firebase= pyrebase.initialize_app(config) db=firebase.database() def home(request): test=db.child('name').get().val() return render(request,"html/editorhtml.html", {"testname": test}) def download(request): return render(request,"html/finalimage.html") did I missed something in installed apps? INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] -
In Django raw query selects all my user twice
I have a raw query in my view: SELECT stressz_profile.id, projekt_id, user_name_id, szerv01b AS szervkult01a FROM stressz_szervezetikultura INNER JOIN stressz_profile WHERE stressz_profile.projekt_id=1 I try to get the data from the db but every time it duplicates the results. It selects my users two times like on the image below and I can't figure it out why. -
Error when installing node-django-hashers
In order to implement password hashing on the server side with nodeJS 14.7.4, we selected node-django-hashers so that it can be implemented the same with django website side, but when installing module, we are recieving the following error. docker build -t auth_api_t1 . [+] Building 102.3s (16/16) FINISHED => [internal] load build definition from Dockerfile 0.3s => => transferring dockerfile: 32B 0.0s => [internal] load .dockerignore 0.3s => => transferring context: 2B 0.0s => [internal] load metadata for docker.io/library/ubuntu:latest 0.0s => [internal] load build context 0.2s => => transferring context: 92B 0.0s => [ 1/12] FROM docker.io/library/ubuntu:latest 0.0s => CACHED [ 2/12] WORKDIR /data 0.0s => CACHED [ 3/12] COPY . /data 0.0s => CACHED [ 4/12] RUN apt update && apt install -y python2 && apt install -y python3 && apt install -y curl && 0.0s => [ 5/12] RUN . "/root/.nvm/nvm.sh" && nvm install --lts 38.0s => [ 6/12] RUN . "/root/.nvm/nvm.sh" && nvm use --lts 5.3s => [ 7/12] RUN . "/root/.nvm/nvm.sh" && nvm alias default v14.7.4 4.3s => [ 8/12] RUN node --version 1.8s => [ 9/12] RUN npm --version 1.2s => [10/12] RUN npm install --global yarn 3.8s => [11/12] RUN echo "run 'yarn install'" … -
Single search bar managing all fields using django-filter and django-tables2 through Jquery
I need to manage the django-table2 using django-filter through jquery. Please help me how can i access this via jquery and how do i pass queryset in django-filter I am having my search box in the following way: where I am passing models in a dynamic way since I am using it in generic purpose. <input type="hidden" name="model_name" value="{{view.class_name}}" id="model_name"> <input type="text" name="search_data" id="search_data" class=" search_data form-control pl-4" placeholder="Search..." value="{{search_key}}"> The script I use $('.search_data').keyup(function(){ var search_key = $.trim($(this).val()); model_name = $('#model_name').val(); url = '/org/' + model_name.toLowerCase() + '/?search_key='+search_key window.location = url }); And here I am using the dynamic List view def generate_views(model_type): friendly = model_type.__name__.lower() app_label = model_type._meta.app_label admin_class = admin.site._registry.get(model_type) if admin_class and not admin_class.form == ModelForm: _form_class = admin_class.form else: _form_class = forms.generate_form(model_type) class ListView( mixins.LoginRequiredMixin, mixins.PermissionRequiredMixin, FilterView, ExportMixin, SingleTableView, ): class_name = model_type.__name__ permission_required = [f'{app_label}.view_{friendly}'] template_name = f'generic/object_list.html' model = model_type filterset_class = filters.generate_filterset(model_type) table_class = tables.generate_table(model_type) table_pagination = { 'per_page': settings.DJANGO_TABLES2_PER_PAGE } def get_context_data(self, **kwargs): context = super(ListView, self).get_context_data(**kwargs) search_key = self.request.GET.get('search_key', '') if search_key: context['search_key'] = search_key return context def get_queryset(self): search_key = self.request.GET.get('search_key', '') fields = filters.build_fields(model_type) queryset = model_type.objects.all() if search_key: for field in fields: lookup = "%s__contains" % field … -
Return context variable along with saved form
I have following class based view which creates a project using form and then returns that created form. class ProjectCreateView(LoginRequiredMixin, CreateView): login_url = "registration:login" model = Project # fields = ['name', 'desc', 'start_date', 'end_date'] template_name = 'project/form.html' form_class = ProjectModelForm def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) # Add in a QuerySet of all the books context['projectCreated'] = True return context def form_valid(self, form): form.instance.user = self.request.user project_name=form.cleaned_data.get('name') print("Project name-------------+++++++++++"+str(project_name)) namesTaken=Project.objects.values_list('name', flat=True) if project_name in namesTaken: return self.render_to_response(self.get_context_data(form=form,projectNameRepeated=True)) ''' else: context={"projectCreated":True,"saved":super().form_valid(form)} return self.render_to_response(context) ''' #context = {'form':super().form_valid(form)} #form=super().form_valid(form) #return self.render_to_response(self.get_context_data(form=form,datasetNameRepeated=True)) return super().form_valid(form) Now I want to return a context which is ProjectCreated=True. This is context is being return even before the form is submitted and the project is created. But I need to return it after the project has been create because then I will display an alert in my template base.html {% elif DatasetCreated %} <script> displayToast("Dataset","Dataset Created Successfully"); </script> {% endif%} following is url code path('create/', views.ProjectCreateView.as_view(), name='create'), So basically I am looking for a way to return a context when the project is saved in database or after form is successfully submitted. Thanks -
'verbose_name': _('Small screens') NameError: name '_' is not defined
After installation django-responsive2 as django-responsive2, i got following error: 'verbose_name': _('Small screens') NameError: name '_' is not defined -
Converting my Django/Python app from App Engine Standard Environment to Flexible Environment
I am trying to convert my Django/Python app from the Google App Engine Standard Environment to the Flexible environment mainly due to the app becoming slow and was constantly hitting a soft memory limit and suggested I upgrade to a larger instance class. I was already at the highest instance class. My problem is when I try to deploy the build is successful but I keep getting an error when Updating service. "Your deployment has failed to become healthy in the allotted time and therefore was rolled back. If you believe this was an error, try adjusting the 'app_start_timeout_sec' setting in the 'readiness_check' section." I've tried adjusting the readiness_check section to allow more time but it just takes longer to give me the same error it seems.I've tried googling this issue and adding more memory but the same error still shows. I'm stuck at this point and I'm not sure where else to look. Here is the app.yaml that successfully deployed on the standard environment entrypoint: gunicorn -b :$PORT xpotools.wsgi instance_class : F4_1G automatic_scaling: min_instances: 5 min_pending_latency: 30ms max_pending_latency: 4s max_concurrent_requests: 20 min_idle_instances: 3 inbound_services: - warmup handlers: - url: /static static_dir: static/ secure: always - url: /.* script: auto … -
How i can wrap json response data for djago-rest-framework?
I use djano rest framework. I have model, serializer and view: class PictureModel(models.Model): id = models.AutoField(primary_key=True) url = models.CharField(max_length=256) class PictureView(mixins.ListModelMixin, generics.GenericAPIView): serializer_class = PictureSerializer queryset = PictureModel.objects.all() def get(self, request): return self.list(request) class PictureSerializer(serializers.ModelSerializer): class Meta: model = PictureModel fields = '__all__' get request return json : [ { "id": 120525, "url": "https://ddd.com/upload/iblock/579/5797cc881f8790926cee4a8fc790d1bd.JPG" }, { "id": 120526, "url": "https://ddd.com/upload/iblock/382/382526e1deee07f60871430bd806aa71.JPG" } ... ] But i need wrap this data to { "success": 1, "data": [ { "id": 120525, "url": "https://ddd.com/upload/iblock/579/5797cc881f8790926cee4a8fc790d1bd.JPG" }, { "id": 120526, "url": "https://ddd.com/upload/iblock/382/382526e1deee07f60871430bd806aa71.JPG" } ... ] How i can do it? I can use middleware for it but i don't know how i can edit response data. Middleware apply for all requests but i need apply it not for all. May be I can use my renderer but I don't know how. P.S. Also I use swagger documentation auto generator.