Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to ran a function some time after the user enterd the url? Django
I have a page that 10 seconds after the user enterd a change to the database is made, how do i do that? I need to add this idea to both a class based view and a regular view. -
DRF nested through model serialization filtering
Each of my models is inherited from the base model, which contains the publishing_status field that helps me control whether or not the object is included in the returned data. class BaseModel(models.Model): class PublishingStatus(models.TextChoices): ACCEPTED = 'accepted', 'Accepted' REJECTED = 'rejected', 'Rejected' publishing_status = models.CharField( max_length=9, choices=PublishingStatus.choices, default=PublishingStatus.DRAFT, help_text="Publishing status represents the state of the object. By default it is 'draft'" ) class Meta: abstract = True Here are two models Word and Homonym they both inherit from BaseModel: class Word(BaseModel): definition = models.CharField(max_length=255) homonyms = models.ManyToManyField('self', through='Homonym', through_fields=('homonym', 'word')) class Homonym(BaseModel): homonym = models.ForeignKey(Word, on_delete=models.CASCADE) word = models.ForeignKey(Word, on_delete=models.CASCADE) Homonyms are basically words too, so I have self-reference here, but through the model Homonym so that I could control these relationships to be public or not for my website. Then follow the serializers and probably the solution should be passed here: class HomonymSerializer(serializers.ModelSerializer): class Meta: model = Homonym fields = '__all__' class WordSerializer(serializers.ModelSerializer): homonyms = HomonymSerializer(many=True) class Meta: model = Word fields = '__all__' Question: Currently, all homonyms are displayed, regardless of whether they are accepted or not. How can I restrict the nested serializer to include only homonyms with the publishing_status="accepted"? Here is my view: class WordRetrieveView(RetrieveAPIView): serializer_class … -
Programmatically trigger password reset in Django 3.2
The method detailed here no longer works. Importing django.contrib.auth.forms.PasswordResetForm results in the custom user class not being available (django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'accounts.CustomUser' that has not been installed). How do I send these emails programmatically? To avoid the X-Y Problem: I don't want user registration. I want admins to be able to create users by supplying an email address, at which point the user receives a password reset email. Upon resetting (more accurately, creating) a password, the user can log in and set a display name and other attributes. -
Django Elastic serach deleting some documents when pointing multiple documents to the same index
I have my django application where i am using django_elasticsearch_dsl to index document to later do elastic search with them. I have two similar models in database so i want the documents to be pointing to the same index in elastic search so later i can do a search with both of them like they are the same. Righ now my setup is like this @registry.register_document class HelpCenterDocument(Document): title = TextField() url = ESTextField('get_absolute_url') site_id = ESIntegerField('site_id') class Index: name = 'help-center-index' class Django: model = HelpCenterPage fields = ['title', 'content'] @registry.register_document class PageDocument(Document): title = TextField() url = TextField('get_public_url') class Index: name = 'global-search-page-index' using = 'global_search' class Django: model = Page When i do manage.py search_index --rebuild it will say that it created Indexing 90 'HelpCenterPage' objects Indexing 213 'Page' objects So with this my index should have 303 documents, this is not the case when i look at the count it shows i have "docs": { "count": 239, "deleted": 64 }, If i comment one of the @registry.register_document the count will be ok, but if i let both of them uncommented it will index only some of them These are the index stats { "_shards": { "total": … -
How to get all values from a Model instance on django
I'm using django signals with post_save and receiving an instance: @receiver(post_save, sender=ServiceOrder) def service_order_post_save(sender, instance, created, **kwargs): if created: print(instance) I just want to get all values from this instance without doing field per field (is a big Model). I tried: instance.objects.values() instance.values() list(instance) as expected all trys failed. -
How can I setup multiple Django Apps using Supervisor (including Gunicorn and Nginx)? bind() to [::]:8090 failed (98: Address already in use)
I already deployed a Django/Wagtail App using Supervisor, Gunicorn and Nginx (on Debian Buster), so I can reach it with http://xx.xxx.xxx.xxx:8090. /etc/nginx/sites-available/cms server { server_name xx.xxx.xxx.xxx; listen 8090; listen [::]:8090 ipv6only=on; error_log /home/www.mysite.com/.local/share/virtualenvs/cms-WqsZ9qOt/var/log/gunicorn-error.log; access_log /home/www.mysite.com/.local/share/virtualenvs/cms-WqsZ9qOt/var/log/gunicorn-access.log; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/www.mysite.com/www/my-site/cms/admin_panel; } location /media/ { root /home/www.mysite.com/www/my-site/cms/admin_panel; } location / { include proxy_params; proxy_pass http://unix:/home/www.mysite.com/.local/share/virtualenvs/cms-WqsZ9qOt/run/gunicorn.sock; } } /etc/supervisor/conf.d/guni-mysite-admin.conf [program:guni-mysite-admin] command=/home/www.mysite.com/.local/share/virtualenvs/cms-WqsZ9qOt/bin/gunicorn admin_panel.wsgi:application --config /home/www.mysite.com/.local/share/virtualenvs/cms-WqsZ9qOt/etc/gunicorn/conf.py user=www.mysite.com autostart=true autorestart=true /etc/supervisor/conf.d/nginx-mysite-admin.conf [program:nginx-mysite-admin] command=/usr/sbin/nginx -g "daemon off;" autostart=true autorestart=true stderr_logfile=/home/www.mysite.com/.local/share/virtualenvs/cms-WqsZ9qOt/var/log/nginx-error.log stdout_logfile=/home/www.mysite.com/.local/share/virtualenvs/cms-WqsZ9qOt/var/log/nginx-access.log stderr_logfile_maxbytes=2MB stdout_logfile_maxbytes=2MB /home/www.mysite.com/.local/share/virtualenvs/cms-WqsZ9qOt/etc/gunicorn/conf.py workers = 3 keepalive = 5 user = 'www.mysite.com' proc_name = 'admin_panel' loglevel = 'error' errorlog = '/home/www.mysite.com/.local/share/virtualenvs/cms-WqsZ9qOt/var/log/gunicorn-error.log' accesslog = '/home/www.mysite.com/.local/share/virtualenvs/cms-WqsZ9qOt/var/log/gunicorn-access.log' bind = 'unix:/home/www.mysite.com/.local/share/virtualenvs/cms-WqsZ9qOt/run/gunicorn.sock' raw_env = ['DJANGO_SETTINGS_MODULE=admin_panel.settings.production'] pythonpath = '/home/www.mysite.com/www/mysite/cms/admin_panel' Now I added 2 more Django Apps the same way. Unfortunately Supervisor can´t bring them up. Sometimes 1 out of 3 runs, but most of the time none of them work. In case it works it creates 3 processes (idk if that´s how it is supposed to be). $ sudo lsof -i:8090 COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME nginx 3631 root 16u IPv4 961301189 0t0 TCP *:8090 (LISTEN) nginx 3631 root 17u IPv6 961301190 0t0 TCP *:8090 (LISTEN) nginx 3632 … -
Getting error when trying run test "RuntimeError" Database access not allowed
I am facing below error ERROR: Database access does not allow def send_orders(): for order in Order.objects.all(): order.send() order.sent = True #factories.py class OrderFactory(....): amount = 100 sent = False #test_order.py def test_send_orders(order): send_orders() assert order.sent -
Django get current model id after model form save & redirect it with this pk to set as fk to another models fk in model form
Working on Django 3.2 & unable to save forms with reference to each other. Like Project>Photos>Assignments>Students every form is a model form & has a relationship with each other. I have one Project Model & Another is Photos, want to get id of project after save & redirect user next model form "Photos" with project id reference where project_id is FK in Photos Model & should be assigned automatically, Can someone please help on this. here is what I have tried. I'm looking for url somethig like this: URL for add project: http://example.com/projects/add-project URL for upload photos project: http://example.com/projects/1/upload-photos #urls.py path('add-project', views.submit_project, name='submit_project'), path('<int:project_id>/upload-photo/', views.upload_media, name='upload_media'), #model.py code class Project(models.Model): owner = models.ForeignKey(User, on_delete=models.PROTECT, null=True, blank=True, related_name='project_owner') title = models.CharField(max_length=200) #Photo Model class ProjectMedia(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) photo1 = models.ImageField(upload_to='projects/media/', null=True, blank=True) #Views.py def submit_project(request): if (request.user.is_authenticated): if request.method == 'POST': form = SubmitProjectForm(request.POST, request.FILES) if form.is_valid(): title = form.cleaned_data['title'] project = Project(title=title) project = form.save(commit=False) project.owner_id = request.user.id project.save() messages.success( request, 'Thank you! Your project has been submitted.') else: form = SubmitProjectForm() context = { 'form': form, } return render(request, 'add-project.html', context) #Photo submit view def upload_media(request, project_id): project = get_object_or_404(Project, pk=project_id) if request.method == 'POST': form = … -
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