Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Serving static files with NGINX and DJANGO
I'm new to programming and I've managed to build my father a website where he can showcase his photography, I recently had to switch from shared hosting to my own VPS that uses ubuntu to give me more control and access to latest pips. I've had everything working on local server regarding static files, everything uploads where it is meant to(for me it was static/media). In production I've got my website running perfectly other than any css working for my templates or even admin panel and images not showing. I have ran the following commands to get where I am, I will so share some code and screenshots of current configuration also. Image folders are also been created rather than images going into media folder. Images in browser have extensions image/image/test4 also. DEBUG = False sudo chown -R www-data:www-data /home/dave/mhprints/static sudo chmod -R 777 /home/dave/mhprints/static sudo chown -R www-data:www-data /home/dave/mhprints/staticfiles sudo chmod -R 777 /home/dave/mhprints/staticfiles sudo chmod -R 777 /var/www/staticfiles sudo chmod -R 777 /var/www/staticfiles I have ImageField set with upload_to='media' Current mapping of my project Mapping of VAR folder ROOTS AND URLS in settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/media') STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS … -
Recommend API SMS notification that will send to certain user from sqlite using Python and Django: AdminLTE
I have a management system, and I really need good SMS notifications. I'm using Python and Django's AdminLTE to embed and utilize sms notifications for a specific user from SQlite. I have tried to install twilio but it doesn't select or get from sqlite. -
django wizard form not working with bootstrap
I have a page that use bootstrap css for styling which is working fine, but when I add a django wizard form to this html page, all the bootstrap css disappear but other normal css file still working fine. html form {% load i18n %} {% load crispy_forms_tags %} {% load static %} {{ wizard.form.media }} <p>Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}</p> <form action="" method="post">{% csrf_token %} <table> {{ wizard.management_form }} {% if wizard.form.forms %} {{ wizard.form.management_form }} {% for form in wizard.form.forms %} {{ form.as_table }} {% endfor %} {% else %} {{ wizard.form }} {% endif %} </table> {% if wizard.steps.prev %} <button name="wizard_goto_step" type="submit" value="{{ wizard.steps.first }}">{% trans "first step" %} </button> <button name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}">{% trans "prev step" %} </button> {% endif %} <input type="submit" value="{% trans " submit" %}"/> </form> views.py class indexForm(SessionWizardView): template_name = "main/indexform.html" form_list = [FormStepOne, FormStepTwo] def done(self, form_list, **kwargs): data_for_step1 = self.get_cleaned_data_for_step('0') data_for_step2 = self.get_cleaned_data_for_step('1') print(data_for_step1) print(data_for_step2) return render(self.request, 'main/done.html', { 'form_data': [form.cleaned_data for form in form_list], }) urls.py path('indexform/', indexForm.as_view(), name='indexform'), I am not sure why my bootstrap css are not loading when others css file are loading correctly when adding the wizzard form -
AttributeError: 'Doctor' object has no attribute 'comments'
I'm working on this project but I got the following error comm = doctor_detail.comments.filter(active=True) AttributeError: 'Doctor' object has no attribute 'comments' however I think that everything is alright this is my models.py class Comments(models.Model): co_name = models.CharField(max_length=50, verbose_name="الاسم ") co_email = models.EmailField( max_length=50, verbose_name="البريد الالكتروني") co_body = models.TextField(max_length=400, verbose_name='التعليق') created_dt = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=True) post = models.ForeignKey( User, on_delete=models.CASCADE, related_name='comments') def __str__(self): return 'علق {} على {}'.format(self.co_name, self.post) this is my views.py def doctor_detail(request, slug): # استدعاء جميع البينات اللي في البروفايل doctor_detail = get_object_or_404(Doctor, slug=slug) comm = doctor_detail.comments.filter(active=True) form = Commentair() if request.method == 'POST': form = Commentair(data=request.POST) if form.is_valid(): new_comment = form.save(commit=False) new_comment.post = doctor_detail new_comment.save() form = Commentair() else: form = Commentair() return render(request, 'user/doctor_detail.html', {'doctor_detail': doctor_detail, 'comm': comm,'form': form }) I really don't know why I'm facing this error because the related name is available and I think everything is okay .please if there is an answer to this write it and explain it to me. thank you -
how to render values from multiple methods in table format in template django
I have a django app. And I have two methods: def total_cost_fruit(self): return [3588.20, 5018.75, 3488.16] def total_cost_fruit2(self): return [3588.20, 5018.75, 3488.99] And I try to render them as table. so this is the views.py: def test(request): values1 = filter_text.total_cost_fruit() values2 = filter_text.total_cost_fruit2() context = { "values1": values1, "values2": values2, "all_values": list(chain(values1, values2)), } return render(request, "main/test.html", context) and template: <div class="wishlist"> <table> <tr> <th>Method 1</th> <th>Method 2</th> </tr> {% for value in all_values %} <tr> <td>{{value.0}}</td> <td>{{value.1}}</td> </tr> {% endfor %} </table> </div> But nothing is displayed -
Perform post request using Django rest framework
I've got a Django rest framework APIView: class MyAPIView(views.APIView): def post(self, request): field = request.POST.get("field") print(field) return Response({"field": field}, status=200) I want to call it from separate process using Django API. I do it like this: request = HttpRequest() request.method = "POST" request.POST = QueryDict(mutable=True) request.POST["field"] = "5" response = MyAPIView.as_view()(request=request) But when field is being printed in MyAPIView it's always None. How to call post method using Django? -
Django - file upload not working on mysql and postgres but working on sqlite
I have a strange problem in my Django application. I have a front end file upload form in which user has to login and upload Excel file which will communicate with select box. The problem is that the file uploading is working on sqlite on local server and apache server on my vps. But its not working if I change my database to Postgres or Mysql. Sentry.io showing me this error (check image). MY code : ` <main class="bg-white container mb-3 mt-3 pb-3 pt-2 rounded rounded-2 text-dark"> <div class=" row justify-content-center"> <div class="medium-4 columns"> <h3 class="fw-bold m-5 text-danger text-center">Application Upload Form</h3> </div> <div class="col-md-7 columns medium-4 ms-5"> <div class="mb-3 rounded rounded-1"> <label for="formFile" class="form-label fw-bold">Generated Lot Number</label> <div id="lotnumberhashdiv" style="display:none">{{lot_hash}}</div> <p id="lotnumberdiv" class="bg-secondary p-4 rounded rounded-1 text-light">{{lotnumber}}</p> </div> <form id="upload-data-form" method="post"> {% csrf_token %} <div class="card rounded-1"> <div class="card-body"> <div class="mb-3"> <label for="fileSelect" class="form-label fw-bold">Choose File (only Excel/Csv)</label> <input class="form-control" name="file" id="excelfileinput" type="file" accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" required> </div> <div class="mb-3"> <label for="formFile" class="form-label fw-bold">Choose Template</label> <select id="selecttemmplatetype" name="template" class="form-select" aria-label="Default select example" required> {% for template in template_types %} <option>{{template.template_name}}</option> {% endfor %} </select> </div> <button type="button" class="btn btn-lg btn-primary w-100" onclick="upload_data()" id="submitbutton">Submit Form</button> </div> </div> </form> </div> <!-- <div … -
dockerfile for selenium. 255 driver initialization error
There is a part of django that sends information via an API to be processed by selenium. There are problems with building docker under selenium. 255 selenium error in logs. I've already broken my head. Please tell me what could be the problem. latest version of geckodriver dockerfile FROM python:3.9 LABEL autor="LOADER" LABEL description="APP" WORKDIR /usr/src/html_loader/ COPY . /usr/src/html_loader/ RUN apt-get update RUN echo "Y" | apt-get install alien RUN echo "Y" | apt-get install gunicorn RUN echo "Y" | apt-get install memcached RUN echo "Y" | apt-get install unixodbc RUN echo "Y" | apt-get install unixodbc-dev RUN echo "Y" | apt-get install cifs-utils RUN echo "Y" | apt-get install libgtk-3-dev RUN echo "Y" | apt-get install libgtk-3-0 RUN echo "Y" | apt-get install libdbus-glib-1-2 RUN echo "Y" | apt-get install xvfb RUN apt-get install libaio1 RUN echo "deb http://deb.debian.org/debian/ unstable main contrib non-free" >> /etc/apt/sources.list.d/debian.list RUN apt-get update RUN echo "Y" | apt-get install -y --no-install-recommends firefox RUN apt-get update && apt-get install -y wget bzip2 libxtst6 libgtk-3-0 libx11-xcb-dev libdbus-glib-1-2 libxt6 libpci-dev && rm -rf /var/lib/apt/lists/* ENV pip=pip3 ENV python=python3 ENV DJANGO_HOST="http://crawlerdjango:4333" RUN pip install --upgrade pip COPY requirements.txt . RUN pip3 install -r requirements.txt RUN apt-get update --allow-releaseinfo-change … -
401 Client Error: Unauthorized for url [mozilla-django-oidc - Keycloack]
I'm trying to integrate Django and Keycloack using mozilla-django-oidc, but unfortunately I'm not having much success as I keep getting 401 Client Error: Unauthorized for url... I created a docker compose that runs Keycloack / KeycloackDB / Django app, like the following docker-compose.yaml version: '3' volumes: postgres_data: driver: local services: postgres: image: postgres volumes: - postgres_data:/var/lib/postgresql/data environment: POSTGRES_DB: keycloak POSTGRES_USER: keycloak POSTGRES_PASSWORD: password networks: - local-keycloak keycloak: image: quay.io/keycloak/keycloak:latest environment: DB_VENDOR: POSTGRES DB_ADDR: postgres DB_DATABASE: keycloak DB_USER: keycloak DB_SCHEMA: public DB_PASSWORD: password KEYCLOAK_ADMIN: admin KEYCLOAK_ADMIN_PASSWORD: Pa55w0rd ports: - "8080:8080" depends_on: - postgres command: - "start-dev" networks: - local-keycloak volumes: - .local/keycloak/:/opt/keycloak/data web: build: context: . ports: - "8000:8000" depends_on: - postgres - keycloak volumes: - .:/app networks: - local-keycloak networks: local-keycloak: I setup my Django project as described in https://mozilla-django-oidc.readthedocs.io/en/stable/installation.html#quick-start settings.py .... AUTHENTICATION_BACKENDS = ( "django.contrib.auth.backends.ModelBackend", "mozilla_django_oidc.auth.OIDCAuthenticationBackend", ) BASE_URL = "http://localhost:8080" KEYCLOACK_IP = "http://192.168.192.3:8080" OIDC_RP_SIGN_ALGO = "RS256" OIDC_OP_JWKS_ENDPOINT = f"{KEYCLOACK_IP}/realms/demo/protocol/openid-connect/certs" OIDC_RP_CLIENT_ID = os.environ['OIDC_RP_CLIENT_ID'] OIDC_RP_CLIENT_SECRET = os.environ['OIDC_RP_CLIENT_SECRET'] OIDC_OP_AUTHORIZATION_ENDPOINT = f"{BASE_URL}/realms/demo/protocol/openid-connect/auth" OIDC_OP_TOKEN_ENDPOINT = f"{KEYCLOACK_IP}/realms/demo/protocol/openid-connect/token" OIDC_OP_USER_ENDPOINT = f"{KEYCLOACK_IP}/realms/demo/protocol/openid-connect/userinfo" LOGIN_REDIRECT_URL = "/" LOGOUT_REDIRECT_URL = "/" views.py from django.http import HttpResponse from django.contrib.auth.decorators import login_required from django.template import loader def index(request): template = loader.get_template('index.html') return HttpResponse(template.render({}, request)) index.html {% if user.is_authenticated %} <p>Current user: {{ … -
Is django data migration immediately applied?
I read the following text on docs: """ Django’s default behavior is to run in autocommit mode. Each query is immediately committed to the database, unless a transaction is active. See below for details. """ and I'm running the following data migration: def fill_query(apps, schema_editor): Result = apps.get_model('monitoring', 'Result') for r in Result.objects.all(): r.query = r.monitored_search.query r.user_id = r.monitored_search.user_id r.save() class Migration(migrations.Migration): dependencies = [ ('monitoring', '0006_searchresult_user_id'), ] operations = [ migrations.RunPython(fill_query), ] But when I try to find objects from Result I found that all still have query and user_id as null. And my data migration keep running (more than 2 millions registers on database) maybe the changes will be applied when data migration stop running or my data migration is not working? -
Creating date counter using javascript in django
Actually, I have a running counter, but when I pull the data with for, a few data comes in and while it should work in each of them, this counter works in only one of them, what should I change, here are my codes:enter image description here -
How to create a statefull Django API server?
I'm creating an API using Django, which receives an image, analyzes it using some AI models, and returns the result. The models are pretty heavy, so I want to load them only once on the application start and keep them in the memory. The models are encapsulated in a class, so my idea is to create a global object being an instance of this class and use it inside of the view. Is it the way to go? If so, where to keep this object? The only possibility that comes to my mind is the views.py file. What is the best way to achieve this? Thanks in advance! -
Embedding real-time Grafana dashboards in Django web application
I want to embed a real-time grafana dashboard into my django web application. Currently, I have embedded the individual panels of the dashboard in my django applications using the iframe link that is generated by grafana, but they are just a snapshot of the graph and the individual panels do not scroll automatically to the current time. -
Django Windows not working, how do I fix it?
I installed Python on Windows so I can install Python packages and Django was one of them. Installation command: pip install Django After installation, I decided to open up Django Django but I got an error saying: Django: The term 'Django' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. -
How to do web scraping with django
I am developing a backend in django and I want to make an api that retrieves data from a web. I scraped with selenium but I don't know how to import it into a django view. -
'psycopg2.errors.UndefinedTable: relation "table" does not exist' when makemigrations
I have a django app and I am trying to migrate from sqlite3 to postgres. I have been following multiples guides on how to do this, and they all do more or less the same and those are the steps I followed: Get a dumpdata with python manage.py dumpdata > whole.json Create db and user and connect to it Config settings.py to set everything to the new database Delete old migrations run python manage.py makemigrations or python manage.py migrate --run-syncdb There are more steps, but I am stuck in this 5th one getting 'psycopg2.errors.UndefinedTable: relation "table" does not exist' Looking for solutions I've come to this post which may help someone, though I might not doing it right or something but commenting models have done nothing for me. Thanks. -
how to render values from multiple methods vertically in template django
I have a django application. And I try to render the values from different methods vertical in the template. So I have this two methods combined in one method: class FilterText: def total_cost_fruit(self): return [3588.20, 5018.75, 3488.16] def total_cost_fruit2(self): return [3588.20, 5018.75, 3488.99] def show_extracted_data_from_file(self): return self.total_cost_fruit() , self.total_cost_fruit2() and views.py: def test(request): content_pdf = "" content_pdf = filter_text.show_extracted_data_from_file() context = { "content_pdf": content_pdf, } and template: <div class="wishlist"> <ul class="nobull"> {% for value in content_pdf %} <span {% if value in diff_set %} style="color: red;" {% endif %}> <li>{{value}}</li> </span> {% endfor %} </ul> </div> But at the moment it displays: [3588.2, 5018.75, 3488.16] [3588.2, 5018.75, 3488.99] But I want to have them to display like: 3588.2 3588.2, 5018.75 5018.75 3488.16 3488.99 So next to ech other. Question: how to display the values next to each other? -
using register_converter() on all ModelViewSet viewsets
Is there a way to use path converters with ModelViewSet without explicitly writing the path urls ? For example I have this path converter: from .utils import REGEX from . import encode_id, decode_id class HashidsConverter(): regex = REGEX def to_python(self, value: str) -> int: return decode_id(value) def to_url(self, value: int) -> str: return encode_id(value) in urls.py file router = DefaultRouter() router.register("client", ClientModelViewSet) register_converter(HashidsConverter, "hashid") urlpatterns = [ path('admin/', admin.site.urls), #path('', include(router.urls)), path('client/<hashid:pk>', ClientModelViewSet.as_view({"get":"retrieve"}), name="client") ] -
get a dictionary variable to use it in the same dictionary to get the file extension django python
I am creating a folder tree to display it. For this I need to get the file extension. Before the folder we nedd to enter a pasword. my views.py ` def www_telechargements(request): if request.method == 'POST': # create a form instance and populate it with data from the request: form = CatalogueForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required # ... # redirect to a new URL: context = { 'mdp': form.cleaned_data["response_mdp"] } good_answer = ("\n".join(context.values())) if good_answer == "Vitasolar1234": template = loader.get_template('telechargement-response.html') arborescence_path = os.path.join(BASE_DIR, "WWW/static/arborescence") arborescence_content = os.listdir(arborescence_path) response_gabarit = { 'answer': True, 'dossier': arborescence_content, 'type': pathlib.Path(os.listdir(response_gabarit('dossier')).suffix)#c'est ici que je veux récupérer le string de 'dossier' } print(os.listdir(arborescence_path)) return HttpResponse(template.render(response_gabarit, request)) else: response_gabarit = {'answer': False} template = loader.get_template('telechargement-response.html') return HttpResponse(template.render(response_gabarit, request)) # if a GET (or any other method) we'll create a blank form else: form = CatalogueForm() return render(request, 'telechargements.html', {'form': form}) this is my mistake : 'type': pathlib.Path(os.listdir(response_gabarit('dossier')).suffix) UnboundLocalError: local variable 'response_gabarit' referenced before assignment I would like to get the string 'dossier' but it is not possible I understand my mistake but I have no idea how to solve this problem I tried to use my … -
How to speed-up (avoid) django boot time when running tests?
When I write django tests, I frequently run then manage.py tests command. To increase test run performance I'm aware of --keepdb and --parallel options. I'm also aware of being able to run a specific test by targeting it. I usually run something like this : manage.py tests myapp.tests.test_file.MyTestCase.test_my_test --keepdb The problem is that each time I run the command, django took few seconds (around 10 seconds in the current project) just to boot-up and start processing the tests. So during a test development I have to wait 10 seconds each time whereas the test itself took 1 second. There is a way to enter a sort of "test mode" which keep django booted-up ? So that I can run tests without to wait for 10 seconds boot time after each code modification. -
Django sub-query in Case When
I have such query qty_used_annotation = Case( When(scope='ticket', then=BookedTicket.objects.filter( global_discount_code__code=F('code'), booking__status__in=['i', 'c', 'g', 'r', 's'] ).count()), When(scope='booking', then=Booking.objects.filter( bookedticket__global_discount_code__code=F('code'), status__in=['i', 'c', 'g', 'r', 's'] ).count()), output_field=IntegerField() ) And it is not working. The error is Cannot resolve keyword 'code' into field. Can somebody explain how to fix it or why it is not working. Thanks -
passing django variables as parameters into href url
On my home page i want to have 3 links that will redirect the user to a page ('127.0.0.1:8000/person/<str:name>') which will display the name that they clicked. I would like to use a for loop to create links for these names as i plan to have much more than 3 names. I have tested with the two methods (for loop / manually writing out all of the links) but can't get the for loop to work. I thought these two methods below would produce the same result. <h2>does not work</h2> {% for person in people %} <a href="{% url 'person' '{{person}}' %}">{{person}}</a> {% endfor %} <h2>works</h2> <a href="{% url 'person' 'logan' %}">logan</a> <a href="{% url 'person' 'paul' %}">paul</a> <a href="{% url 'person' 'nicola' %}">nicola</a> What the urls look like in page source: views.py def home(request): return render(request, "APP/home.html", context={"people":['logan', 'paul', 'nicola']}) def person(request, name): return render(request, 'APP/person.html', context={"name":name}) urls.py urlpatterns = [ path('home/', views.home, name='home'), path('person/<str:name>/', views.person, name='person'), ] -
Django Haystack update index only for 1 model
I am currently trying out Django haystack to update data from PostgreSQL to a solr collection. So, I have defined 2 models in search_indexes.py. So, when I run the command python manage.py update_index it indexes the data from both the models defined in search_indexes.py to my solr collection. HOW DO I PERFORM update_index OPERATION ONLY FOR A SPECIFIC MODEL THAT I NEED? Currently, when I run the command, the following 2 models ran. Indexing 2 model1 Indexing 12 model2 search_indexes.py from haystack import indexes from .models import table1, table2 class model1(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField( document=True, use_template=True, template_name="search/indexes/tenants/table1_text.txt" ) ats_id = indexes.CharField(model_attr='ats_id') ats_name = indexes.CharField(model_attr='ats_name') added_by = indexes.CharField(model_attr='added_by') added_on = indexes.DateTimeField(model_attr='added_on') def get_model(self): return table1 def index_queryset(self, using=None): return self.get_model().objects.all() class model2(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField( document=True, use_template=True, template_name="search/indexes/tenants/table2_text.txt" template_id = indexes.CharField(model_attr='template_id') template_name = indexes.CharField(model_attr='template_name') aspect = indexes.CharField(model_attr='aspect') version = indexes.CharField(model_attr='version') added_by = indexes.CharField(model_attr='added_by') added_on = indexes.DateTimeField(model_attr='added_on') ats_id = indexes.CharField(model_attr='ats_id') def get_model(self): return table2 def index_queryset(self, using=None): return self.get_model().objects.all() Please suggest a workaround. -
How to post manytomany field value in Postman for API
I have a field which is ManyToMany. I would like to enter the value in POSTMAN for API post operation. But everytime It says: "This field is required." even though I provided the value. Serializer: class DaySerializer(serializers.ModelSerializer): class Meta: model = Day fields = '__all__' class TutorProfileSerializer(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField( read_only=True, default=serializers.CurrentUserDefault(), source='user.username') image_url = serializers.SerializerMethodField('get_image_url') tutor_availablility = DaySerializer(many=True) class Meta: model = TutorProfile fields = '__all__' -
Best practice for testing a django project
I have a django project with 3 apps. Now, I want to test my project. So I was in dilemma that what should be the best practice for testing a Django project with pytest? Which approach is preferable ? Approach 1 : └── app_name └── tests ├── __init__.py ├── test_forms.py ├── test_models.py └── test_views.py Approach 2 : └── app_name └── tests ├── __init__.py ├── unit_tests ├── __init__.py ├── test_views.py ├── test_models.py ├── test_forms.py ├── integration_tests ├── __init__.py ├── test_views.py ├── test_models.py ├── test_forms.py ├── functional_tests ├── __init__.py ├── test_views.py ├── test_models.py ├── test_forms.py Note : We are using pytest here. What I am expecting is which approach should be followed while testing a django project